blob: 4680bcd11d078cea7e4ebc8d2e51bcca9b76098b [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044
Chris Lattnera26fb342009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000047 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
48 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000049}
50
John McCallbebede42011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerouge4a5b4442012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000096 return false;
97}
98
Richard Smith6cbd65d2013-07-11 02:27:57 +000099/// Check that the argument to __builtin_addressof is a glvalue, and set the
100/// result type to the corresponding pointer type.
101static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
102 if (checkArgCount(S, TheCall, 1))
103 return true;
104
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000105 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000106 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
107 if (ResultType.isNull())
108 return true;
109
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000110 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000111 TheCall->setType(ResultType);
112 return false;
113}
114
John McCall03107a42015-10-29 20:48:01 +0000115static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
116 if (checkArgCount(S, TheCall, 3))
117 return true;
118
119 // First two arguments should be integers.
120 for (unsigned I = 0; I < 2; ++I) {
121 Expr *Arg = TheCall->getArg(I);
122 QualType Ty = Arg->getType();
123 if (!Ty->isIntegerType()) {
124 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
125 << Ty << Arg->getSourceRange();
126 return true;
127 }
128 }
129
130 // Third argument should be a pointer to a non-const integer.
131 // IRGen correctly handles volatile, restrict, and address spaces, and
132 // the other qualifiers aren't possible.
133 {
134 Expr *Arg = TheCall->getArg(2);
135 QualType Ty = Arg->getType();
136 const auto *PtrTy = Ty->getAs<PointerType>();
137 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
138 !PtrTy->getPointeeType().isConstQualified())) {
139 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
140 << Ty << Arg->getSourceRange();
141 return true;
142 }
143 }
144
145 return false;
146}
147
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000148static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
149 CallExpr *TheCall, unsigned SizeIdx,
150 unsigned DstSizeIdx) {
151 if (TheCall->getNumArgs() <= SizeIdx ||
152 TheCall->getNumArgs() <= DstSizeIdx)
153 return;
154
155 const Expr *SizeArg = TheCall->getArg(SizeIdx);
156 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
157
158 llvm::APSInt Size, DstSize;
159
160 // find out if both sizes are known at compile time
161 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
162 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
163 return;
164
165 if (Size.ule(DstSize))
166 return;
167
168 // confirmed overflow so generate the diagnostic.
169 IdentifierInfo *FnName = FDecl->getIdentifier();
170 SourceLocation SL = TheCall->getLocStart();
171 SourceRange SR = TheCall->getSourceRange();
172
173 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
174}
175
Peter Collingbournef7706832014-12-12 23:41:25 +0000176static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
177 if (checkArgCount(S, BuiltinCall, 2))
178 return true;
179
180 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
181 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
182 Expr *Call = BuiltinCall->getArg(0);
183 Expr *Chain = BuiltinCall->getArg(1);
184
185 if (Call->getStmtClass() != Stmt::CallExprClass) {
186 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
187 << Call->getSourceRange();
188 return true;
189 }
190
191 auto CE = cast<CallExpr>(Call);
192 if (CE->getCallee()->getType()->isBlockPointerType()) {
193 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
194 << Call->getSourceRange();
195 return true;
196 }
197
198 const Decl *TargetDecl = CE->getCalleeDecl();
199 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
200 if (FD->getBuiltinID()) {
201 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
202 << Call->getSourceRange();
203 return true;
204 }
205
206 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
207 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
208 << Call->getSourceRange();
209 return true;
210 }
211
212 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
213 if (ChainResult.isInvalid())
214 return true;
215 if (!ChainResult.get()->getType()->isPointerType()) {
216 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
217 << Chain->getSourceRange();
218 return true;
219 }
220
David Majnemerced8bdf2015-02-25 17:36:15 +0000221 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000222 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
223 QualType BuiltinTy = S.Context.getFunctionType(
224 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
225 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
226
227 Builtin =
228 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
229
230 BuiltinCall->setType(CE->getType());
231 BuiltinCall->setValueKind(CE->getValueKind());
232 BuiltinCall->setObjectKind(CE->getObjectKind());
233 BuiltinCall->setCallee(Builtin);
234 BuiltinCall->setArg(1, ChainResult.get());
235
236 return false;
237}
238
Reid Kleckner1d59f992015-01-22 01:36:17 +0000239static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
240 Scope::ScopeFlags NeededScopeFlags,
241 unsigned DiagID) {
242 // Scopes aren't available during instantiation. Fortunately, builtin
243 // functions cannot be template args so they cannot be formed through template
244 // instantiation. Therefore checking once during the parse is sufficient.
245 if (!SemaRef.ActiveTemplateInstantiations.empty())
246 return false;
247
248 Scope *S = SemaRef.getCurScope();
249 while (S && !S->isSEHExceptScope())
250 S = S->getParent();
251 if (!S || !(S->getFlags() & NeededScopeFlags)) {
252 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
253 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
254 << DRE->getDecl()->getIdentifier();
255 return true;
256 }
257
258 return false;
259}
260
John McCalldadc5752010-08-24 06:29:42 +0000261ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000262Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
263 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000264 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000265
Chris Lattner3be167f2010-10-01 23:23:24 +0000266 // Find out if any arguments are required to be integer constant expressions.
267 unsigned ICEArguments = 0;
268 ASTContext::GetBuiltinTypeError Error;
269 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
270 if (Error != ASTContext::GE_None)
271 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
272
273 // If any arguments are required to be ICE's, check and diagnose.
274 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
275 // Skip arguments not required to be ICE's.
276 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
277
278 llvm::APSInt Result;
279 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
280 return true;
281 ICEArguments &= ~(1 << ArgNo);
282 }
283
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000285 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000286 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000287 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000288 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000289 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000290 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000291 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000292 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000293 if (SemaBuiltinVAStart(TheCall))
294 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000295 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000296 case Builtin::BI__va_start: {
297 switch (Context.getTargetInfo().getTriple().getArch()) {
298 case llvm::Triple::arm:
299 case llvm::Triple::thumb:
300 if (SemaBuiltinVAStartARM(TheCall))
301 return ExprError();
302 break;
303 default:
304 if (SemaBuiltinVAStart(TheCall))
305 return ExprError();
306 break;
307 }
308 break;
309 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000310 case Builtin::BI__builtin_isgreater:
311 case Builtin::BI__builtin_isgreaterequal:
312 case Builtin::BI__builtin_isless:
313 case Builtin::BI__builtin_islessequal:
314 case Builtin::BI__builtin_islessgreater:
315 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 if (SemaBuiltinUnorderedCompare(TheCall))
317 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000318 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000319 case Builtin::BI__builtin_fpclassify:
320 if (SemaBuiltinFPClassification(TheCall, 6))
321 return ExprError();
322 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000323 case Builtin::BI__builtin_isfinite:
324 case Builtin::BI__builtin_isinf:
325 case Builtin::BI__builtin_isinf_sign:
326 case Builtin::BI__builtin_isnan:
327 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000328 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000329 return ExprError();
330 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000331 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000332 return SemaBuiltinShuffleVector(TheCall);
333 // TheCall will be freed by the smart pointer here, but that's fine, since
334 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000335 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000336 if (SemaBuiltinPrefetch(TheCall))
337 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000338 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000339 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000340 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000341 if (SemaBuiltinAssume(TheCall))
342 return ExprError();
343 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000344 case Builtin::BI__builtin_assume_aligned:
345 if (SemaBuiltinAssumeAligned(TheCall))
346 return ExprError();
347 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000348 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000349 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000350 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000351 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000352 case Builtin::BI__builtin_longjmp:
353 if (SemaBuiltinLongjmp(TheCall))
354 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000355 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000356 case Builtin::BI__builtin_setjmp:
357 if (SemaBuiltinSetjmp(TheCall))
358 return ExprError();
359 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000360 case Builtin::BI_setjmp:
361 case Builtin::BI_setjmpex:
362 if (checkArgCount(*this, TheCall, 1))
363 return true;
364 break;
John McCallbebede42011-02-26 05:39:39 +0000365
366 case Builtin::BI__builtin_classify_type:
367 if (checkArgCount(*this, TheCall, 1)) return true;
368 TheCall->setType(Context.IntTy);
369 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000370 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000371 if (checkArgCount(*this, TheCall, 1)) return true;
372 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000373 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000374 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000375 case Builtin::BI__sync_fetch_and_add_1:
376 case Builtin::BI__sync_fetch_and_add_2:
377 case Builtin::BI__sync_fetch_and_add_4:
378 case Builtin::BI__sync_fetch_and_add_8:
379 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000380 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000381 case Builtin::BI__sync_fetch_and_sub_1:
382 case Builtin::BI__sync_fetch_and_sub_2:
383 case Builtin::BI__sync_fetch_and_sub_4:
384 case Builtin::BI__sync_fetch_and_sub_8:
385 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000386 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000387 case Builtin::BI__sync_fetch_and_or_1:
388 case Builtin::BI__sync_fetch_and_or_2:
389 case Builtin::BI__sync_fetch_and_or_4:
390 case Builtin::BI__sync_fetch_and_or_8:
391 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000392 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000393 case Builtin::BI__sync_fetch_and_and_1:
394 case Builtin::BI__sync_fetch_and_and_2:
395 case Builtin::BI__sync_fetch_and_and_4:
396 case Builtin::BI__sync_fetch_and_and_8:
397 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000398 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000399 case Builtin::BI__sync_fetch_and_xor_1:
400 case Builtin::BI__sync_fetch_and_xor_2:
401 case Builtin::BI__sync_fetch_and_xor_4:
402 case Builtin::BI__sync_fetch_and_xor_8:
403 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000404 case Builtin::BI__sync_fetch_and_nand:
405 case Builtin::BI__sync_fetch_and_nand_1:
406 case Builtin::BI__sync_fetch_and_nand_2:
407 case Builtin::BI__sync_fetch_and_nand_4:
408 case Builtin::BI__sync_fetch_and_nand_8:
409 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000410 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000411 case Builtin::BI__sync_add_and_fetch_1:
412 case Builtin::BI__sync_add_and_fetch_2:
413 case Builtin::BI__sync_add_and_fetch_4:
414 case Builtin::BI__sync_add_and_fetch_8:
415 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000416 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000417 case Builtin::BI__sync_sub_and_fetch_1:
418 case Builtin::BI__sync_sub_and_fetch_2:
419 case Builtin::BI__sync_sub_and_fetch_4:
420 case Builtin::BI__sync_sub_and_fetch_8:
421 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000422 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000423 case Builtin::BI__sync_and_and_fetch_1:
424 case Builtin::BI__sync_and_and_fetch_2:
425 case Builtin::BI__sync_and_and_fetch_4:
426 case Builtin::BI__sync_and_and_fetch_8:
427 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000428 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000429 case Builtin::BI__sync_or_and_fetch_1:
430 case Builtin::BI__sync_or_and_fetch_2:
431 case Builtin::BI__sync_or_and_fetch_4:
432 case Builtin::BI__sync_or_and_fetch_8:
433 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000434 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000435 case Builtin::BI__sync_xor_and_fetch_1:
436 case Builtin::BI__sync_xor_and_fetch_2:
437 case Builtin::BI__sync_xor_and_fetch_4:
438 case Builtin::BI__sync_xor_and_fetch_8:
439 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000440 case Builtin::BI__sync_nand_and_fetch:
441 case Builtin::BI__sync_nand_and_fetch_1:
442 case Builtin::BI__sync_nand_and_fetch_2:
443 case Builtin::BI__sync_nand_and_fetch_4:
444 case Builtin::BI__sync_nand_and_fetch_8:
445 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000446 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000447 case Builtin::BI__sync_val_compare_and_swap_1:
448 case Builtin::BI__sync_val_compare_and_swap_2:
449 case Builtin::BI__sync_val_compare_and_swap_4:
450 case Builtin::BI__sync_val_compare_and_swap_8:
451 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000452 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000453 case Builtin::BI__sync_bool_compare_and_swap_1:
454 case Builtin::BI__sync_bool_compare_and_swap_2:
455 case Builtin::BI__sync_bool_compare_and_swap_4:
456 case Builtin::BI__sync_bool_compare_and_swap_8:
457 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000458 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000459 case Builtin::BI__sync_lock_test_and_set_1:
460 case Builtin::BI__sync_lock_test_and_set_2:
461 case Builtin::BI__sync_lock_test_and_set_4:
462 case Builtin::BI__sync_lock_test_and_set_8:
463 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000464 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000465 case Builtin::BI__sync_lock_release_1:
466 case Builtin::BI__sync_lock_release_2:
467 case Builtin::BI__sync_lock_release_4:
468 case Builtin::BI__sync_lock_release_8:
469 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000470 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000471 case Builtin::BI__sync_swap_1:
472 case Builtin::BI__sync_swap_2:
473 case Builtin::BI__sync_swap_4:
474 case Builtin::BI__sync_swap_8:
475 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000476 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000477 case Builtin::BI__builtin_nontemporal_load:
478 case Builtin::BI__builtin_nontemporal_store:
479 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000480#define BUILTIN(ID, TYPE, ATTRS)
481#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
482 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000483 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000484#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000485 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000486 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000487 return ExprError();
488 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000489 case Builtin::BI__builtin_addressof:
490 if (SemaBuiltinAddressof(*this, TheCall))
491 return ExprError();
492 break;
John McCall03107a42015-10-29 20:48:01 +0000493 case Builtin::BI__builtin_add_overflow:
494 case Builtin::BI__builtin_sub_overflow:
495 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000496 if (SemaBuiltinOverflow(*this, TheCall))
497 return ExprError();
498 break;
Richard Smith760520b2014-06-03 23:27:44 +0000499 case Builtin::BI__builtin_operator_new:
500 case Builtin::BI__builtin_operator_delete:
501 if (!getLangOpts().CPlusPlus) {
502 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
503 << (BuiltinID == Builtin::BI__builtin_operator_new
504 ? "__builtin_operator_new"
505 : "__builtin_operator_delete")
506 << "C++";
507 return ExprError();
508 }
509 // CodeGen assumes it can find the global new and delete to call,
510 // so ensure that they are declared.
511 DeclareGlobalNewDelete();
512 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000513
514 // check secure string manipulation functions where overflows
515 // are detectable at compile time
516 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000517 case Builtin::BI__builtin___memmove_chk:
518 case Builtin::BI__builtin___memset_chk:
519 case Builtin::BI__builtin___strlcat_chk:
520 case Builtin::BI__builtin___strlcpy_chk:
521 case Builtin::BI__builtin___strncat_chk:
522 case Builtin::BI__builtin___strncpy_chk:
523 case Builtin::BI__builtin___stpncpy_chk:
524 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
525 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000526 case Builtin::BI__builtin___memccpy_chk:
527 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
528 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000529 case Builtin::BI__builtin___snprintf_chk:
530 case Builtin::BI__builtin___vsnprintf_chk:
531 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
532 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000533
534 case Builtin::BI__builtin_call_with_static_chain:
535 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
536 return ExprError();
537 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000538
539 case Builtin::BI__exception_code:
540 case Builtin::BI_exception_code: {
541 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
542 diag::err_seh___except_block))
543 return ExprError();
544 break;
545 }
546 case Builtin::BI__exception_info:
547 case Builtin::BI_exception_info: {
548 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
549 diag::err_seh___except_filter))
550 return ExprError();
551 break;
552 }
553
David Majnemerba3e5ec2015-03-13 18:26:17 +0000554 case Builtin::BI__GetExceptionInfo:
555 if (checkArgCount(*this, TheCall, 1))
556 return ExprError();
557
558 if (CheckCXXThrowOperand(
559 TheCall->getLocStart(),
560 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
561 TheCall))
562 return ExprError();
563
564 TheCall->setType(Context.VoidPtrTy);
565 break;
566
Nate Begeman4904e322010-06-08 02:47:44 +0000567 }
Richard Smith760520b2014-06-03 23:27:44 +0000568
Nate Begeman4904e322010-06-08 02:47:44 +0000569 // Since the target specific builtins for each arch overlap, only check those
570 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000571 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000572 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000573 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000574 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000575 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000576 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000577 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
578 return ExprError();
579 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000580 case llvm::Triple::aarch64:
581 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000582 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000583 return ExprError();
584 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000585 case llvm::Triple::mips:
586 case llvm::Triple::mipsel:
587 case llvm::Triple::mips64:
588 case llvm::Triple::mips64el:
589 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
590 return ExprError();
591 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000592 case llvm::Triple::systemz:
593 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
594 return ExprError();
595 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000596 case llvm::Triple::x86:
597 case llvm::Triple::x86_64:
598 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
599 return ExprError();
600 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000601 case llvm::Triple::ppc:
602 case llvm::Triple::ppc64:
603 case llvm::Triple::ppc64le:
604 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
605 return ExprError();
606 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000607 default:
608 break;
609 }
610 }
611
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000612 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000613}
614
Nate Begeman91e1fea2010-06-14 05:21:25 +0000615// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000616static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000617 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000618 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000619 switch (Type.getEltType()) {
620 case NeonTypeFlags::Int8:
621 case NeonTypeFlags::Poly8:
622 return shift ? 7 : (8 << IsQuad) - 1;
623 case NeonTypeFlags::Int16:
624 case NeonTypeFlags::Poly16:
625 return shift ? 15 : (4 << IsQuad) - 1;
626 case NeonTypeFlags::Int32:
627 return shift ? 31 : (2 << IsQuad) - 1;
628 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000629 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000630 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000631 case NeonTypeFlags::Poly128:
632 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000633 case NeonTypeFlags::Float16:
634 assert(!shift && "cannot shift float types!");
635 return (4 << IsQuad) - 1;
636 case NeonTypeFlags::Float32:
637 assert(!shift && "cannot shift float types!");
638 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000639 case NeonTypeFlags::Float64:
640 assert(!shift && "cannot shift float types!");
641 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000642 }
David Blaikie8a40f702012-01-17 06:56:22 +0000643 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000644}
645
Bob Wilsone4d77232011-11-08 05:04:11 +0000646/// getNeonEltType - Return the QualType corresponding to the elements of
647/// the vector type specified by the NeonTypeFlags. This is used to check
648/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000649static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000650 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000651 switch (Flags.getEltType()) {
652 case NeonTypeFlags::Int8:
653 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
654 case NeonTypeFlags::Int16:
655 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
656 case NeonTypeFlags::Int32:
657 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
658 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000659 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000660 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
661 else
662 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
663 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000664 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000665 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000666 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000667 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000668 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000669 if (IsInt64Long)
670 return Context.UnsignedLongTy;
671 else
672 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000673 case NeonTypeFlags::Poly128:
674 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000675 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000676 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000677 case NeonTypeFlags::Float32:
678 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000679 case NeonTypeFlags::Float64:
680 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000681 }
David Blaikie8a40f702012-01-17 06:56:22 +0000682 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000683}
684
Tim Northover12670412014-02-19 10:37:05 +0000685bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000686 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000687 uint64_t mask = 0;
688 unsigned TV = 0;
689 int PtrArgNum = -1;
690 bool HasConstPtr = false;
691 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000692#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000693#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000694#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000695 }
696
697 // For NEON intrinsics which are overloaded on vector element type, validate
698 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000699 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000700 if (mask) {
701 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
702 return true;
703
704 TV = Result.getLimitedValue(64);
705 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
706 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000707 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000708 }
709
710 if (PtrArgNum >= 0) {
711 // Check that pointer arguments have the specified type.
712 Expr *Arg = TheCall->getArg(PtrArgNum);
713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
714 Arg = ICE->getSubExpr();
715 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
716 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000717
Tim Northovera2ee4332014-03-29 15:09:45 +0000718 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000719 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000720 bool IsInt64Long =
721 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
722 QualType EltTy =
723 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000724 if (HasConstPtr)
725 EltTy = EltTy.withConst();
726 QualType LHSTy = Context.getPointerType(EltTy);
727 AssignConvertType ConvTy;
728 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
729 if (RHS.isInvalid())
730 return true;
731 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
732 RHS.get(), AA_Assigning))
733 return true;
734 }
735
736 // For NEON intrinsics which take an immediate value as part of the
737 // instruction, range check them here.
738 unsigned i = 0, l = 0, u = 0;
739 switch (BuiltinID) {
740 default:
741 return false;
Tim Northover12670412014-02-19 10:37:05 +0000742#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000743#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000744#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000745 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000746
Richard Sandiford28940af2014-04-16 08:47:51 +0000747 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000748}
749
Tim Northovera2ee4332014-03-29 15:09:45 +0000750bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
751 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000752 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000753 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000754 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000755 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000756 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000757 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
758 BuiltinID == AArch64::BI__builtin_arm_strex ||
759 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000760 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000761 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000762 BuiltinID == ARM::BI__builtin_arm_ldaex ||
763 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
764 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000765
766 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
767
768 // Ensure that we have the proper number of arguments.
769 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
770 return true;
771
772 // Inspect the pointer argument of the atomic builtin. This should always be
773 // a pointer type, whose element is an integral scalar or pointer type.
774 // Because it is a pointer type, we don't have to worry about any implicit
775 // casts here.
776 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
777 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
778 if (PointerArgRes.isInvalid())
779 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000780 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000781
782 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
783 if (!pointerType) {
784 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
785 << PointerArg->getType() << PointerArg->getSourceRange();
786 return true;
787 }
788
789 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
790 // task is to insert the appropriate casts into the AST. First work out just
791 // what the appropriate type is.
792 QualType ValType = pointerType->getPointeeType();
793 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
794 if (IsLdrex)
795 AddrType.addConst();
796
797 // Issue a warning if the cast is dodgy.
798 CastKind CastNeeded = CK_NoOp;
799 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
800 CastNeeded = CK_BitCast;
801 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
802 << PointerArg->getType()
803 << Context.getPointerType(AddrType)
804 << AA_Passing << PointerArg->getSourceRange();
805 }
806
807 // Finally, do the cast and replace the argument with the corrected version.
808 AddrType = Context.getPointerType(AddrType);
809 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
810 if (PointerArgRes.isInvalid())
811 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000812 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000813
814 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
815
816 // In general, we allow ints, floats and pointers to be loaded and stored.
817 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
818 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
819 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
820 << PointerArg->getType() << PointerArg->getSourceRange();
821 return true;
822 }
823
824 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000825 if (Context.getTypeSize(ValType) > MaxWidth) {
826 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000827 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
828 << PointerArg->getType() << PointerArg->getSourceRange();
829 return true;
830 }
831
832 switch (ValType.getObjCLifetime()) {
833 case Qualifiers::OCL_None:
834 case Qualifiers::OCL_ExplicitNone:
835 // okay
836 break;
837
838 case Qualifiers::OCL_Weak:
839 case Qualifiers::OCL_Strong:
840 case Qualifiers::OCL_Autoreleasing:
841 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
842 << ValType << PointerArg->getSourceRange();
843 return true;
844 }
845
846
847 if (IsLdrex) {
848 TheCall->setType(ValType);
849 return false;
850 }
851
852 // Initialize the argument to be stored.
853 ExprResult ValArg = TheCall->getArg(0);
854 InitializedEntity Entity = InitializedEntity::InitializeParameter(
855 Context, ValType, /*consume*/ false);
856 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
857 if (ValArg.isInvalid())
858 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000859 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000860
861 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
862 // but the custom checker bypasses all default analysis.
863 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000864 return false;
865}
866
Nate Begeman4904e322010-06-08 02:47:44 +0000867bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000868 llvm::APSInt Result;
869
Tim Northover6aacd492013-07-16 09:47:53 +0000870 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000871 BuiltinID == ARM::BI__builtin_arm_ldaex ||
872 BuiltinID == ARM::BI__builtin_arm_strex ||
873 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000874 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000875 }
876
Yi Kong26d104a2014-08-13 19:18:14 +0000877 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
878 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
879 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
880 }
881
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000882 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
883 BuiltinID == ARM::BI__builtin_arm_wsr64)
884 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
885
886 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
887 BuiltinID == ARM::BI__builtin_arm_rsrp ||
888 BuiltinID == ARM::BI__builtin_arm_wsr ||
889 BuiltinID == ARM::BI__builtin_arm_wsrp)
890 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
891
Tim Northover12670412014-02-19 10:37:05 +0000892 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
893 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000894
Yi Kong4efadfb2014-07-03 16:01:25 +0000895 // For intrinsics which take an immediate value as part of the instruction,
896 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000897 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000898 switch (BuiltinID) {
899 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000900 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
901 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000902 case ARM::BI__builtin_arm_vcvtr_f:
903 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000904 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000905 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000906 case ARM::BI__builtin_arm_isb:
907 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000908 }
Nate Begemand773fe62010-06-13 04:47:52 +0000909
Nate Begemanf568b072010-08-03 21:32:34 +0000910 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000911 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000912}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000913
Tim Northover573cbee2014-05-24 12:52:07 +0000914bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000915 CallExpr *TheCall) {
916 llvm::APSInt Result;
917
Tim Northover573cbee2014-05-24 12:52:07 +0000918 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000919 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
920 BuiltinID == AArch64::BI__builtin_arm_strex ||
921 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000922 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
923 }
924
Yi Konga5548432014-08-13 19:18:20 +0000925 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
926 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
927 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
928 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
929 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
930 }
931
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000932 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
933 BuiltinID == AArch64::BI__builtin_arm_wsr64)
934 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
935
936 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
937 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
938 BuiltinID == AArch64::BI__builtin_arm_wsr ||
939 BuiltinID == AArch64::BI__builtin_arm_wsrp)
940 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
941
Tim Northovera2ee4332014-03-29 15:09:45 +0000942 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
943 return true;
944
Yi Kong19a29ac2014-07-17 10:52:06 +0000945 // For intrinsics which take an immediate value as part of the instruction,
946 // range check them here.
947 unsigned i = 0, l = 0, u = 0;
948 switch (BuiltinID) {
949 default: return false;
950 case AArch64::BI__builtin_arm_dmb:
951 case AArch64::BI__builtin_arm_dsb:
952 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
953 }
954
Yi Kong19a29ac2014-07-17 10:52:06 +0000955 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000956}
957
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000958bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
959 unsigned i = 0, l = 0, u = 0;
960 switch (BuiltinID) {
961 default: return false;
962 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
963 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000964 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
965 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
966 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
967 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
968 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000969 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000970
Richard Sandiford28940af2014-04-16 08:47:51 +0000971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000972}
973
Kit Bartone50adcb2015-03-30 19:40:59 +0000974bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
975 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000976 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
977 BuiltinID == PPC::BI__builtin_divdeu ||
978 BuiltinID == PPC::BI__builtin_bpermd;
979 bool IsTarget64Bit = Context.getTargetInfo()
980 .getTypeWidth(Context
981 .getTargetInfo()
982 .getIntPtrType()) == 64;
983 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
984 BuiltinID == PPC::BI__builtin_divweu ||
985 BuiltinID == PPC::BI__builtin_divde ||
986 BuiltinID == PPC::BI__builtin_divdeu;
987
988 if (Is64BitBltin && !IsTarget64Bit)
989 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
990 << TheCall->getSourceRange();
991
992 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
993 (BuiltinID == PPC::BI__builtin_bpermd &&
994 !Context.getTargetInfo().hasFeature("bpermd")))
995 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
996 << TheCall->getSourceRange();
997
Kit Bartone50adcb2015-03-30 19:40:59 +0000998 switch (BuiltinID) {
999 default: return false;
1000 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1001 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1004 case PPC::BI__builtin_tbegin:
1005 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1006 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1007 case PPC::BI__builtin_tabortwc:
1008 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1009 case PPC::BI__builtin_tabortwci:
1010 case PPC::BI__builtin_tabortdci:
1011 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1012 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1013 }
1014 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1015}
1016
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001017bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1018 CallExpr *TheCall) {
1019 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1020 Expr *Arg = TheCall->getArg(0);
1021 llvm::APSInt AbortCode(32);
1022 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1023 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1024 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1025 << Arg->getSourceRange();
1026 }
1027
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001028 // For intrinsics which take an immediate value as part of the instruction,
1029 // range check them here.
1030 unsigned i = 0, l = 0, u = 0;
1031 switch (BuiltinID) {
1032 default: return false;
1033 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1034 case SystemZ::BI__builtin_s390_verimb:
1035 case SystemZ::BI__builtin_s390_verimh:
1036 case SystemZ::BI__builtin_s390_verimf:
1037 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1038 case SystemZ::BI__builtin_s390_vfaeb:
1039 case SystemZ::BI__builtin_s390_vfaeh:
1040 case SystemZ::BI__builtin_s390_vfaef:
1041 case SystemZ::BI__builtin_s390_vfaebs:
1042 case SystemZ::BI__builtin_s390_vfaehs:
1043 case SystemZ::BI__builtin_s390_vfaefs:
1044 case SystemZ::BI__builtin_s390_vfaezb:
1045 case SystemZ::BI__builtin_s390_vfaezh:
1046 case SystemZ::BI__builtin_s390_vfaezf:
1047 case SystemZ::BI__builtin_s390_vfaezbs:
1048 case SystemZ::BI__builtin_s390_vfaezhs:
1049 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1050 case SystemZ::BI__builtin_s390_vfidb:
1051 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1052 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1053 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1054 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1055 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1056 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1057 case SystemZ::BI__builtin_s390_vstrcb:
1058 case SystemZ::BI__builtin_s390_vstrch:
1059 case SystemZ::BI__builtin_s390_vstrcf:
1060 case SystemZ::BI__builtin_s390_vstrczb:
1061 case SystemZ::BI__builtin_s390_vstrczh:
1062 case SystemZ::BI__builtin_s390_vstrczf:
1063 case SystemZ::BI__builtin_s390_vstrcbs:
1064 case SystemZ::BI__builtin_s390_vstrchs:
1065 case SystemZ::BI__builtin_s390_vstrcfs:
1066 case SystemZ::BI__builtin_s390_vstrczbs:
1067 case SystemZ::BI__builtin_s390_vstrczhs:
1068 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1069 }
1070 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001071}
1072
Craig Topper5ba2c502015-11-07 08:08:31 +00001073/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1074/// This checks that the target supports __builtin_cpu_supports and
1075/// that the string argument is constant and valid.
1076static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1077 Expr *Arg = TheCall->getArg(0);
1078
1079 // Check if the argument is a string literal.
1080 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1081 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1082 << Arg->getSourceRange();
1083
1084 // Check the contents of the string.
1085 StringRef Feature =
1086 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1087 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1088 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1089 << Arg->getSourceRange();
1090 return false;
1091}
1092
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001093bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001094 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001095 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001096 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001097 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001098 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001099 case X86::BI__builtin_ms_va_start:
1100 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001101 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001102 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001103 case X86::BI__builtin_ia32_vpermil2pd:
1104 case X86::BI__builtin_ia32_vpermil2pd256:
1105 case X86::BI__builtin_ia32_vpermil2ps:
1106 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001107 case X86::BI__builtin_ia32_cmpb128_mask:
1108 case X86::BI__builtin_ia32_cmpw128_mask:
1109 case X86::BI__builtin_ia32_cmpd128_mask:
1110 case X86::BI__builtin_ia32_cmpq128_mask:
1111 case X86::BI__builtin_ia32_cmpb256_mask:
1112 case X86::BI__builtin_ia32_cmpw256_mask:
1113 case X86::BI__builtin_ia32_cmpd256_mask:
1114 case X86::BI__builtin_ia32_cmpq256_mask:
1115 case X86::BI__builtin_ia32_cmpb512_mask:
1116 case X86::BI__builtin_ia32_cmpw512_mask:
1117 case X86::BI__builtin_ia32_cmpd512_mask:
1118 case X86::BI__builtin_ia32_cmpq512_mask:
1119 case X86::BI__builtin_ia32_ucmpb128_mask:
1120 case X86::BI__builtin_ia32_ucmpw128_mask:
1121 case X86::BI__builtin_ia32_ucmpd128_mask:
1122 case X86::BI__builtin_ia32_ucmpq128_mask:
1123 case X86::BI__builtin_ia32_ucmpb256_mask:
1124 case X86::BI__builtin_ia32_ucmpw256_mask:
1125 case X86::BI__builtin_ia32_ucmpd256_mask:
1126 case X86::BI__builtin_ia32_ucmpq256_mask:
1127 case X86::BI__builtin_ia32_ucmpb512_mask:
1128 case X86::BI__builtin_ia32_ucmpw512_mask:
1129 case X86::BI__builtin_ia32_ucmpd512_mask:
1130 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001131 case X86::BI__builtin_ia32_roundps:
1132 case X86::BI__builtin_ia32_roundpd:
1133 case X86::BI__builtin_ia32_roundps256:
1134 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1135 case X86::BI__builtin_ia32_roundss:
1136 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1137 case X86::BI__builtin_ia32_cmpps:
1138 case X86::BI__builtin_ia32_cmpss:
1139 case X86::BI__builtin_ia32_cmppd:
1140 case X86::BI__builtin_ia32_cmpsd:
1141 case X86::BI__builtin_ia32_cmpps256:
1142 case X86::BI__builtin_ia32_cmppd256:
1143 case X86::BI__builtin_ia32_cmpps512_mask:
1144 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001145 case X86::BI__builtin_ia32_vpcomub:
1146 case X86::BI__builtin_ia32_vpcomuw:
1147 case X86::BI__builtin_ia32_vpcomud:
1148 case X86::BI__builtin_ia32_vpcomuq:
1149 case X86::BI__builtin_ia32_vpcomb:
1150 case X86::BI__builtin_ia32_vpcomw:
1151 case X86::BI__builtin_ia32_vpcomd:
1152 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001153 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001154 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001155}
1156
Richard Smith55ce3522012-06-25 20:30:08 +00001157/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1158/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1159/// Returns true when the format fits the function and the FormatStringInfo has
1160/// been populated.
1161bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1162 FormatStringInfo *FSI) {
1163 FSI->HasVAListArg = Format->getFirstArg() == 0;
1164 FSI->FormatIdx = Format->getFormatIdx() - 1;
1165 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001166
Richard Smith55ce3522012-06-25 20:30:08 +00001167 // The way the format attribute works in GCC, the implicit this argument
1168 // of member functions is counted. However, it doesn't appear in our own
1169 // lists, so decrement format_idx in that case.
1170 if (IsCXXMember) {
1171 if(FSI->FormatIdx == 0)
1172 return false;
1173 --FSI->FormatIdx;
1174 if (FSI->FirstDataArg != 0)
1175 --FSI->FirstDataArg;
1176 }
1177 return true;
1178}
Mike Stump11289f42009-09-09 15:08:12 +00001179
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001180/// Checks if a the given expression evaluates to null.
1181///
1182/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001183static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001184 // If the expression has non-null type, it doesn't evaluate to null.
1185 if (auto nullability
1186 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1187 if (*nullability == NullabilityKind::NonNull)
1188 return false;
1189 }
1190
Ted Kremeneka146db32014-01-17 06:24:47 +00001191 // As a special case, transparent unions initialized with zero are
1192 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001193 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001194 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1195 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001196 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001197 if (const InitListExpr *ILE =
1198 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001199 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001200 }
1201
1202 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001203 return (!Expr->isValueDependent() &&
1204 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1205 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001206}
1207
1208static void CheckNonNullArgument(Sema &S,
1209 const Expr *ArgExpr,
1210 SourceLocation CallSiteLoc) {
1211 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001212 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1213 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001214}
1215
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001216bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1217 FormatStringInfo FSI;
1218 if ((GetFormatStringType(Format) == FST_NSString) &&
1219 getFormatStringInfo(Format, false, &FSI)) {
1220 Idx = FSI.FormatIdx;
1221 return true;
1222 }
1223 return false;
1224}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001225/// \brief Diagnose use of %s directive in an NSString which is being passed
1226/// as formatting string to formatting method.
1227static void
1228DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1229 const NamedDecl *FDecl,
1230 Expr **Args,
1231 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001232 unsigned Idx = 0;
1233 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001234 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1235 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001236 Idx = 2;
1237 Format = true;
1238 }
1239 else
1240 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1241 if (S.GetFormatNSStringIdx(I, Idx)) {
1242 Format = true;
1243 break;
1244 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001245 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001246 if (!Format || NumArgs <= Idx)
1247 return;
1248 const Expr *FormatExpr = Args[Idx];
1249 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1250 FormatExpr = CSCE->getSubExpr();
1251 const StringLiteral *FormatString;
1252 if (const ObjCStringLiteral *OSL =
1253 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1254 FormatString = OSL->getString();
1255 else
1256 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1257 if (!FormatString)
1258 return;
1259 if (S.FormatStringHasSArg(FormatString)) {
1260 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1261 << "%s" << 1 << 1;
1262 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1263 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001264 }
1265}
1266
Douglas Gregorb4866e82015-06-19 18:13:19 +00001267/// Determine whether the given type has a non-null nullability annotation.
1268static bool isNonNullType(ASTContext &ctx, QualType type) {
1269 if (auto nullability = type->getNullability(ctx))
1270 return *nullability == NullabilityKind::NonNull;
1271
1272 return false;
1273}
1274
Ted Kremenek2bc73332014-01-17 06:24:43 +00001275static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001276 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001277 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001278 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001279 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001280 assert((FDecl || Proto) && "Need a function declaration or prototype");
1281
Ted Kremenek9aedc152014-01-17 06:24:56 +00001282 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001283 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001284 if (FDecl) {
1285 // Handle the nonnull attribute on the function/method declaration itself.
1286 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1287 if (!NonNull->args_size()) {
1288 // Easy case: all pointer arguments are nonnull.
1289 for (const auto *Arg : Args)
1290 if (S.isValidPointerAttrType(Arg->getType()))
1291 CheckNonNullArgument(S, Arg, CallSiteLoc);
1292 return;
1293 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001294
Douglas Gregorb4866e82015-06-19 18:13:19 +00001295 for (unsigned Val : NonNull->args()) {
1296 if (Val >= Args.size())
1297 continue;
1298 if (NonNullArgs.empty())
1299 NonNullArgs.resize(Args.size());
1300 NonNullArgs.set(Val);
1301 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001302 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001303 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001304
Douglas Gregorb4866e82015-06-19 18:13:19 +00001305 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1306 // Handle the nonnull attribute on the parameters of the
1307 // function/method.
1308 ArrayRef<ParmVarDecl*> parms;
1309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1310 parms = FD->parameters();
1311 else
1312 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1313
1314 unsigned ParamIndex = 0;
1315 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1316 I != E; ++I, ++ParamIndex) {
1317 const ParmVarDecl *PVD = *I;
1318 if (PVD->hasAttr<NonNullAttr>() ||
1319 isNonNullType(S.Context, PVD->getType())) {
1320 if (NonNullArgs.empty())
1321 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001322
Douglas Gregorb4866e82015-06-19 18:13:19 +00001323 NonNullArgs.set(ParamIndex);
1324 }
1325 }
1326 } else {
1327 // If we have a non-function, non-method declaration but no
1328 // function prototype, try to dig out the function prototype.
1329 if (!Proto) {
1330 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1331 QualType type = VD->getType().getNonReferenceType();
1332 if (auto pointerType = type->getAs<PointerType>())
1333 type = pointerType->getPointeeType();
1334 else if (auto blockType = type->getAs<BlockPointerType>())
1335 type = blockType->getPointeeType();
1336 // FIXME: data member pointers?
1337
1338 // Dig out the function prototype, if there is one.
1339 Proto = type->getAs<FunctionProtoType>();
1340 }
1341 }
1342
1343 // Fill in non-null argument information from the nullability
1344 // information on the parameter types (if we have them).
1345 if (Proto) {
1346 unsigned Index = 0;
1347 for (auto paramType : Proto->getParamTypes()) {
1348 if (isNonNullType(S.Context, paramType)) {
1349 if (NonNullArgs.empty())
1350 NonNullArgs.resize(Args.size());
1351
1352 NonNullArgs.set(Index);
1353 }
1354
1355 ++Index;
1356 }
1357 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001358 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001359
Douglas Gregorb4866e82015-06-19 18:13:19 +00001360 // Check for non-null arguments.
1361 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1362 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001363 if (NonNullArgs[ArgIndex])
1364 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001365 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001366}
1367
Richard Smith55ce3522012-06-25 20:30:08 +00001368/// Handles the checks for format strings, non-POD arguments to vararg
1369/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001370void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1371 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001372 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001373 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001374 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001375 if (CurContext->isDependentContext())
1376 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001377
Ted Kremenekb8176da2010-09-09 04:33:05 +00001378 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001379 llvm::SmallBitVector CheckedVarArgs;
1380 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001381 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001382 // Only create vector if there are format attributes.
1383 CheckedVarArgs.resize(Args.size());
1384
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001385 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001386 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001387 }
Richard Smithd7293d72013-08-05 18:49:43 +00001388 }
Richard Smith55ce3522012-06-25 20:30:08 +00001389
1390 // Refuse POD arguments that weren't caught by the format string
1391 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001392 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001393 unsigned NumParams = Proto ? Proto->getNumParams()
1394 : FDecl && isa<FunctionDecl>(FDecl)
1395 ? cast<FunctionDecl>(FDecl)->getNumParams()
1396 : FDecl && isa<ObjCMethodDecl>(FDecl)
1397 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1398 : 0;
1399
Alp Toker9cacbab2014-01-20 20:26:09 +00001400 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001401 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001402 if (const Expr *Arg = Args[ArgIdx]) {
1403 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1404 checkVariadicArgument(Arg, CallType);
1405 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001406 }
Richard Smithd7293d72013-08-05 18:49:43 +00001407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregorb4866e82015-06-19 18:13:19 +00001409 if (FDecl || Proto) {
1410 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001411
Richard Trieu41bc0992013-06-22 00:20:41 +00001412 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001413 if (FDecl) {
1414 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1415 CheckArgumentWithTypeTag(I, Args.data());
1416 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001417 }
Richard Smith55ce3522012-06-25 20:30:08 +00001418}
1419
1420/// CheckConstructorCall - Check a constructor call for correctness and safety
1421/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001422void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1423 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001424 const FunctionProtoType *Proto,
1425 SourceLocation Loc) {
1426 VariadicCallType CallType =
1427 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001428 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1429 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001430}
1431
1432/// CheckFunctionCall - Check a direct function call for various correctness
1433/// and safety properties not strictly enforced by the C type system.
1434bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1435 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001436 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1437 isa<CXXMethodDecl>(FDecl);
1438 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1439 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001440 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1441 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001442 Expr** Args = TheCall->getArgs();
1443 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001444 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001445 // If this is a call to a member operator, hide the first argument
1446 // from checkCall.
1447 // FIXME: Our choice of AST representation here is less than ideal.
1448 ++Args;
1449 --NumArgs;
1450 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001451 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001452 IsMemberFunction, TheCall->getRParenLoc(),
1453 TheCall->getCallee()->getSourceRange(), CallType);
1454
1455 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1456 // None of the checks below are needed for functions that don't have
1457 // simple names (e.g., C++ conversion functions).
1458 if (!FnInfo)
1459 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001460
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001461 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001462 if (getLangOpts().ObjC1)
1463 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001464
Anna Zaks22122702012-01-17 00:37:07 +00001465 unsigned CMId = FDecl->getMemoryFunctionKind();
1466 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001467 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001468
Anna Zaks201d4892012-01-13 21:52:01 +00001469 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001470 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001471 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001472 else if (CMId == Builtin::BIstrncat)
1473 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001474 else
Anna Zaks22122702012-01-17 00:37:07 +00001475 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001476
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001477 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001478}
1479
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001480bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001481 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001482 VariadicCallType CallType =
1483 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001484
Douglas Gregorb4866e82015-06-19 18:13:19 +00001485 checkCall(Method, nullptr, Args,
1486 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1487 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001488
1489 return false;
1490}
1491
Richard Trieu664c4c62013-06-20 21:03:13 +00001492bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1493 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001494 QualType Ty;
1495 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001496 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001497 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001498 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001499 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001500 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregorb4866e82015-06-19 18:13:19 +00001502 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1503 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001504 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Richard Trieu664c4c62013-06-20 21:03:13 +00001506 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001507 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001508 CallType = VariadicDoesNotApply;
1509 } else if (Ty->isBlockPointerType()) {
1510 CallType = VariadicBlock;
1511 } else { // Ty->isFunctionPointerType()
1512 CallType = VariadicFunction;
1513 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001514
Douglas Gregorb4866e82015-06-19 18:13:19 +00001515 checkCall(NDecl, Proto,
1516 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1517 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001518 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001519
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001520 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001521}
1522
Richard Trieu41bc0992013-06-22 00:20:41 +00001523/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1524/// such as function pointers returned from functions.
1525bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001526 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001527 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001528 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001529 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001530 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001531 TheCall->getCallee()->getSourceRange(), CallType);
1532
1533 return false;
1534}
1535
Tim Northovere94a34c2014-03-11 10:49:14 +00001536static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1537 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1538 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1539 return false;
1540
1541 switch (Op) {
1542 case AtomicExpr::AO__c11_atomic_init:
1543 llvm_unreachable("There is no ordering argument for an init");
1544
1545 case AtomicExpr::AO__c11_atomic_load:
1546 case AtomicExpr::AO__atomic_load_n:
1547 case AtomicExpr::AO__atomic_load:
1548 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1549 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1550
1551 case AtomicExpr::AO__c11_atomic_store:
1552 case AtomicExpr::AO__atomic_store:
1553 case AtomicExpr::AO__atomic_store_n:
1554 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1555 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1556 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1557
1558 default:
1559 return true;
1560 }
1561}
1562
Richard Smithfeea8832012-04-12 05:08:17 +00001563ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1564 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001565 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1566 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001567
Richard Smithfeea8832012-04-12 05:08:17 +00001568 // All these operations take one of the following forms:
1569 enum {
1570 // C __c11_atomic_init(A *, C)
1571 Init,
1572 // C __c11_atomic_load(A *, int)
1573 Load,
1574 // void __atomic_load(A *, CP, int)
1575 Copy,
1576 // C __c11_atomic_add(A *, M, int)
1577 Arithmetic,
1578 // C __atomic_exchange_n(A *, CP, int)
1579 Xchg,
1580 // void __atomic_exchange(A *, C *, CP, int)
1581 GNUXchg,
1582 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1583 C11CmpXchg,
1584 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1585 GNUCmpXchg
1586 } Form = Init;
1587 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1588 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1589 // where:
1590 // C is an appropriate type,
1591 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1592 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1593 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1594 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001595
Gabor Horvath98bd0982015-03-16 09:59:54 +00001596 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1597 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1598 AtomicExpr::AO__atomic_load,
1599 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001600 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1601 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1602 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1603 Op == AtomicExpr::AO__atomic_store_n ||
1604 Op == AtomicExpr::AO__atomic_exchange_n ||
1605 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1606 bool IsAddSub = false;
1607
1608 switch (Op) {
1609 case AtomicExpr::AO__c11_atomic_init:
1610 Form = Init;
1611 break;
1612
1613 case AtomicExpr::AO__c11_atomic_load:
1614 case AtomicExpr::AO__atomic_load_n:
1615 Form = Load;
1616 break;
1617
1618 case AtomicExpr::AO__c11_atomic_store:
1619 case AtomicExpr::AO__atomic_load:
1620 case AtomicExpr::AO__atomic_store:
1621 case AtomicExpr::AO__atomic_store_n:
1622 Form = Copy;
1623 break;
1624
1625 case AtomicExpr::AO__c11_atomic_fetch_add:
1626 case AtomicExpr::AO__c11_atomic_fetch_sub:
1627 case AtomicExpr::AO__atomic_fetch_add:
1628 case AtomicExpr::AO__atomic_fetch_sub:
1629 case AtomicExpr::AO__atomic_add_fetch:
1630 case AtomicExpr::AO__atomic_sub_fetch:
1631 IsAddSub = true;
1632 // Fall through.
1633 case AtomicExpr::AO__c11_atomic_fetch_and:
1634 case AtomicExpr::AO__c11_atomic_fetch_or:
1635 case AtomicExpr::AO__c11_atomic_fetch_xor:
1636 case AtomicExpr::AO__atomic_fetch_and:
1637 case AtomicExpr::AO__atomic_fetch_or:
1638 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001639 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001640 case AtomicExpr::AO__atomic_and_fetch:
1641 case AtomicExpr::AO__atomic_or_fetch:
1642 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001643 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001644 Form = Arithmetic;
1645 break;
1646
1647 case AtomicExpr::AO__c11_atomic_exchange:
1648 case AtomicExpr::AO__atomic_exchange_n:
1649 Form = Xchg;
1650 break;
1651
1652 case AtomicExpr::AO__atomic_exchange:
1653 Form = GNUXchg;
1654 break;
1655
1656 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1657 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1658 Form = C11CmpXchg;
1659 break;
1660
1661 case AtomicExpr::AO__atomic_compare_exchange:
1662 case AtomicExpr::AO__atomic_compare_exchange_n:
1663 Form = GNUCmpXchg;
1664 break;
1665 }
1666
1667 // Check we have the right number of arguments.
1668 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001669 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001670 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001671 << TheCall->getCallee()->getSourceRange();
1672 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001673 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1674 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001675 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001676 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001677 << TheCall->getCallee()->getSourceRange();
1678 return ExprError();
1679 }
1680
Richard Smithfeea8832012-04-12 05:08:17 +00001681 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001682 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001683 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1684 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1685 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001686 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001687 << Ptr->getType() << Ptr->getSourceRange();
1688 return ExprError();
1689 }
1690
Richard Smithfeea8832012-04-12 05:08:17 +00001691 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1692 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1693 QualType ValType = AtomTy; // 'C'
1694 if (IsC11) {
1695 if (!AtomTy->isAtomicType()) {
1696 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1697 << Ptr->getType() << Ptr->getSourceRange();
1698 return ExprError();
1699 }
Richard Smithe00921a2012-09-15 06:09:58 +00001700 if (AtomTy.isConstQualified()) {
1701 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1702 << Ptr->getType() << Ptr->getSourceRange();
1703 return ExprError();
1704 }
Richard Smithfeea8832012-04-12 05:08:17 +00001705 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001706 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1707 if (ValType.isConstQualified()) {
1708 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1709 << Ptr->getType() << Ptr->getSourceRange();
1710 return ExprError();
1711 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001712 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001713
Richard Smithfeea8832012-04-12 05:08:17 +00001714 // For an arithmetic operation, the implied arithmetic must be well-formed.
1715 if (Form == Arithmetic) {
1716 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1717 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1718 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1719 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1720 return ExprError();
1721 }
1722 if (!IsAddSub && !ValType->isIntegerType()) {
1723 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1724 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1725 return ExprError();
1726 }
David Majnemere85cff82015-01-28 05:48:06 +00001727 if (IsC11 && ValType->isPointerType() &&
1728 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1729 diag::err_incomplete_type)) {
1730 return ExprError();
1731 }
Richard Smithfeea8832012-04-12 05:08:17 +00001732 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1733 // For __atomic_*_n operations, the value type must be a scalar integral or
1734 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001735 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001736 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1737 return ExprError();
1738 }
1739
Eli Friedmanaa769812013-09-11 03:49:34 +00001740 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1741 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001742 // For GNU atomics, require a trivially-copyable type. This is not part of
1743 // the GNU atomics specification, but we enforce it for sanity.
1744 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001745 << Ptr->getType() << Ptr->getSourceRange();
1746 return ExprError();
1747 }
1748
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001749 switch (ValType.getObjCLifetime()) {
1750 case Qualifiers::OCL_None:
1751 case Qualifiers::OCL_ExplicitNone:
1752 // okay
1753 break;
1754
1755 case Qualifiers::OCL_Weak:
1756 case Qualifiers::OCL_Strong:
1757 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001758 // FIXME: Can this happen? By this point, ValType should be known
1759 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001760 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1761 << ValType << Ptr->getSourceRange();
1762 return ExprError();
1763 }
1764
David Majnemerc6eb6502015-06-03 00:26:35 +00001765 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1766 // volatile-ness of the pointee-type inject itself into the result or the
1767 // other operands.
1768 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001769 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001770 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001771 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001772 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001773 ResultType = Context.BoolTy;
1774
Richard Smithfeea8832012-04-12 05:08:17 +00001775 // The type of a parameter passed 'by value'. In the GNU atomics, such
1776 // arguments are actually passed as pointers.
1777 QualType ByValType = ValType; // 'CP'
1778 if (!IsC11 && !IsN)
1779 ByValType = Ptr->getType();
1780
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001781 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1782 // but not the second argument. We need to manually remove possible const
1783 // qualifiers.
1784
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001785 // The first argument --- the pointer --- has a fixed type; we
1786 // deduce the types of the rest of the arguments accordingly. Walk
1787 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001788 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001789 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001790 if (i < NumVals[Form] + 1) {
1791 switch (i) {
1792 case 1:
1793 // The second argument is the non-atomic operand. For arithmetic, this
1794 // is always passed by value, and for a compare_exchange it is always
1795 // passed by address. For the rest, GNU uses by-address and C11 uses
1796 // by-value.
1797 assert(Form != Load);
1798 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1799 Ty = ValType;
1800 else if (Form == Copy || Form == Xchg)
1801 Ty = ByValType;
1802 else if (Form == Arithmetic)
1803 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00001804 else {
1805 Expr *ValArg = TheCall->getArg(i);
1806 unsigned AS = 0;
1807 // Keep address space of non-atomic pointer type.
1808 if (const PointerType *PtrTy =
1809 ValArg->getType()->getAs<PointerType>()) {
1810 AS = PtrTy->getPointeeType().getAddressSpace();
1811 }
1812 Ty = Context.getPointerType(
1813 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
1814 }
Richard Smithfeea8832012-04-12 05:08:17 +00001815 break;
1816 case 2:
1817 // The third argument to compare_exchange / GNU exchange is a
1818 // (pointer to a) desired value.
1819 Ty = ByValType;
1820 break;
1821 case 3:
1822 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1823 Ty = Context.BoolTy;
1824 break;
1825 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001826 } else {
1827 // The order(s) are always converted to int.
1828 Ty = Context.IntTy;
1829 }
Richard Smithfeea8832012-04-12 05:08:17 +00001830
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001831 InitializedEntity Entity =
1832 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001833 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1835 if (Arg.isInvalid())
1836 return true;
1837 TheCall->setArg(i, Arg.get());
1838 }
1839
Richard Smithfeea8832012-04-12 05:08:17 +00001840 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001841 SmallVector<Expr*, 5> SubExprs;
1842 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001843 switch (Form) {
1844 case Init:
1845 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001846 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001847 break;
1848 case Load:
1849 SubExprs.push_back(TheCall->getArg(1)); // Order
1850 break;
1851 case Copy:
1852 case Arithmetic:
1853 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001854 SubExprs.push_back(TheCall->getArg(2)); // Order
1855 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001856 break;
1857 case GNUXchg:
1858 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1859 SubExprs.push_back(TheCall->getArg(3)); // Order
1860 SubExprs.push_back(TheCall->getArg(1)); // Val1
1861 SubExprs.push_back(TheCall->getArg(2)); // Val2
1862 break;
1863 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001864 SubExprs.push_back(TheCall->getArg(3)); // Order
1865 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001866 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001867 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001868 break;
1869 case GNUCmpXchg:
1870 SubExprs.push_back(TheCall->getArg(4)); // Order
1871 SubExprs.push_back(TheCall->getArg(1)); // Val1
1872 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1873 SubExprs.push_back(TheCall->getArg(2)); // Val2
1874 SubExprs.push_back(TheCall->getArg(3)); // Weak
1875 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001876 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001877
1878 if (SubExprs.size() >= 2 && Form != Init) {
1879 llvm::APSInt Result(32);
1880 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1881 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001882 Diag(SubExprs[1]->getLocStart(),
1883 diag::warn_atomic_op_has_invalid_memory_order)
1884 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001885 }
1886
Fariborz Jahanian615de762013-05-28 17:37:39 +00001887 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1888 SubExprs, ResultType, Op,
1889 TheCall->getRParenLoc());
1890
1891 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1892 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1893 Context.AtomicUsesUnsupportedLibcall(AE))
1894 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1895 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001896
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001897 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001898}
1899
1900
John McCall29ad95b2011-08-27 01:09:30 +00001901/// checkBuiltinArgument - Given a call to a builtin function, perform
1902/// normal type-checking on the given argument, updating the call in
1903/// place. This is useful when a builtin function requires custom
1904/// type-checking for some of its arguments but not necessarily all of
1905/// them.
1906///
1907/// Returns true on error.
1908static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1909 FunctionDecl *Fn = E->getDirectCallee();
1910 assert(Fn && "builtin call without direct callee!");
1911
1912 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1913 InitializedEntity Entity =
1914 InitializedEntity::InitializeParameter(S.Context, Param);
1915
1916 ExprResult Arg = E->getArg(0);
1917 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1918 if (Arg.isInvalid())
1919 return true;
1920
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001921 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001922 return false;
1923}
1924
Chris Lattnerdc046542009-05-08 06:58:22 +00001925/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1926/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1927/// type of its first argument. The main ActOnCallExpr routines have already
1928/// promoted the types of arguments because all of these calls are prototyped as
1929/// void(...).
1930///
1931/// This function goes through and does final semantic checking for these
1932/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001933ExprResult
1934Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001935 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001936 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1937 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1938
1939 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001940 if (TheCall->getNumArgs() < 1) {
1941 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1942 << 0 << 1 << TheCall->getNumArgs()
1943 << TheCall->getCallee()->getSourceRange();
1944 return ExprError();
1945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
Chris Lattnerdc046542009-05-08 06:58:22 +00001947 // Inspect the first argument of the atomic builtin. This should always be
1948 // a pointer type, whose element is an integral scalar or pointer type.
1949 // Because it is a pointer type, we don't have to worry about any implicit
1950 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001951 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001952 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001953 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1954 if (FirstArgResult.isInvalid())
1955 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001956 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001957 TheCall->setArg(0, FirstArg);
1958
John McCall31168b02011-06-15 23:02:42 +00001959 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1960 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001961 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1962 << FirstArg->getType() << FirstArg->getSourceRange();
1963 return ExprError();
1964 }
Mike Stump11289f42009-09-09 15:08:12 +00001965
John McCall31168b02011-06-15 23:02:42 +00001966 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001967 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001968 !ValType->isBlockPointerType()) {
1969 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1970 << FirstArg->getType() << FirstArg->getSourceRange();
1971 return ExprError();
1972 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001973
John McCall31168b02011-06-15 23:02:42 +00001974 switch (ValType.getObjCLifetime()) {
1975 case Qualifiers::OCL_None:
1976 case Qualifiers::OCL_ExplicitNone:
1977 // okay
1978 break;
1979
1980 case Qualifiers::OCL_Weak:
1981 case Qualifiers::OCL_Strong:
1982 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001983 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001984 << ValType << FirstArg->getSourceRange();
1985 return ExprError();
1986 }
1987
John McCallb50451a2011-10-05 07:41:44 +00001988 // Strip any qualifiers off ValType.
1989 ValType = ValType.getUnqualifiedType();
1990
Chandler Carruth3973af72010-07-18 20:54:12 +00001991 // The majority of builtins return a value, but a few have special return
1992 // types, so allow them to override appropriately below.
1993 QualType ResultType = ValType;
1994
Chris Lattnerdc046542009-05-08 06:58:22 +00001995 // We need to figure out which concrete builtin this maps onto. For example,
1996 // __sync_fetch_and_add with a 2 byte object turns into
1997 // __sync_fetch_and_add_2.
1998#define BUILTIN_ROW(x) \
1999 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2000 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattnerdc046542009-05-08 06:58:22 +00002002 static const unsigned BuiltinIndices[][5] = {
2003 BUILTIN_ROW(__sync_fetch_and_add),
2004 BUILTIN_ROW(__sync_fetch_and_sub),
2005 BUILTIN_ROW(__sync_fetch_and_or),
2006 BUILTIN_ROW(__sync_fetch_and_and),
2007 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002008 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002009
Chris Lattnerdc046542009-05-08 06:58:22 +00002010 BUILTIN_ROW(__sync_add_and_fetch),
2011 BUILTIN_ROW(__sync_sub_and_fetch),
2012 BUILTIN_ROW(__sync_and_and_fetch),
2013 BUILTIN_ROW(__sync_or_and_fetch),
2014 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002015 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002016
Chris Lattnerdc046542009-05-08 06:58:22 +00002017 BUILTIN_ROW(__sync_val_compare_and_swap),
2018 BUILTIN_ROW(__sync_bool_compare_and_swap),
2019 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002020 BUILTIN_ROW(__sync_lock_release),
2021 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002022 };
Mike Stump11289f42009-09-09 15:08:12 +00002023#undef BUILTIN_ROW
2024
Chris Lattnerdc046542009-05-08 06:58:22 +00002025 // Determine the index of the size.
2026 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002027 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002028 case 1: SizeIndex = 0; break;
2029 case 2: SizeIndex = 1; break;
2030 case 4: SizeIndex = 2; break;
2031 case 8: SizeIndex = 3; break;
2032 case 16: SizeIndex = 4; break;
2033 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2035 << FirstArg->getType() << FirstArg->getSourceRange();
2036 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002037 }
Mike Stump11289f42009-09-09 15:08:12 +00002038
Chris Lattnerdc046542009-05-08 06:58:22 +00002039 // Each of these builtins has one pointer argument, followed by some number of
2040 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2041 // that we ignore. Find out which row of BuiltinIndices to read from as well
2042 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002043 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002044 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002045 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002046 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002047 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002048 case Builtin::BI__sync_fetch_and_add:
2049 case Builtin::BI__sync_fetch_and_add_1:
2050 case Builtin::BI__sync_fetch_and_add_2:
2051 case Builtin::BI__sync_fetch_and_add_4:
2052 case Builtin::BI__sync_fetch_and_add_8:
2053 case Builtin::BI__sync_fetch_and_add_16:
2054 BuiltinIndex = 0;
2055 break;
2056
2057 case Builtin::BI__sync_fetch_and_sub:
2058 case Builtin::BI__sync_fetch_and_sub_1:
2059 case Builtin::BI__sync_fetch_and_sub_2:
2060 case Builtin::BI__sync_fetch_and_sub_4:
2061 case Builtin::BI__sync_fetch_and_sub_8:
2062 case Builtin::BI__sync_fetch_and_sub_16:
2063 BuiltinIndex = 1;
2064 break;
2065
2066 case Builtin::BI__sync_fetch_and_or:
2067 case Builtin::BI__sync_fetch_and_or_1:
2068 case Builtin::BI__sync_fetch_and_or_2:
2069 case Builtin::BI__sync_fetch_and_or_4:
2070 case Builtin::BI__sync_fetch_and_or_8:
2071 case Builtin::BI__sync_fetch_and_or_16:
2072 BuiltinIndex = 2;
2073 break;
2074
2075 case Builtin::BI__sync_fetch_and_and:
2076 case Builtin::BI__sync_fetch_and_and_1:
2077 case Builtin::BI__sync_fetch_and_and_2:
2078 case Builtin::BI__sync_fetch_and_and_4:
2079 case Builtin::BI__sync_fetch_and_and_8:
2080 case Builtin::BI__sync_fetch_and_and_16:
2081 BuiltinIndex = 3;
2082 break;
Mike Stump11289f42009-09-09 15:08:12 +00002083
Douglas Gregor73722482011-11-28 16:30:08 +00002084 case Builtin::BI__sync_fetch_and_xor:
2085 case Builtin::BI__sync_fetch_and_xor_1:
2086 case Builtin::BI__sync_fetch_and_xor_2:
2087 case Builtin::BI__sync_fetch_and_xor_4:
2088 case Builtin::BI__sync_fetch_and_xor_8:
2089 case Builtin::BI__sync_fetch_and_xor_16:
2090 BuiltinIndex = 4;
2091 break;
2092
Hal Finkeld2208b52014-10-02 20:53:50 +00002093 case Builtin::BI__sync_fetch_and_nand:
2094 case Builtin::BI__sync_fetch_and_nand_1:
2095 case Builtin::BI__sync_fetch_and_nand_2:
2096 case Builtin::BI__sync_fetch_and_nand_4:
2097 case Builtin::BI__sync_fetch_and_nand_8:
2098 case Builtin::BI__sync_fetch_and_nand_16:
2099 BuiltinIndex = 5;
2100 WarnAboutSemanticsChange = true;
2101 break;
2102
Douglas Gregor73722482011-11-28 16:30:08 +00002103 case Builtin::BI__sync_add_and_fetch:
2104 case Builtin::BI__sync_add_and_fetch_1:
2105 case Builtin::BI__sync_add_and_fetch_2:
2106 case Builtin::BI__sync_add_and_fetch_4:
2107 case Builtin::BI__sync_add_and_fetch_8:
2108 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002109 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002110 break;
2111
2112 case Builtin::BI__sync_sub_and_fetch:
2113 case Builtin::BI__sync_sub_and_fetch_1:
2114 case Builtin::BI__sync_sub_and_fetch_2:
2115 case Builtin::BI__sync_sub_and_fetch_4:
2116 case Builtin::BI__sync_sub_and_fetch_8:
2117 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002118 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002119 break;
2120
2121 case Builtin::BI__sync_and_and_fetch:
2122 case Builtin::BI__sync_and_and_fetch_1:
2123 case Builtin::BI__sync_and_and_fetch_2:
2124 case Builtin::BI__sync_and_and_fetch_4:
2125 case Builtin::BI__sync_and_and_fetch_8:
2126 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002127 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002128 break;
2129
2130 case Builtin::BI__sync_or_and_fetch:
2131 case Builtin::BI__sync_or_and_fetch_1:
2132 case Builtin::BI__sync_or_and_fetch_2:
2133 case Builtin::BI__sync_or_and_fetch_4:
2134 case Builtin::BI__sync_or_and_fetch_8:
2135 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002136 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002137 break;
2138
2139 case Builtin::BI__sync_xor_and_fetch:
2140 case Builtin::BI__sync_xor_and_fetch_1:
2141 case Builtin::BI__sync_xor_and_fetch_2:
2142 case Builtin::BI__sync_xor_and_fetch_4:
2143 case Builtin::BI__sync_xor_and_fetch_8:
2144 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002145 BuiltinIndex = 10;
2146 break;
2147
2148 case Builtin::BI__sync_nand_and_fetch:
2149 case Builtin::BI__sync_nand_and_fetch_1:
2150 case Builtin::BI__sync_nand_and_fetch_2:
2151 case Builtin::BI__sync_nand_and_fetch_4:
2152 case Builtin::BI__sync_nand_and_fetch_8:
2153 case Builtin::BI__sync_nand_and_fetch_16:
2154 BuiltinIndex = 11;
2155 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002156 break;
Mike Stump11289f42009-09-09 15:08:12 +00002157
Chris Lattnerdc046542009-05-08 06:58:22 +00002158 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002159 case Builtin::BI__sync_val_compare_and_swap_1:
2160 case Builtin::BI__sync_val_compare_and_swap_2:
2161 case Builtin::BI__sync_val_compare_and_swap_4:
2162 case Builtin::BI__sync_val_compare_and_swap_8:
2163 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002164 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002165 NumFixed = 2;
2166 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002167
Chris Lattnerdc046542009-05-08 06:58:22 +00002168 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002169 case Builtin::BI__sync_bool_compare_and_swap_1:
2170 case Builtin::BI__sync_bool_compare_and_swap_2:
2171 case Builtin::BI__sync_bool_compare_and_swap_4:
2172 case Builtin::BI__sync_bool_compare_and_swap_8:
2173 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002174 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002175 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002176 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002177 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002178
2179 case Builtin::BI__sync_lock_test_and_set:
2180 case Builtin::BI__sync_lock_test_and_set_1:
2181 case Builtin::BI__sync_lock_test_and_set_2:
2182 case Builtin::BI__sync_lock_test_and_set_4:
2183 case Builtin::BI__sync_lock_test_and_set_8:
2184 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002185 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002186 break;
2187
Chris Lattnerdc046542009-05-08 06:58:22 +00002188 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002189 case Builtin::BI__sync_lock_release_1:
2190 case Builtin::BI__sync_lock_release_2:
2191 case Builtin::BI__sync_lock_release_4:
2192 case Builtin::BI__sync_lock_release_8:
2193 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002194 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002195 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002196 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002197 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002198
2199 case Builtin::BI__sync_swap:
2200 case Builtin::BI__sync_swap_1:
2201 case Builtin::BI__sync_swap_2:
2202 case Builtin::BI__sync_swap_4:
2203 case Builtin::BI__sync_swap_8:
2204 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002205 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002206 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Chris Lattnerdc046542009-05-08 06:58:22 +00002209 // Now that we know how many fixed arguments we expect, first check that we
2210 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002211 if (TheCall->getNumArgs() < 1+NumFixed) {
2212 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2213 << 0 << 1+NumFixed << TheCall->getNumArgs()
2214 << TheCall->getCallee()->getSourceRange();
2215 return ExprError();
2216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
Hal Finkeld2208b52014-10-02 20:53:50 +00002218 if (WarnAboutSemanticsChange) {
2219 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2220 << TheCall->getCallee()->getSourceRange();
2221 }
2222
Chris Lattner5b9241b2009-05-08 15:36:58 +00002223 // Get the decl for the concrete builtin from this, we can tell what the
2224 // concrete integer type we should convert to is.
2225 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002226 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002227 FunctionDecl *NewBuiltinDecl;
2228 if (NewBuiltinID == BuiltinID)
2229 NewBuiltinDecl = FDecl;
2230 else {
2231 // Perform builtin lookup to avoid redeclaring it.
2232 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2233 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2234 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2235 assert(Res.getFoundDecl());
2236 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002237 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002238 return ExprError();
2239 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002240
John McCallcf142162010-08-07 06:22:56 +00002241 // The first argument --- the pointer --- has a fixed type; we
2242 // deduce the types of the rest of the arguments accordingly. Walk
2243 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002244 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002245 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002246
Chris Lattnerdc046542009-05-08 06:58:22 +00002247 // GCC does an implicit conversion to the pointer or integer ValType. This
2248 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002249 // Initialize the argument.
2250 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2251 ValType, /*consume*/ false);
2252 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002253 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002254 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattnerdc046542009-05-08 06:58:22 +00002256 // Okay, we have something that *can* be converted to the right type. Check
2257 // to see if there is a potentially weird extension going on here. This can
2258 // happen when you do an atomic operation on something like an char* and
2259 // pass in 42. The 42 gets converted to char. This is even more strange
2260 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002261 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002262 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002263 }
Mike Stump11289f42009-09-09 15:08:12 +00002264
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002265 ASTContext& Context = this->getASTContext();
2266
2267 // Create a new DeclRefExpr to refer to the new decl.
2268 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2269 Context,
2270 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002271 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002272 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002273 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002274 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002275 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002276 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chris Lattnerdc046542009-05-08 06:58:22 +00002278 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002279 // FIXME: This loses syntactic information.
2280 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2281 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2282 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002283 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002285 // Change the result type of the call to match the original value type. This
2286 // is arbitrary, but the codegen for these builtins ins design to handle it
2287 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002288 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002289
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002290 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002291}
2292
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002293/// SemaBuiltinNontemporalOverloaded - We have a call to
2294/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2295/// overloaded function based on the pointer type of its last argument.
2296///
2297/// This function goes through and does final semantic checking for these
2298/// builtins.
2299ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2300 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2301 DeclRefExpr *DRE =
2302 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2303 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2304 unsigned BuiltinID = FDecl->getBuiltinID();
2305 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2306 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2307 "Unexpected nontemporal load/store builtin!");
2308 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2309 unsigned numArgs = isStore ? 2 : 1;
2310
2311 // Ensure that we have the proper number of arguments.
2312 if (checkArgCount(*this, TheCall, numArgs))
2313 return ExprError();
2314
2315 // Inspect the last argument of the nontemporal builtin. This should always
2316 // be a pointer type, from which we imply the type of the memory access.
2317 // Because it is a pointer type, we don't have to worry about any implicit
2318 // casts here.
2319 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2320 ExprResult PointerArgResult =
2321 DefaultFunctionArrayLvalueConversion(PointerArg);
2322
2323 if (PointerArgResult.isInvalid())
2324 return ExprError();
2325 PointerArg = PointerArgResult.get();
2326 TheCall->setArg(numArgs - 1, PointerArg);
2327
2328 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2329 if (!pointerType) {
2330 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2331 << PointerArg->getType() << PointerArg->getSourceRange();
2332 return ExprError();
2333 }
2334
2335 QualType ValType = pointerType->getPointeeType();
2336
2337 // Strip any qualifiers off ValType.
2338 ValType = ValType.getUnqualifiedType();
2339 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2340 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2341 !ValType->isVectorType()) {
2342 Diag(DRE->getLocStart(),
2343 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2344 << PointerArg->getType() << PointerArg->getSourceRange();
2345 return ExprError();
2346 }
2347
2348 if (!isStore) {
2349 TheCall->setType(ValType);
2350 return TheCallResult;
2351 }
2352
2353 ExprResult ValArg = TheCall->getArg(0);
2354 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2355 Context, ValType, /*consume*/ false);
2356 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2357 if (ValArg.isInvalid())
2358 return ExprError();
2359
2360 TheCall->setArg(0, ValArg.get());
2361 TheCall->setType(Context.VoidTy);
2362 return TheCallResult;
2363}
2364
Chris Lattner6436fb62009-02-18 06:01:06 +00002365/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002366/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002367/// Note: It might also make sense to do the UTF-16 conversion here (would
2368/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002369bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002370 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002371 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2372
Douglas Gregorfb65e592011-07-27 05:40:30 +00002373 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002374 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2375 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002376 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002377 }
Mike Stump11289f42009-09-09 15:08:12 +00002378
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002379 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002380 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002381 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002382 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002383 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002384 UTF16 *ToPtr = &ToBuf[0];
2385
2386 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2387 &ToPtr, ToPtr + NumBytes,
2388 strictConversion);
2389 // Check for conversion failure.
2390 if (Result != conversionOK)
2391 Diag(Arg->getLocStart(),
2392 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2393 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002394 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002395}
2396
Charles Davisc7d5c942015-09-17 20:55:33 +00002397/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2398/// for validity. Emit an error and return true on failure; return false
2399/// on success.
2400bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002401 Expr *Fn = TheCall->getCallee();
2402 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002403 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002404 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002405 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2406 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002407 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002408 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002409 return true;
2410 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002411
2412 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002413 return Diag(TheCall->getLocEnd(),
2414 diag::err_typecheck_call_too_few_args_at_least)
2415 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002416 }
2417
John McCall29ad95b2011-08-27 01:09:30 +00002418 // Type-check the first argument normally.
2419 if (checkBuiltinArgument(*this, TheCall, 0))
2420 return true;
2421
Chris Lattnere202e6a2007-12-20 00:05:45 +00002422 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002423 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002424 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002425 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002426 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002427 else if (FunctionDecl *FD = getCurFunctionDecl())
2428 isVariadic = FD->isVariadic();
2429 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002430 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002431
Chris Lattnere202e6a2007-12-20 00:05:45 +00002432 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002433 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2434 return true;
2435 }
Mike Stump11289f42009-09-09 15:08:12 +00002436
Chris Lattner43be2e62007-12-19 23:59:04 +00002437 // Verify that the second argument to the builtin is the last argument of the
2438 // current function or method.
2439 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002440 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002441
Nico Weber9eea7642013-05-24 23:31:57 +00002442 // These are valid if SecondArgIsLastNamedArgument is false after the next
2443 // block.
2444 QualType Type;
2445 SourceLocation ParamLoc;
2446
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002447 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2448 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002449 // FIXME: This isn't correct for methods (results in bogus warning).
2450 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002451 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002452 if (CurBlock)
2453 LastArg = *(CurBlock->TheDecl->param_end()-1);
2454 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002455 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002456 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002457 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002458 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002459
2460 Type = PV->getType();
2461 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002462 }
2463 }
Mike Stump11289f42009-09-09 15:08:12 +00002464
Chris Lattner43be2e62007-12-19 23:59:04 +00002465 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002466 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002467 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002468 else if (Type->isReferenceType()) {
2469 Diag(Arg->getLocStart(),
2470 diag::warn_va_start_of_reference_type_is_undefined);
2471 Diag(ParamLoc, diag::note_parameter_type) << Type;
2472 }
2473
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002474 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002475 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002476}
Chris Lattner43be2e62007-12-19 23:59:04 +00002477
Charles Davisc7d5c942015-09-17 20:55:33 +00002478/// Check the arguments to '__builtin_va_start' for validity, and that
2479/// it was called from a function of the native ABI.
2480/// Emit an error and return true on failure; return false on success.
2481bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2482 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2483 // On x64 Windows, don't allow this in System V ABI functions.
2484 // (Yes, that means there's no corresponding way to support variadic
2485 // System V ABI functions on Windows.)
2486 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2487 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2488 clang::CallingConv CC = CC_C;
2489 if (const FunctionDecl *FD = getCurFunctionDecl())
2490 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2491 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2492 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2493 return Diag(TheCall->getCallee()->getLocStart(),
2494 diag::err_va_start_used_in_wrong_abi_function)
2495 << (OS != llvm::Triple::Win32);
2496 }
2497 return SemaBuiltinVAStartImpl(TheCall);
2498}
2499
2500/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2501/// it was called from a Win64 ABI function.
2502/// Emit an error and return true on failure; return false on success.
2503bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2504 // This only makes sense for x86-64.
2505 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2506 Expr *Callee = TheCall->getCallee();
2507 if (TT.getArch() != llvm::Triple::x86_64)
2508 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2509 // Don't allow this in System V ABI functions.
2510 clang::CallingConv CC = CC_C;
2511 if (const FunctionDecl *FD = getCurFunctionDecl())
2512 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2513 if (CC == CC_X86_64SysV ||
2514 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2515 return Diag(Callee->getLocStart(),
2516 diag::err_ms_va_start_used_in_sysv_function);
2517 return SemaBuiltinVAStartImpl(TheCall);
2518}
2519
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002520bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2521 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2522 // const char *named_addr);
2523
2524 Expr *Func = Call->getCallee();
2525
2526 if (Call->getNumArgs() < 3)
2527 return Diag(Call->getLocEnd(),
2528 diag::err_typecheck_call_too_few_args_at_least)
2529 << 0 /*function call*/ << 3 << Call->getNumArgs();
2530
2531 // Determine whether the current function is variadic or not.
2532 bool IsVariadic;
2533 if (BlockScopeInfo *CurBlock = getCurBlock())
2534 IsVariadic = CurBlock->TheDecl->isVariadic();
2535 else if (FunctionDecl *FD = getCurFunctionDecl())
2536 IsVariadic = FD->isVariadic();
2537 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2538 IsVariadic = MD->isVariadic();
2539 else
2540 llvm_unreachable("unexpected statement type");
2541
2542 if (!IsVariadic) {
2543 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2544 return true;
2545 }
2546
2547 // Type-check the first argument normally.
2548 if (checkBuiltinArgument(*this, Call, 0))
2549 return true;
2550
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002551 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002552 unsigned ArgNo;
2553 QualType Type;
2554 } ArgumentTypes[] = {
2555 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2556 { 2, Context.getSizeType() },
2557 };
2558
2559 for (const auto &AT : ArgumentTypes) {
2560 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2561 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2562 continue;
2563 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2564 << Arg->getType() << AT.Type << 1 /* different class */
2565 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2566 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2567 }
2568
2569 return false;
2570}
2571
Chris Lattner2da14fb2007-12-20 00:26:33 +00002572/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2573/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002574bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2575 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002576 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002577 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002578 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002579 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002580 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002581 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002582 << SourceRange(TheCall->getArg(2)->getLocStart(),
2583 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002584
John Wiegley01296292011-04-08 18:41:53 +00002585 ExprResult OrigArg0 = TheCall->getArg(0);
2586 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002587
Chris Lattner2da14fb2007-12-20 00:26:33 +00002588 // Do standard promotions between the two arguments, returning their common
2589 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002590 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002591 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2592 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002593
2594 // Make sure any conversions are pushed back into the call; this is
2595 // type safe since unordered compare builtins are declared as "_Bool
2596 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002597 TheCall->setArg(0, OrigArg0.get());
2598 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002599
John Wiegley01296292011-04-08 18:41:53 +00002600 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002601 return false;
2602
Chris Lattner2da14fb2007-12-20 00:26:33 +00002603 // If the common type isn't a real floating type, then the arguments were
2604 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002605 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002606 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002607 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002608 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2609 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002610
Chris Lattner2da14fb2007-12-20 00:26:33 +00002611 return false;
2612}
2613
Benjamin Kramer634fc102010-02-15 22:42:31 +00002614/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2615/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002616/// to check everything. We expect the last argument to be a floating point
2617/// value.
2618bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2619 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002620 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002621 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002622 if (TheCall->getNumArgs() > NumArgs)
2623 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002624 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002625 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002626 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002627 (*(TheCall->arg_end()-1))->getLocEnd());
2628
Benjamin Kramer64aae502010-02-16 10:07:31 +00002629 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002630
Eli Friedman7e4faac2009-08-31 20:06:00 +00002631 if (OrigArg->isTypeDependent())
2632 return false;
2633
Chris Lattner68784ef2010-05-06 05:50:07 +00002634 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002635 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002636 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002637 diag::err_typecheck_call_invalid_unary_fp)
2638 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002639
Chris Lattner68784ef2010-05-06 05:50:07 +00002640 // If this is an implicit conversion from float -> double, remove it.
2641 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2642 Expr *CastArg = Cast->getSubExpr();
2643 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2644 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2645 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002646 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002647 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002648 }
2649 }
2650
Eli Friedman7e4faac2009-08-31 20:06:00 +00002651 return false;
2652}
2653
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002654/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2655// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002656ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002657 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002658 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002659 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002660 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2661 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002662
Nate Begemana0110022010-06-08 00:16:34 +00002663 // Determine which of the following types of shufflevector we're checking:
2664 // 1) unary, vector mask: (lhs, mask)
2665 // 2) binary, vector mask: (lhs, rhs, mask)
2666 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2667 QualType resType = TheCall->getArg(0)->getType();
2668 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002669
Douglas Gregorc25f7662009-05-19 22:10:17 +00002670 if (!TheCall->getArg(0)->isTypeDependent() &&
2671 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002672 QualType LHSType = TheCall->getArg(0)->getType();
2673 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002674
Craig Topperbaca3892013-07-29 06:47:04 +00002675 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2676 return ExprError(Diag(TheCall->getLocStart(),
2677 diag::err_shufflevector_non_vector)
2678 << SourceRange(TheCall->getArg(0)->getLocStart(),
2679 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002680
Nate Begemana0110022010-06-08 00:16:34 +00002681 numElements = LHSType->getAs<VectorType>()->getNumElements();
2682 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002683
Nate Begemana0110022010-06-08 00:16:34 +00002684 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2685 // with mask. If so, verify that RHS is an integer vector type with the
2686 // same number of elts as lhs.
2687 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002688 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002689 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002690 return ExprError(Diag(TheCall->getLocStart(),
2691 diag::err_shufflevector_incompatible_vector)
2692 << SourceRange(TheCall->getArg(1)->getLocStart(),
2693 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002694 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002695 return ExprError(Diag(TheCall->getLocStart(),
2696 diag::err_shufflevector_incompatible_vector)
2697 << SourceRange(TheCall->getArg(0)->getLocStart(),
2698 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002699 } else if (numElements != numResElements) {
2700 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002701 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002702 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002703 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002704 }
2705
2706 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002707 if (TheCall->getArg(i)->isTypeDependent() ||
2708 TheCall->getArg(i)->isValueDependent())
2709 continue;
2710
Nate Begemana0110022010-06-08 00:16:34 +00002711 llvm::APSInt Result(32);
2712 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2713 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002714 diag::err_shufflevector_nonconstant_argument)
2715 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002716
Craig Topper50ad5b72013-08-03 17:40:38 +00002717 // Allow -1 which will be translated to undef in the IR.
2718 if (Result.isSigned() && Result.isAllOnesValue())
2719 continue;
2720
Chris Lattner7ab824e2008-08-10 02:05:13 +00002721 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002722 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002723 diag::err_shufflevector_argument_too_large)
2724 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002725 }
2726
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002727 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002728
Chris Lattner7ab824e2008-08-10 02:05:13 +00002729 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002730 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002731 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002732 }
2733
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002734 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2735 TheCall->getCallee()->getLocStart(),
2736 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002737}
Chris Lattner43be2e62007-12-19 23:59:04 +00002738
Hal Finkelc4d7c822013-09-18 03:29:45 +00002739/// SemaConvertVectorExpr - Handle __builtin_convertvector
2740ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2741 SourceLocation BuiltinLoc,
2742 SourceLocation RParenLoc) {
2743 ExprValueKind VK = VK_RValue;
2744 ExprObjectKind OK = OK_Ordinary;
2745 QualType DstTy = TInfo->getType();
2746 QualType SrcTy = E->getType();
2747
2748 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2749 return ExprError(Diag(BuiltinLoc,
2750 diag::err_convertvector_non_vector)
2751 << E->getSourceRange());
2752 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2753 return ExprError(Diag(BuiltinLoc,
2754 diag::err_convertvector_non_vector_type));
2755
2756 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2757 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2758 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2759 if (SrcElts != DstElts)
2760 return ExprError(Diag(BuiltinLoc,
2761 diag::err_convertvector_incompatible_vector)
2762 << E->getSourceRange());
2763 }
2764
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002765 return new (Context)
2766 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002767}
2768
Daniel Dunbarb7257262008-07-21 22:59:13 +00002769/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2770// This is declared to take (const void*, ...) and can take two
2771// optional constant int args.
2772bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002773 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002774
Chris Lattner3b054132008-11-19 05:08:23 +00002775 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002776 return Diag(TheCall->getLocEnd(),
2777 diag::err_typecheck_call_too_many_args_at_most)
2778 << 0 /*function call*/ << 3 << NumArgs
2779 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002780
2781 // Argument 0 is checked for us and the remaining arguments must be
2782 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002783 for (unsigned i = 1; i != NumArgs; ++i)
2784 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002785 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002786
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002787 return false;
2788}
2789
Hal Finkelf0417332014-07-17 14:25:55 +00002790/// SemaBuiltinAssume - Handle __assume (MS Extension).
2791// __assume does not evaluate its arguments, and should warn if its argument
2792// has side effects.
2793bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2794 Expr *Arg = TheCall->getArg(0);
2795 if (Arg->isInstantiationDependent()) return false;
2796
2797 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002798 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002799 << Arg->getSourceRange()
2800 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2801
2802 return false;
2803}
2804
2805/// Handle __builtin_assume_aligned. This is declared
2806/// as (const void*, size_t, ...) and can take one optional constant int arg.
2807bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2808 unsigned NumArgs = TheCall->getNumArgs();
2809
2810 if (NumArgs > 3)
2811 return Diag(TheCall->getLocEnd(),
2812 diag::err_typecheck_call_too_many_args_at_most)
2813 << 0 /*function call*/ << 3 << NumArgs
2814 << TheCall->getSourceRange();
2815
2816 // The alignment must be a constant integer.
2817 Expr *Arg = TheCall->getArg(1);
2818
2819 // We can't check the value of a dependent argument.
2820 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2821 llvm::APSInt Result;
2822 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2823 return true;
2824
2825 if (!Result.isPowerOf2())
2826 return Diag(TheCall->getLocStart(),
2827 diag::err_alignment_not_power_of_two)
2828 << Arg->getSourceRange();
2829 }
2830
2831 if (NumArgs > 2) {
2832 ExprResult Arg(TheCall->getArg(2));
2833 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2834 Context.getSizeType(), false);
2835 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2836 if (Arg.isInvalid()) return true;
2837 TheCall->setArg(2, Arg.get());
2838 }
Hal Finkelf0417332014-07-17 14:25:55 +00002839
2840 return false;
2841}
2842
Eric Christopher8d0c6212010-04-17 02:26:23 +00002843/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2844/// TheCall is a constant expression.
2845bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2846 llvm::APSInt &Result) {
2847 Expr *Arg = TheCall->getArg(ArgNum);
2848 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2849 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2850
2851 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2852
2853 if (!Arg->isIntegerConstantExpr(Result, Context))
2854 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002855 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002856
Chris Lattnerd545ad12009-09-23 06:06:36 +00002857 return false;
2858}
2859
Richard Sandiford28940af2014-04-16 08:47:51 +00002860/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2861/// TheCall is a constant expression in the range [Low, High].
2862bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2863 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002864 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002865
2866 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002867 Expr *Arg = TheCall->getArg(ArgNum);
2868 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002869 return false;
2870
Eric Christopher8d0c6212010-04-17 02:26:23 +00002871 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002872 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002873 return true;
2874
Richard Sandiford28940af2014-04-16 08:47:51 +00002875 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002876 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002877 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002878
2879 return false;
2880}
2881
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002882/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2883/// TheCall is an ARM/AArch64 special register string literal.
2884bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2885 int ArgNum, unsigned ExpectedFieldNum,
2886 bool AllowName) {
2887 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2888 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2889 BuiltinID == ARM::BI__builtin_arm_rsr ||
2890 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2891 BuiltinID == ARM::BI__builtin_arm_wsr ||
2892 BuiltinID == ARM::BI__builtin_arm_wsrp;
2893 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2894 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2895 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2896 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2897 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2898 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2899 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2900
2901 // We can't check the value of a dependent argument.
2902 Expr *Arg = TheCall->getArg(ArgNum);
2903 if (Arg->isTypeDependent() || Arg->isValueDependent())
2904 return false;
2905
2906 // Check if the argument is a string literal.
2907 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2908 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2909 << Arg->getSourceRange();
2910
2911 // Check the type of special register given.
2912 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2913 SmallVector<StringRef, 6> Fields;
2914 Reg.split(Fields, ":");
2915
2916 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2917 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2918 << Arg->getSourceRange();
2919
2920 // If the string is the name of a register then we cannot check that it is
2921 // valid here but if the string is of one the forms described in ACLE then we
2922 // can check that the supplied fields are integers and within the valid
2923 // ranges.
2924 if (Fields.size() > 1) {
2925 bool FiveFields = Fields.size() == 5;
2926
2927 bool ValidString = true;
2928 if (IsARMBuiltin) {
2929 ValidString &= Fields[0].startswith_lower("cp") ||
2930 Fields[0].startswith_lower("p");
2931 if (ValidString)
2932 Fields[0] =
2933 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2934
2935 ValidString &= Fields[2].startswith_lower("c");
2936 if (ValidString)
2937 Fields[2] = Fields[2].drop_front(1);
2938
2939 if (FiveFields) {
2940 ValidString &= Fields[3].startswith_lower("c");
2941 if (ValidString)
2942 Fields[3] = Fields[3].drop_front(1);
2943 }
2944 }
2945
2946 SmallVector<int, 5> Ranges;
2947 if (FiveFields)
2948 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2949 else
2950 Ranges.append({15, 7, 15});
2951
2952 for (unsigned i=0; i<Fields.size(); ++i) {
2953 int IntField;
2954 ValidString &= !Fields[i].getAsInteger(10, IntField);
2955 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2956 }
2957
2958 if (!ValidString)
2959 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2960 << Arg->getSourceRange();
2961
2962 } else if (IsAArch64Builtin && Fields.size() == 1) {
2963 // If the register name is one of those that appear in the condition below
2964 // and the special register builtin being used is one of the write builtins,
2965 // then we require that the argument provided for writing to the register
2966 // is an integer constant expression. This is because it will be lowered to
2967 // an MSR (immediate) instruction, so we need to know the immediate at
2968 // compile time.
2969 if (TheCall->getNumArgs() != 2)
2970 return false;
2971
2972 std::string RegLower = Reg.lower();
2973 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2974 RegLower != "pan" && RegLower != "uao")
2975 return false;
2976
2977 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2978 }
2979
2980 return false;
2981}
2982
Eli Friedmanc97d0142009-05-03 06:04:26 +00002983/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002984/// This checks that the target supports __builtin_longjmp and
2985/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002986bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002987 if (!Context.getTargetInfo().hasSjLjLowering())
2988 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2989 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2990
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002991 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002992 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002993
Eric Christopher8d0c6212010-04-17 02:26:23 +00002994 // TODO: This is less than ideal. Overload this to take a value.
2995 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2996 return true;
2997
2998 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002999 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3000 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3001
3002 return false;
3003}
3004
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003005
3006/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3007/// This checks that the target supports __builtin_setjmp.
3008bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3009 if (!Context.getTargetInfo().hasSjLjLowering())
3010 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3011 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3012 return false;
3013}
3014
Richard Smithd7293d72013-08-05 18:49:43 +00003015namespace {
3016enum StringLiteralCheckType {
3017 SLCT_NotALiteral,
3018 SLCT_UncheckedLiteral,
3019 SLCT_CheckedLiteral
3020};
3021}
3022
Richard Smith55ce3522012-06-25 20:30:08 +00003023// Determine if an expression is a string literal or constant string.
3024// If this function returns false on the arguments to a function expecting a
3025// format string, we will usually need to emit a warning.
3026// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003027static StringLiteralCheckType
3028checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3029 bool HasVAListArg, unsigned format_idx,
3030 unsigned firstDataArg, Sema::FormatStringType Type,
3031 Sema::VariadicCallType CallType, bool InFunctionCall,
3032 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003033 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003034 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003035 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003036
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003037 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003038
Richard Smithd7293d72013-08-05 18:49:43 +00003039 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003040 // Technically -Wformat-nonliteral does not warn about this case.
3041 // The behavior of printf and friends in this case is implementation
3042 // dependent. Ideally if the format string cannot be null then
3043 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003044 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003045
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003046 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003047 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003048 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003049 // The expression is a literal if both sub-expressions were, and it was
3050 // completely checked only if both sub-expressions were checked.
3051 const AbstractConditionalOperator *C =
3052 cast<AbstractConditionalOperator>(E);
3053 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003054 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003055 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003056 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003057 if (Left == SLCT_NotALiteral)
3058 return SLCT_NotALiteral;
3059 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003060 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003061 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003062 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003063 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003064 }
3065
3066 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003067 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3068 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003069 }
3070
John McCallc07a0c72011-02-17 10:25:35 +00003071 case Stmt::OpaqueValueExprClass:
3072 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3073 E = src;
3074 goto tryAgain;
3075 }
Richard Smith55ce3522012-06-25 20:30:08 +00003076 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003077
Ted Kremeneka8890832011-02-24 23:03:04 +00003078 case Stmt::PredefinedExprClass:
3079 // While __func__, etc., are technically not string literals, they
3080 // cannot contain format specifiers and thus are not a security
3081 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003082 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003083
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003084 case Stmt::DeclRefExprClass: {
3085 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003086
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003087 // As an exception, do not flag errors for variables binding to
3088 // const string literals.
3089 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3090 bool isConstant = false;
3091 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003092
Richard Smithd7293d72013-08-05 18:49:43 +00003093 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3094 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003095 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003096 isConstant = T.isConstant(S.Context) &&
3097 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003098 } else if (T->isObjCObjectPointerType()) {
3099 // In ObjC, there is usually no "const ObjectPointer" type,
3100 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003101 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003104 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003105 if (const Expr *Init = VD->getAnyInitializer()) {
3106 // Look through initializers like const char c[] = { "foo" }
3107 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3108 if (InitList->isStringLiteralInit())
3109 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3110 }
Richard Smithd7293d72013-08-05 18:49:43 +00003111 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003112 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003113 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003114 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003115 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003116 }
Mike Stump11289f42009-09-09 15:08:12 +00003117
Anders Carlssonb012ca92009-06-28 19:55:58 +00003118 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3119 // special check to see if the format string is a function parameter
3120 // of the function calling the printf function. If the function
3121 // has an attribute indicating it is a printf-like function, then we
3122 // should suppress warnings concerning non-literals being used in a call
3123 // to a vprintf function. For example:
3124 //
3125 // void
3126 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3127 // va_list ap;
3128 // va_start(ap, fmt);
3129 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3130 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003131 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003132 if (HasVAListArg) {
3133 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3134 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3135 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003136 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003137 // adjust for implicit parameter
3138 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3139 if (MD->isInstance())
3140 ++PVIndex;
3141 // We also check if the formats are compatible.
3142 // We can't pass a 'scanf' string to a 'printf' function.
3143 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003144 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003145 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003146 }
3147 }
3148 }
3149 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
Richard Smith55ce3522012-06-25 20:30:08 +00003152 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003153 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003154
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003155 case Stmt::CallExprClass:
3156 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003157 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003158 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3159 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3160 unsigned ArgIndex = FA->getFormatIdx();
3161 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3162 if (MD->isInstance())
3163 --ArgIndex;
3164 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003165
Richard Smithd7293d72013-08-05 18:49:43 +00003166 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003167 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003168 Type, CallType, InFunctionCall,
3169 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003170 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3171 unsigned BuiltinID = FD->getBuiltinID();
3172 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3173 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3174 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003175 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003176 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003177 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003178 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003179 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003180 }
3181 }
Mike Stump11289f42009-09-09 15:08:12 +00003182
Richard Smith55ce3522012-06-25 20:30:08 +00003183 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003184 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003185 case Stmt::ObjCStringLiteralClass:
3186 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003187 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003188
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003189 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003190 StrE = ObjCFExpr->getString();
3191 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003192 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003193
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003194 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003195 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3196 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003197 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003198 }
Mike Stump11289f42009-09-09 15:08:12 +00003199
Richard Smith55ce3522012-06-25 20:30:08 +00003200 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003203 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003204 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003205 }
3206}
3207
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003208Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003209 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003210 .Case("scanf", FST_Scanf)
3211 .Cases("printf", "printf0", FST_Printf)
3212 .Cases("NSString", "CFString", FST_NSString)
3213 .Case("strftime", FST_Strftime)
3214 .Case("strfmon", FST_Strfmon)
3215 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003216 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003217 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003218 .Default(FST_Unknown);
3219}
3220
Jordan Rose3e0ec582012-07-19 18:10:23 +00003221/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003222/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003223/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003224bool Sema::CheckFormatArguments(const FormatAttr *Format,
3225 ArrayRef<const Expr *> Args,
3226 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003227 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003228 SourceLocation Loc, SourceRange Range,
3229 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003230 FormatStringInfo FSI;
3231 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003232 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003233 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003234 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003235 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003236}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003237
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003238bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003239 bool HasVAListArg, unsigned format_idx,
3240 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003241 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003242 SourceLocation Loc, SourceRange Range,
3243 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003244 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003245 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003246 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003247 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003248 }
Mike Stump11289f42009-09-09 15:08:12 +00003249
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003250 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003251
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003252 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003253 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003254 // Dynamically generated format strings are difficult to
3255 // automatically vet at compile time. Requiring that format strings
3256 // are string literals: (1) permits the checking of format strings by
3257 // the compiler and thereby (2) can practically remove the source of
3258 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003259
Mike Stump11289f42009-09-09 15:08:12 +00003260 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003261 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003262 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003263 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003264 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003265 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3266 format_idx, firstDataArg, Type, CallType,
3267 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003268 if (CT != SLCT_NotALiteral)
3269 // Literal format string found, check done!
3270 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003271
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003272 // Strftime is particular as it always uses a single 'time' argument,
3273 // so it is safe to pass a non-literal string.
3274 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003275 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003276
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003277 // Do not emit diag when the string param is a macro expansion and the
3278 // format is either NSString or CFString. This is a hack to prevent
3279 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3280 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003281 if (Type == FST_NSString &&
3282 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003283 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003284
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003285 // If there are no arguments specified, warn with -Wformat-security, otherwise
3286 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003287 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003288 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003289 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003290 << OrigFormatExpr->getSourceRange();
3291 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003292 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003293 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003294 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003295 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003296}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003297
Ted Kremenekab278de2010-01-28 23:39:18 +00003298namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003299class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3300protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003301 Sema &S;
3302 const StringLiteral *FExpr;
3303 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003304 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003305 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003306 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003307 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003308 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003309 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003310 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003311 bool usesPositionalArgs;
3312 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003313 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003314 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003315 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003316public:
Ted Kremenek02087932010-07-16 02:11:22 +00003317 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003318 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003319 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003320 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003321 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003322 Sema::VariadicCallType callType,
3323 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003324 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003325 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3326 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003327 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003328 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003329 inFunctionCall(inFunctionCall), CallType(callType),
3330 CheckedVarArgs(CheckedVarArgs) {
3331 CoveredArgs.resize(numDataArgs);
3332 CoveredArgs.reset();
3333 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003334
Ted Kremenek019d2242010-01-29 01:50:07 +00003335 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003336
Ted Kremenek02087932010-07-16 02:11:22 +00003337 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003338 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003339
Jordan Rose92303592012-09-08 04:00:03 +00003340 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003341 const analyze_format_string::FormatSpecifier &FS,
3342 const analyze_format_string::ConversionSpecifier &CS,
3343 const char *startSpecifier, unsigned specifierLen,
3344 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003345
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003346 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003347 const analyze_format_string::FormatSpecifier &FS,
3348 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003349
3350 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003351 const analyze_format_string::ConversionSpecifier &CS,
3352 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003353
Craig Toppere14c0f82014-03-12 04:55:44 +00003354 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003355
Craig Toppere14c0f82014-03-12 04:55:44 +00003356 void HandleInvalidPosition(const char *startSpecifier,
3357 unsigned specifierLen,
3358 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003359
Craig Toppere14c0f82014-03-12 04:55:44 +00003360 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003361
Craig Toppere14c0f82014-03-12 04:55:44 +00003362 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003363
Richard Trieu03cf7b72011-10-28 00:41:25 +00003364 template <typename Range>
3365 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3366 const Expr *ArgumentExpr,
3367 PartialDiagnostic PDiag,
3368 SourceLocation StringLoc,
3369 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003370 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003371
Ted Kremenek02087932010-07-16 02:11:22 +00003372protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003373 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3374 const char *startSpec,
3375 unsigned specifierLen,
3376 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003377
3378 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3379 const char *startSpec,
3380 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003381
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003382 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003383 CharSourceRange getSpecifierRange(const char *startSpecifier,
3384 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003385 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003386
Ted Kremenek5739de72010-01-29 01:06:55 +00003387 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003388
3389 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3390 const analyze_format_string::ConversionSpecifier &CS,
3391 const char *startSpecifier, unsigned specifierLen,
3392 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003393
3394 template <typename Range>
3395 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3396 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003397 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003398};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003399}
Ted Kremenekab278de2010-01-28 23:39:18 +00003400
Ted Kremenek02087932010-07-16 02:11:22 +00003401SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003402 return OrigFormatExpr->getSourceRange();
3403}
3404
Ted Kremenek02087932010-07-16 02:11:22 +00003405CharSourceRange CheckFormatHandler::
3406getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003407 SourceLocation Start = getLocationOfByte(startSpecifier);
3408 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3409
3410 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003411 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003412
3413 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003414}
3415
Ted Kremenek02087932010-07-16 02:11:22 +00003416SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003417 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003418}
3419
Ted Kremenek02087932010-07-16 02:11:22 +00003420void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3421 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003422 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3423 getLocationOfByte(startSpecifier),
3424 /*IsStringLocation*/true,
3425 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003426}
3427
Jordan Rose92303592012-09-08 04:00:03 +00003428void CheckFormatHandler::HandleInvalidLengthModifier(
3429 const analyze_format_string::FormatSpecifier &FS,
3430 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003431 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003432 using namespace analyze_format_string;
3433
3434 const LengthModifier &LM = FS.getLengthModifier();
3435 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3436
3437 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003438 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003439 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003440 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003441 getLocationOfByte(LM.getStart()),
3442 /*IsStringLocation*/true,
3443 getSpecifierRange(startSpecifier, specifierLen));
3444
3445 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3446 << FixedLM->toString()
3447 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3448
3449 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003450 FixItHint Hint;
3451 if (DiagID == diag::warn_format_nonsensical_length)
3452 Hint = FixItHint::CreateRemoval(LMRange);
3453
3454 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003455 getLocationOfByte(LM.getStart()),
3456 /*IsStringLocation*/true,
3457 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003458 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003459 }
3460}
3461
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003462void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003463 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003464 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003465 using namespace analyze_format_string;
3466
3467 const LengthModifier &LM = FS.getLengthModifier();
3468 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3469
3470 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003471 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003472 if (FixedLM) {
3473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3474 << LM.toString() << 0,
3475 getLocationOfByte(LM.getStart()),
3476 /*IsStringLocation*/true,
3477 getSpecifierRange(startSpecifier, specifierLen));
3478
3479 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3480 << FixedLM->toString()
3481 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3482
3483 } else {
3484 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3485 << LM.toString() << 0,
3486 getLocationOfByte(LM.getStart()),
3487 /*IsStringLocation*/true,
3488 getSpecifierRange(startSpecifier, specifierLen));
3489 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003490}
3491
3492void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3493 const analyze_format_string::ConversionSpecifier &CS,
3494 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003495 using namespace analyze_format_string;
3496
3497 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003498 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003499 if (FixedCS) {
3500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3501 << CS.toString() << /*conversion specifier*/1,
3502 getLocationOfByte(CS.getStart()),
3503 /*IsStringLocation*/true,
3504 getSpecifierRange(startSpecifier, specifierLen));
3505
3506 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3507 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3508 << FixedCS->toString()
3509 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3510 } else {
3511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3512 << CS.toString() << /*conversion specifier*/1,
3513 getLocationOfByte(CS.getStart()),
3514 /*IsStringLocation*/true,
3515 getSpecifierRange(startSpecifier, specifierLen));
3516 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003517}
3518
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003519void CheckFormatHandler::HandlePosition(const char *startPos,
3520 unsigned posLen) {
3521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3522 getLocationOfByte(startPos),
3523 /*IsStringLocation*/true,
3524 getSpecifierRange(startPos, posLen));
3525}
3526
Ted Kremenekd1668192010-02-27 01:41:03 +00003527void
Ted Kremenek02087932010-07-16 02:11:22 +00003528CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3529 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3531 << (unsigned) p,
3532 getLocationOfByte(startPos), /*IsStringLocation*/true,
3533 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003534}
3535
Ted Kremenek02087932010-07-16 02:11:22 +00003536void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003537 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003538 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3539 getLocationOfByte(startPos),
3540 /*IsStringLocation*/true,
3541 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003542}
3543
Ted Kremenek02087932010-07-16 02:11:22 +00003544void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003545 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003546 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003547 EmitFormatDiagnostic(
3548 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3549 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3550 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003551 }
Ted Kremenek02087932010-07-16 02:11:22 +00003552}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003553
Jordan Rose58bbe422012-07-19 18:10:08 +00003554// Note that this may return NULL if there was an error parsing or building
3555// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003556const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003557 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003558}
3559
3560void CheckFormatHandler::DoneProcessing() {
3561 // Does the number of data arguments exceed the number of
3562 // format conversions in the format string?
3563 if (!HasVAListArg) {
3564 // Find any arguments that weren't covered.
3565 CoveredArgs.flip();
3566 signed notCoveredArg = CoveredArgs.find_first();
3567 if (notCoveredArg >= 0) {
3568 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003569 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3570 SourceLocation Loc = E->getLocStart();
3571 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3572 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3573 Loc, /*IsStringLocation*/false,
3574 getFormatStringRange());
3575 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003576 }
Ted Kremenek02087932010-07-16 02:11:22 +00003577 }
3578 }
3579}
3580
Ted Kremenekce815422010-07-19 21:25:57 +00003581bool
3582CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3583 SourceLocation Loc,
3584 const char *startSpec,
3585 unsigned specifierLen,
3586 const char *csStart,
3587 unsigned csLen) {
3588
3589 bool keepGoing = true;
3590 if (argIndex < NumDataArgs) {
3591 // Consider the argument coverered, even though the specifier doesn't
3592 // make sense.
3593 CoveredArgs.set(argIndex);
3594 }
3595 else {
3596 // If argIndex exceeds the number of data arguments we
3597 // don't issue a warning because that is just a cascade of warnings (and
3598 // they may have intended '%%' anyway). We don't want to continue processing
3599 // the format string after this point, however, as we will like just get
3600 // gibberish when trying to match arguments.
3601 keepGoing = false;
3602 }
3603
Richard Trieu03cf7b72011-10-28 00:41:25 +00003604 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3605 << StringRef(csStart, csLen),
3606 Loc, /*IsStringLocation*/true,
3607 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003608
3609 return keepGoing;
3610}
3611
Richard Trieu03cf7b72011-10-28 00:41:25 +00003612void
3613CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3614 const char *startSpec,
3615 unsigned specifierLen) {
3616 EmitFormatDiagnostic(
3617 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3618 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3619}
3620
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003621bool
3622CheckFormatHandler::CheckNumArgs(
3623 const analyze_format_string::FormatSpecifier &FS,
3624 const analyze_format_string::ConversionSpecifier &CS,
3625 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3626
3627 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003628 PartialDiagnostic PDiag = FS.usesPositionalArg()
3629 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3630 << (argIndex+1) << NumDataArgs)
3631 : S.PDiag(diag::warn_printf_insufficient_data_args);
3632 EmitFormatDiagnostic(
3633 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3634 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003635 return false;
3636 }
3637 return true;
3638}
3639
Richard Trieu03cf7b72011-10-28 00:41:25 +00003640template<typename Range>
3641void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3642 SourceLocation Loc,
3643 bool IsStringLocation,
3644 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003645 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003646 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003647 Loc, IsStringLocation, StringRange, FixIt);
3648}
3649
3650/// \brief If the format string is not within the funcion call, emit a note
3651/// so that the function call and string are in diagnostic messages.
3652///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003653/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003654/// call and only one diagnostic message will be produced. Otherwise, an
3655/// extra note will be emitted pointing to location of the format string.
3656///
3657/// \param ArgumentExpr the expression that is passed as the format string
3658/// argument in the function call. Used for getting locations when two
3659/// diagnostics are emitted.
3660///
3661/// \param PDiag the callee should already have provided any strings for the
3662/// diagnostic message. This function only adds locations and fixits
3663/// to diagnostics.
3664///
3665/// \param Loc primary location for diagnostic. If two diagnostics are
3666/// required, one will be at Loc and a new SourceLocation will be created for
3667/// the other one.
3668///
3669/// \param IsStringLocation if true, Loc points to the format string should be
3670/// used for the note. Otherwise, Loc points to the argument list and will
3671/// be used with PDiag.
3672///
3673/// \param StringRange some or all of the string to highlight. This is
3674/// templated so it can accept either a CharSourceRange or a SourceRange.
3675///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003676/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003677template<typename Range>
3678void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3679 const Expr *ArgumentExpr,
3680 PartialDiagnostic PDiag,
3681 SourceLocation Loc,
3682 bool IsStringLocation,
3683 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003684 ArrayRef<FixItHint> FixIt) {
3685 if (InFunctionCall) {
3686 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3687 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003688 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003689 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003690 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3691 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003692
3693 const Sema::SemaDiagnosticBuilder &Note =
3694 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3695 diag::note_format_string_defined);
3696
3697 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003698 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003699 }
3700}
3701
Ted Kremenek02087932010-07-16 02:11:22 +00003702//===--- CHECK: Printf format string checking ------------------------------===//
3703
3704namespace {
3705class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003706 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003707public:
3708 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3709 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003710 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003711 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003712 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003713 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003714 Sema::VariadicCallType CallType,
3715 llvm::SmallBitVector &CheckedVarArgs)
3716 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3717 numDataArgs, beg, hasVAListArg, Args,
3718 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3719 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003720 {}
3721
Craig Toppere14c0f82014-03-12 04:55:44 +00003722
Ted Kremenek02087932010-07-16 02:11:22 +00003723 bool HandleInvalidPrintfConversionSpecifier(
3724 const analyze_printf::PrintfSpecifier &FS,
3725 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003726 unsigned specifierLen) override;
3727
Ted Kremenek02087932010-07-16 02:11:22 +00003728 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3729 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003730 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003731 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3732 const char *StartSpecifier,
3733 unsigned SpecifierLen,
3734 const Expr *E);
3735
Ted Kremenek02087932010-07-16 02:11:22 +00003736 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3737 const char *startSpecifier, unsigned specifierLen);
3738 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3739 const analyze_printf::OptionalAmount &Amt,
3740 unsigned type,
3741 const char *startSpecifier, unsigned specifierLen);
3742 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3743 const analyze_printf::OptionalFlag &flag,
3744 const char *startSpecifier, unsigned specifierLen);
3745 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3746 const analyze_printf::OptionalFlag &ignoredFlag,
3747 const analyze_printf::OptionalFlag &flag,
3748 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003749 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003750 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003751
3752 void HandleEmptyObjCModifierFlag(const char *startFlag,
3753 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003754
Ted Kremenek2b417712015-07-02 05:39:16 +00003755 void HandleInvalidObjCModifierFlag(const char *startFlag,
3756 unsigned flagLen) override;
3757
3758 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3759 const char *flagsEnd,
3760 const char *conversionPosition)
3761 override;
3762};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003763}
Ted Kremenek02087932010-07-16 02:11:22 +00003764
3765bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3766 const analyze_printf::PrintfSpecifier &FS,
3767 const char *startSpecifier,
3768 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003769 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003770 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003771
Ted Kremenekce815422010-07-19 21:25:57 +00003772 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3773 getLocationOfByte(CS.getStart()),
3774 startSpecifier, specifierLen,
3775 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003776}
3777
Ted Kremenek02087932010-07-16 02:11:22 +00003778bool CheckPrintfHandler::HandleAmount(
3779 const analyze_format_string::OptionalAmount &Amt,
3780 unsigned k, const char *startSpecifier,
3781 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003782
3783 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003784 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003785 unsigned argIndex = Amt.getArgIndex();
3786 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003787 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3788 << k,
3789 getLocationOfByte(Amt.getStart()),
3790 /*IsStringLocation*/true,
3791 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003792 // Don't do any more checking. We will just emit
3793 // spurious errors.
3794 return false;
3795 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003796
Ted Kremenek5739de72010-01-29 01:06:55 +00003797 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003798 // Although not in conformance with C99, we also allow the argument to be
3799 // an 'unsigned int' as that is a reasonably safe case. GCC also
3800 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003801 CoveredArgs.set(argIndex);
3802 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003803 if (!Arg)
3804 return false;
3805
Ted Kremenek5739de72010-01-29 01:06:55 +00003806 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003807
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003808 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3809 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003810
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003811 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003812 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003813 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003814 << T << Arg->getSourceRange(),
3815 getLocationOfByte(Amt.getStart()),
3816 /*IsStringLocation*/true,
3817 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003818 // Don't do any more checking. We will just emit
3819 // spurious errors.
3820 return false;
3821 }
3822 }
3823 }
3824 return true;
3825}
Ted Kremenek5739de72010-01-29 01:06:55 +00003826
Tom Careb49ec692010-06-17 19:00:27 +00003827void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003828 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003829 const analyze_printf::OptionalAmount &Amt,
3830 unsigned type,
3831 const char *startSpecifier,
3832 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003833 const analyze_printf::PrintfConversionSpecifier &CS =
3834 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003835
Richard Trieu03cf7b72011-10-28 00:41:25 +00003836 FixItHint fixit =
3837 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3838 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3839 Amt.getConstantLength()))
3840 : FixItHint();
3841
3842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3843 << type << CS.toString(),
3844 getLocationOfByte(Amt.getStart()),
3845 /*IsStringLocation*/true,
3846 getSpecifierRange(startSpecifier, specifierLen),
3847 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003848}
3849
Ted Kremenek02087932010-07-16 02:11:22 +00003850void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003851 const analyze_printf::OptionalFlag &flag,
3852 const char *startSpecifier,
3853 unsigned specifierLen) {
3854 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003855 const analyze_printf::PrintfConversionSpecifier &CS =
3856 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003857 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3858 << flag.toString() << CS.toString(),
3859 getLocationOfByte(flag.getPosition()),
3860 /*IsStringLocation*/true,
3861 getSpecifierRange(startSpecifier, specifierLen),
3862 FixItHint::CreateRemoval(
3863 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003864}
3865
3866void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003867 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003868 const analyze_printf::OptionalFlag &ignoredFlag,
3869 const analyze_printf::OptionalFlag &flag,
3870 const char *startSpecifier,
3871 unsigned specifierLen) {
3872 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003873 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3874 << ignoredFlag.toString() << flag.toString(),
3875 getLocationOfByte(ignoredFlag.getPosition()),
3876 /*IsStringLocation*/true,
3877 getSpecifierRange(startSpecifier, specifierLen),
3878 FixItHint::CreateRemoval(
3879 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003880}
3881
Ted Kremenek2b417712015-07-02 05:39:16 +00003882// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3883// bool IsStringLocation, Range StringRange,
3884// ArrayRef<FixItHint> Fixit = None);
3885
3886void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3887 unsigned flagLen) {
3888 // Warn about an empty flag.
3889 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3890 getLocationOfByte(startFlag),
3891 /*IsStringLocation*/true,
3892 getSpecifierRange(startFlag, flagLen));
3893}
3894
3895void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3896 unsigned flagLen) {
3897 // Warn about an invalid flag.
3898 auto Range = getSpecifierRange(startFlag, flagLen);
3899 StringRef flag(startFlag, flagLen);
3900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3901 getLocationOfByte(startFlag),
3902 /*IsStringLocation*/true,
3903 Range, FixItHint::CreateRemoval(Range));
3904}
3905
3906void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3907 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3908 // Warn about using '[...]' without a '@' conversion.
3909 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3910 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3911 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3912 getLocationOfByte(conversionPosition),
3913 /*IsStringLocation*/true,
3914 Range, FixItHint::CreateRemoval(Range));
3915}
3916
Richard Smith55ce3522012-06-25 20:30:08 +00003917// Determines if the specified is a C++ class or struct containing
3918// a member with the specified name and kind (e.g. a CXXMethodDecl named
3919// "c_str()").
3920template<typename MemberKind>
3921static llvm::SmallPtrSet<MemberKind*, 1>
3922CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3923 const RecordType *RT = Ty->getAs<RecordType>();
3924 llvm::SmallPtrSet<MemberKind*, 1> Results;
3925
3926 if (!RT)
3927 return Results;
3928 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003929 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003930 return Results;
3931
Alp Tokerb6cc5922014-05-03 03:45:55 +00003932 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003933 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003934 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003935
3936 // We just need to include all members of the right kind turned up by the
3937 // filter, at this point.
3938 if (S.LookupQualifiedName(R, RT->getDecl()))
3939 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3940 NamedDecl *decl = (*I)->getUnderlyingDecl();
3941 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3942 Results.insert(FK);
3943 }
3944 return Results;
3945}
3946
Richard Smith2868a732014-02-28 01:36:39 +00003947/// Check if we could call '.c_str()' on an object.
3948///
3949/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3950/// allow the call, or if it would be ambiguous).
3951bool Sema::hasCStrMethod(const Expr *E) {
3952 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3953 MethodSet Results =
3954 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3955 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3956 MI != ME; ++MI)
3957 if ((*MI)->getMinRequiredArguments() == 0)
3958 return true;
3959 return false;
3960}
3961
Richard Smith55ce3522012-06-25 20:30:08 +00003962// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003963// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003964// Returns true when a c_str() conversion method is found.
3965bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003966 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003967 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3968
3969 MethodSet Results =
3970 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3971
3972 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3973 MI != ME; ++MI) {
3974 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003975 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003976 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003977 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003978 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003979 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3980 << "c_str()"
3981 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3982 return true;
3983 }
3984 }
3985
3986 return false;
3987}
3988
Ted Kremenekab278de2010-01-28 23:39:18 +00003989bool
Ted Kremenek02087932010-07-16 02:11:22 +00003990CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003991 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003992 const char *startSpecifier,
3993 unsigned specifierLen) {
3994
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003995 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003996 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003997 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003998
Ted Kremenek6cd69422010-07-19 22:01:06 +00003999 if (FS.consumesDataArgument()) {
4000 if (atFirstArg) {
4001 atFirstArg = false;
4002 usesPositionalArgs = FS.usesPositionalArg();
4003 }
4004 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004005 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4006 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004007 return false;
4008 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004009 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004010
Ted Kremenekd1668192010-02-27 01:41:03 +00004011 // First check if the field width, precision, and conversion specifier
4012 // have matching data arguments.
4013 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4014 startSpecifier, specifierLen)) {
4015 return false;
4016 }
4017
4018 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4019 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004020 return false;
4021 }
4022
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004023 if (!CS.consumesDataArgument()) {
4024 // FIXME: Technically specifying a precision or field width here
4025 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004026 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004027 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004028
Ted Kremenek4a49d982010-02-26 19:18:41 +00004029 // Consume the argument.
4030 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004031 if (argIndex < NumDataArgs) {
4032 // The check to see if the argIndex is valid will come later.
4033 // We set the bit here because we may exit early from this
4034 // function if we encounter some other error.
4035 CoveredArgs.set(argIndex);
4036 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004037
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004038 // FreeBSD kernel extensions.
4039 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4040 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4041 // We need at least two arguments.
4042 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4043 return false;
4044
4045 // Claim the second argument.
4046 CoveredArgs.set(argIndex + 1);
4047
4048 // Type check the first argument (int for %b, pointer for %D)
4049 const Expr *Ex = getDataArg(argIndex);
4050 const analyze_printf::ArgType &AT =
4051 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4052 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4053 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4054 EmitFormatDiagnostic(
4055 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4056 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4057 << false << Ex->getSourceRange(),
4058 Ex->getLocStart(), /*IsStringLocation*/false,
4059 getSpecifierRange(startSpecifier, specifierLen));
4060
4061 // Type check the second argument (char * for both %b and %D)
4062 Ex = getDataArg(argIndex + 1);
4063 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4064 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4065 EmitFormatDiagnostic(
4066 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4067 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4068 << false << Ex->getSourceRange(),
4069 Ex->getLocStart(), /*IsStringLocation*/false,
4070 getSpecifierRange(startSpecifier, specifierLen));
4071
4072 return true;
4073 }
4074
Ted Kremenek4a49d982010-02-26 19:18:41 +00004075 // Check for using an Objective-C specific conversion specifier
4076 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004077 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004078 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4079 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004080 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004081
Tom Careb49ec692010-06-17 19:00:27 +00004082 // Check for invalid use of field width
4083 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004084 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004085 startSpecifier, specifierLen);
4086 }
4087
4088 // Check for invalid use of precision
4089 if (!FS.hasValidPrecision()) {
4090 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4091 startSpecifier, specifierLen);
4092 }
4093
4094 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004095 if (!FS.hasValidThousandsGroupingPrefix())
4096 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004097 if (!FS.hasValidLeadingZeros())
4098 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4099 if (!FS.hasValidPlusPrefix())
4100 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004101 if (!FS.hasValidSpacePrefix())
4102 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004103 if (!FS.hasValidAlternativeForm())
4104 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4105 if (!FS.hasValidLeftJustified())
4106 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4107
4108 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004109 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4110 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4111 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004112 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4113 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4114 startSpecifier, specifierLen);
4115
4116 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004117 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004118 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4119 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004120 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004121 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004122 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004123 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4124 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004125
Jordan Rose92303592012-09-08 04:00:03 +00004126 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4127 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4128
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004129 // The remaining checks depend on the data arguments.
4130 if (HasVAListArg)
4131 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004132
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004133 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004134 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004135
Jordan Rose58bbe422012-07-19 18:10:08 +00004136 const Expr *Arg = getDataArg(argIndex);
4137 if (!Arg)
4138 return true;
4139
4140 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004141}
4142
Jordan Roseaee34382012-09-05 22:56:26 +00004143static bool requiresParensToAddCast(const Expr *E) {
4144 // FIXME: We should have a general way to reason about operator
4145 // precedence and whether parens are actually needed here.
4146 // Take care of a few common cases where they aren't.
4147 const Expr *Inside = E->IgnoreImpCasts();
4148 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4149 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4150
4151 switch (Inside->getStmtClass()) {
4152 case Stmt::ArraySubscriptExprClass:
4153 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004154 case Stmt::CharacterLiteralClass:
4155 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004156 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004157 case Stmt::FloatingLiteralClass:
4158 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004159 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004160 case Stmt::ObjCArrayLiteralClass:
4161 case Stmt::ObjCBoolLiteralExprClass:
4162 case Stmt::ObjCBoxedExprClass:
4163 case Stmt::ObjCDictionaryLiteralClass:
4164 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004165 case Stmt::ObjCIvarRefExprClass:
4166 case Stmt::ObjCMessageExprClass:
4167 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004168 case Stmt::ObjCStringLiteralClass:
4169 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004170 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004171 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004172 case Stmt::UnaryOperatorClass:
4173 return false;
4174 default:
4175 return true;
4176 }
4177}
4178
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004179static std::pair<QualType, StringRef>
4180shouldNotPrintDirectly(const ASTContext &Context,
4181 QualType IntendedTy,
4182 const Expr *E) {
4183 // Use a 'while' to peel off layers of typedefs.
4184 QualType TyTy = IntendedTy;
4185 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4186 StringRef Name = UserTy->getDecl()->getName();
4187 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4188 .Case("NSInteger", Context.LongTy)
4189 .Case("NSUInteger", Context.UnsignedLongTy)
4190 .Case("SInt32", Context.IntTy)
4191 .Case("UInt32", Context.UnsignedIntTy)
4192 .Default(QualType());
4193
4194 if (!CastTy.isNull())
4195 return std::make_pair(CastTy, Name);
4196
4197 TyTy = UserTy->desugar();
4198 }
4199
4200 // Strip parens if necessary.
4201 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4202 return shouldNotPrintDirectly(Context,
4203 PE->getSubExpr()->getType(),
4204 PE->getSubExpr());
4205
4206 // If this is a conditional expression, then its result type is constructed
4207 // via usual arithmetic conversions and thus there might be no necessary
4208 // typedef sugar there. Recurse to operands to check for NSInteger &
4209 // Co. usage condition.
4210 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4211 QualType TrueTy, FalseTy;
4212 StringRef TrueName, FalseName;
4213
4214 std::tie(TrueTy, TrueName) =
4215 shouldNotPrintDirectly(Context,
4216 CO->getTrueExpr()->getType(),
4217 CO->getTrueExpr());
4218 std::tie(FalseTy, FalseName) =
4219 shouldNotPrintDirectly(Context,
4220 CO->getFalseExpr()->getType(),
4221 CO->getFalseExpr());
4222
4223 if (TrueTy == FalseTy)
4224 return std::make_pair(TrueTy, TrueName);
4225 else if (TrueTy.isNull())
4226 return std::make_pair(FalseTy, FalseName);
4227 else if (FalseTy.isNull())
4228 return std::make_pair(TrueTy, TrueName);
4229 }
4230
4231 return std::make_pair(QualType(), StringRef());
4232}
4233
Richard Smith55ce3522012-06-25 20:30:08 +00004234bool
4235CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4236 const char *StartSpecifier,
4237 unsigned SpecifierLen,
4238 const Expr *E) {
4239 using namespace analyze_format_string;
4240 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004241 // Now type check the data expression that matches the
4242 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004243 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4244 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004245 if (!AT.isValid())
4246 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004247
Jordan Rose598ec092012-12-05 18:44:40 +00004248 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004249 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4250 ExprTy = TET->getUnderlyingExpr()->getType();
4251 }
4252
Seth Cantrellb4802962015-03-04 03:12:10 +00004253 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4254
4255 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004256 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004257 }
Jordan Rose98709982012-06-04 22:48:57 +00004258
Jordan Rose22b74712012-09-05 22:56:19 +00004259 // Look through argument promotions for our error message's reported type.
4260 // This includes the integral and floating promotions, but excludes array
4261 // and function pointer decay; seeing that an argument intended to be a
4262 // string has type 'char [6]' is probably more confusing than 'char *'.
4263 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4264 if (ICE->getCastKind() == CK_IntegralCast ||
4265 ICE->getCastKind() == CK_FloatingCast) {
4266 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004267 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004268
4269 // Check if we didn't match because of an implicit cast from a 'char'
4270 // or 'short' to an 'int'. This is done because printf is a varargs
4271 // function.
4272 if (ICE->getType() == S.Context.IntTy ||
4273 ICE->getType() == S.Context.UnsignedIntTy) {
4274 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004275 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004276 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004277 }
Jordan Rose98709982012-06-04 22:48:57 +00004278 }
Jordan Rose598ec092012-12-05 18:44:40 +00004279 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4280 // Special case for 'a', which has type 'int' in C.
4281 // Note, however, that we do /not/ want to treat multibyte constants like
4282 // 'MooV' as characters! This form is deprecated but still exists.
4283 if (ExprTy == S.Context.IntTy)
4284 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4285 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004286 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004287
Jordan Rosebc53ed12014-05-31 04:12:14 +00004288 // Look through enums to their underlying type.
4289 bool IsEnum = false;
4290 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4291 ExprTy = EnumTy->getDecl()->getIntegerType();
4292 IsEnum = true;
4293 }
4294
Jordan Rose0e5badd2012-12-05 18:44:49 +00004295 // %C in an Objective-C context prints a unichar, not a wchar_t.
4296 // If the argument is an integer of some kind, believe the %C and suggest
4297 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004298 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004299 if (ObjCContext &&
4300 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4301 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4302 !ExprTy->isCharType()) {
4303 // 'unichar' is defined as a typedef of unsigned short, but we should
4304 // prefer using the typedef if it is visible.
4305 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004306
4307 // While we are here, check if the value is an IntegerLiteral that happens
4308 // to be within the valid range.
4309 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4310 const llvm::APInt &V = IL->getValue();
4311 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4312 return true;
4313 }
4314
Jordan Rose0e5badd2012-12-05 18:44:49 +00004315 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4316 Sema::LookupOrdinaryName);
4317 if (S.LookupName(Result, S.getCurScope())) {
4318 NamedDecl *ND = Result.getFoundDecl();
4319 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4320 if (TD->getUnderlyingType() == IntendedTy)
4321 IntendedTy = S.Context.getTypedefType(TD);
4322 }
4323 }
4324 }
4325
4326 // Special-case some of Darwin's platform-independence types by suggesting
4327 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004328 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004329 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004330 QualType CastTy;
4331 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4332 if (!CastTy.isNull()) {
4333 IntendedTy = CastTy;
4334 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004335 }
4336 }
4337
Jordan Rose22b74712012-09-05 22:56:19 +00004338 // We may be able to offer a FixItHint if it is a supported type.
4339 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004340 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004341 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004342
Jordan Rose22b74712012-09-05 22:56:19 +00004343 if (success) {
4344 // Get the fix string from the fixed format specifier
4345 SmallString<16> buf;
4346 llvm::raw_svector_ostream os(buf);
4347 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004348
Jordan Roseaee34382012-09-05 22:56:26 +00004349 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4350
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004351 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004352 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4353 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4354 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4355 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004356 // In this case, the specifier is wrong and should be changed to match
4357 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004358 EmitFormatDiagnostic(S.PDiag(diag)
4359 << AT.getRepresentativeTypeName(S.Context)
4360 << IntendedTy << IsEnum << E->getSourceRange(),
4361 E->getLocStart(),
4362 /*IsStringLocation*/ false, SpecRange,
4363 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004364
4365 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004366 // The canonical type for formatting this value is different from the
4367 // actual type of the expression. (This occurs, for example, with Darwin's
4368 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4369 // should be printed as 'long' for 64-bit compatibility.)
4370 // Rather than emitting a normal format/argument mismatch, we want to
4371 // add a cast to the recommended type (and correct the format string
4372 // if necessary).
4373 SmallString<16> CastBuf;
4374 llvm::raw_svector_ostream CastFix(CastBuf);
4375 CastFix << "(";
4376 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4377 CastFix << ")";
4378
4379 SmallVector<FixItHint,4> Hints;
4380 if (!AT.matchesType(S.Context, IntendedTy))
4381 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4382
4383 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4384 // If there's already a cast present, just replace it.
4385 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4386 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4387
4388 } else if (!requiresParensToAddCast(E)) {
4389 // If the expression has high enough precedence,
4390 // just write the C-style cast.
4391 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4392 CastFix.str()));
4393 } else {
4394 // Otherwise, add parens around the expression as well as the cast.
4395 CastFix << "(";
4396 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4397 CastFix.str()));
4398
Alp Tokerb6cc5922014-05-03 03:45:55 +00004399 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004400 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4401 }
4402
Jordan Rose0e5badd2012-12-05 18:44:49 +00004403 if (ShouldNotPrintDirectly) {
4404 // The expression has a type that should not be printed directly.
4405 // We extract the name from the typedef because we don't want to show
4406 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004407 StringRef Name;
4408 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4409 Name = TypedefTy->getDecl()->getName();
4410 else
4411 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004412 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004413 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004414 << E->getSourceRange(),
4415 E->getLocStart(), /*IsStringLocation=*/false,
4416 SpecRange, Hints);
4417 } else {
4418 // In this case, the expression could be printed using a different
4419 // specifier, but we've decided that the specifier is probably correct
4420 // and we should cast instead. Just use the normal warning message.
4421 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004422 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4423 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004424 << E->getSourceRange(),
4425 E->getLocStart(), /*IsStringLocation*/false,
4426 SpecRange, Hints);
4427 }
Jordan Roseaee34382012-09-05 22:56:26 +00004428 }
Jordan Rose22b74712012-09-05 22:56:19 +00004429 } else {
4430 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4431 SpecifierLen);
4432 // Since the warning for passing non-POD types to variadic functions
4433 // was deferred until now, we emit a warning for non-POD
4434 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004435 switch (S.isValidVarArgType(ExprTy)) {
4436 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004437 case Sema::VAK_ValidInCXX11: {
4438 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4439 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4440 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4441 }
Richard Smithd7293d72013-08-05 18:49:43 +00004442
Seth Cantrellb4802962015-03-04 03:12:10 +00004443 EmitFormatDiagnostic(
4444 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4445 << IsEnum << CSR << E->getSourceRange(),
4446 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4447 break;
4448 }
Richard Smithd7293d72013-08-05 18:49:43 +00004449 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004450 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004451 EmitFormatDiagnostic(
4452 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004453 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004454 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004455 << CallType
4456 << AT.getRepresentativeTypeName(S.Context)
4457 << CSR
4458 << E->getSourceRange(),
4459 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004460 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004461 break;
4462
4463 case Sema::VAK_Invalid:
4464 if (ExprTy->isObjCObjectType())
4465 EmitFormatDiagnostic(
4466 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4467 << S.getLangOpts().CPlusPlus11
4468 << ExprTy
4469 << CallType
4470 << AT.getRepresentativeTypeName(S.Context)
4471 << CSR
4472 << E->getSourceRange(),
4473 E->getLocStart(), /*IsStringLocation*/false, CSR);
4474 else
4475 // FIXME: If this is an initializer list, suggest removing the braces
4476 // or inserting a cast to the target type.
4477 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4478 << isa<InitListExpr>(E) << ExprTy << CallType
4479 << AT.getRepresentativeTypeName(S.Context)
4480 << E->getSourceRange();
4481 break;
4482 }
4483
4484 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4485 "format string specifier index out of range");
4486 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004487 }
4488
Ted Kremenekab278de2010-01-28 23:39:18 +00004489 return true;
4490}
4491
Ted Kremenek02087932010-07-16 02:11:22 +00004492//===--- CHECK: Scanf format string checking ------------------------------===//
4493
4494namespace {
4495class CheckScanfHandler : public CheckFormatHandler {
4496public:
4497 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4498 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004499 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004500 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004501 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004502 Sema::VariadicCallType CallType,
4503 llvm::SmallBitVector &CheckedVarArgs)
4504 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4505 numDataArgs, beg, hasVAListArg,
4506 Args, formatIdx, inFunctionCall, CallType,
4507 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004508 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004509
4510 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4511 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004512 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004513
4514 bool HandleInvalidScanfConversionSpecifier(
4515 const analyze_scanf::ScanfSpecifier &FS,
4516 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004517 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004518
Craig Toppere14c0f82014-03-12 04:55:44 +00004519 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004520};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004521}
Ted Kremenekab278de2010-01-28 23:39:18 +00004522
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004523void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4524 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004525 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4526 getLocationOfByte(end), /*IsStringLocation*/true,
4527 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004528}
4529
Ted Kremenekce815422010-07-19 21:25:57 +00004530bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4531 const analyze_scanf::ScanfSpecifier &FS,
4532 const char *startSpecifier,
4533 unsigned specifierLen) {
4534
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004535 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004536 FS.getConversionSpecifier();
4537
4538 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4539 getLocationOfByte(CS.getStart()),
4540 startSpecifier, specifierLen,
4541 CS.getStart(), CS.getLength());
4542}
4543
Ted Kremenek02087932010-07-16 02:11:22 +00004544bool CheckScanfHandler::HandleScanfSpecifier(
4545 const analyze_scanf::ScanfSpecifier &FS,
4546 const char *startSpecifier,
4547 unsigned specifierLen) {
4548
4549 using namespace analyze_scanf;
4550 using namespace analyze_format_string;
4551
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004552 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004553
Ted Kremenek6cd69422010-07-19 22:01:06 +00004554 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4555 // be used to decide if we are using positional arguments consistently.
4556 if (FS.consumesDataArgument()) {
4557 if (atFirstArg) {
4558 atFirstArg = false;
4559 usesPositionalArgs = FS.usesPositionalArg();
4560 }
4561 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004562 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4563 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004564 return false;
4565 }
Ted Kremenek02087932010-07-16 02:11:22 +00004566 }
4567
4568 // Check if the field with is non-zero.
4569 const OptionalAmount &Amt = FS.getFieldWidth();
4570 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4571 if (Amt.getConstantAmount() == 0) {
4572 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4573 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004574 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4575 getLocationOfByte(Amt.getStart()),
4576 /*IsStringLocation*/true, R,
4577 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004578 }
4579 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004580
Ted Kremenek02087932010-07-16 02:11:22 +00004581 if (!FS.consumesDataArgument()) {
4582 // FIXME: Technically specifying a precision or field width here
4583 // makes no sense. Worth issuing a warning at some point.
4584 return true;
4585 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004586
Ted Kremenek02087932010-07-16 02:11:22 +00004587 // Consume the argument.
4588 unsigned argIndex = FS.getArgIndex();
4589 if (argIndex < NumDataArgs) {
4590 // The check to see if the argIndex is valid will come later.
4591 // We set the bit here because we may exit early from this
4592 // function if we encounter some other error.
4593 CoveredArgs.set(argIndex);
4594 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004595
Ted Kremenek4407ea42010-07-20 20:04:47 +00004596 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004597 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004598 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4599 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004600 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004601 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004602 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004603 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4604 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004605
Jordan Rose92303592012-09-08 04:00:03 +00004606 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4607 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4608
Ted Kremenek02087932010-07-16 02:11:22 +00004609 // The remaining checks depend on the data arguments.
4610 if (HasVAListArg)
4611 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004612
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004613 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004614 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004615
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004616 // Check that the argument type matches the format specifier.
4617 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004618 if (!Ex)
4619 return true;
4620
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004621 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004622
4623 if (!AT.isValid()) {
4624 return true;
4625 }
4626
Seth Cantrellb4802962015-03-04 03:12:10 +00004627 analyze_format_string::ArgType::MatchKind match =
4628 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004629 if (match == analyze_format_string::ArgType::Match) {
4630 return true;
4631 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004632
Seth Cantrell79340072015-03-04 05:58:08 +00004633 ScanfSpecifier fixedFS = FS;
4634 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4635 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004636
Seth Cantrell79340072015-03-04 05:58:08 +00004637 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4638 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4639 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4640 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004641
Seth Cantrell79340072015-03-04 05:58:08 +00004642 if (success) {
4643 // Get the fix string from the fixed format specifier.
4644 SmallString<128> buf;
4645 llvm::raw_svector_ostream os(buf);
4646 fixedFS.toString(os);
4647
4648 EmitFormatDiagnostic(
4649 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4650 << Ex->getType() << false << Ex->getSourceRange(),
4651 Ex->getLocStart(),
4652 /*IsStringLocation*/ false,
4653 getSpecifierRange(startSpecifier, specifierLen),
4654 FixItHint::CreateReplacement(
4655 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4656 } else {
4657 EmitFormatDiagnostic(S.PDiag(diag)
4658 << AT.getRepresentativeTypeName(S.Context)
4659 << Ex->getType() << false << Ex->getSourceRange(),
4660 Ex->getLocStart(),
4661 /*IsStringLocation*/ false,
4662 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004663 }
4664
Ted Kremenek02087932010-07-16 02:11:22 +00004665 return true;
4666}
4667
4668void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004669 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004670 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004671 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004672 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004673 bool inFunctionCall, VariadicCallType CallType,
4674 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004675
Ted Kremenekab278de2010-01-28 23:39:18 +00004676 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004677 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004678 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004679 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004680 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4681 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004682 return;
4683 }
Ted Kremenek02087932010-07-16 02:11:22 +00004684
Ted Kremenekab278de2010-01-28 23:39:18 +00004685 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004686 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004687 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004688 // Account for cases where the string literal is truncated in a declaration.
4689 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4690 assert(T && "String literal not of constant array type!");
4691 size_t TypeSize = T->getSize().getZExtValue();
4692 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004693 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004694
4695 // Emit a warning if the string literal is truncated and does not contain an
4696 // embedded null character.
4697 if (TypeSize <= StrRef.size() &&
4698 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4699 CheckFormatHandler::EmitFormatDiagnostic(
4700 *this, inFunctionCall, Args[format_idx],
4701 PDiag(diag::warn_printf_format_string_not_null_terminated),
4702 FExpr->getLocStart(),
4703 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4704 return;
4705 }
4706
Ted Kremenekab278de2010-01-28 23:39:18 +00004707 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004708 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004709 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004710 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004711 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4712 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004713 return;
4714 }
Ted Kremenek02087932010-07-16 02:11:22 +00004715
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004716 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004717 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004718 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004719 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004720 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004721 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004722
Hans Wennborg23926bd2011-12-15 10:25:47 +00004723 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004724 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004725 Context.getTargetInfo(),
4726 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004727 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004728 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004729 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004730 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004731 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004732
Hans Wennborg23926bd2011-12-15 10:25:47 +00004733 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004734 getLangOpts(),
4735 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004736 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004737 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004738}
4739
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004740bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4741 // Str - The format string. NOTE: this is NOT null-terminated!
4742 StringRef StrRef = FExpr->getString();
4743 const char *Str = StrRef.data();
4744 // Account for cases where the string literal is truncated in a declaration.
4745 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4746 assert(T && "String literal not of constant array type!");
4747 size_t TypeSize = T->getSize().getZExtValue();
4748 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4749 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4750 getLangOpts(),
4751 Context.getTargetInfo());
4752}
4753
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004754//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4755
4756// Returns the related absolute value function that is larger, of 0 if one
4757// does not exist.
4758static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4759 switch (AbsFunction) {
4760 default:
4761 return 0;
4762
4763 case Builtin::BI__builtin_abs:
4764 return Builtin::BI__builtin_labs;
4765 case Builtin::BI__builtin_labs:
4766 return Builtin::BI__builtin_llabs;
4767 case Builtin::BI__builtin_llabs:
4768 return 0;
4769
4770 case Builtin::BI__builtin_fabsf:
4771 return Builtin::BI__builtin_fabs;
4772 case Builtin::BI__builtin_fabs:
4773 return Builtin::BI__builtin_fabsl;
4774 case Builtin::BI__builtin_fabsl:
4775 return 0;
4776
4777 case Builtin::BI__builtin_cabsf:
4778 return Builtin::BI__builtin_cabs;
4779 case Builtin::BI__builtin_cabs:
4780 return Builtin::BI__builtin_cabsl;
4781 case Builtin::BI__builtin_cabsl:
4782 return 0;
4783
4784 case Builtin::BIabs:
4785 return Builtin::BIlabs;
4786 case Builtin::BIlabs:
4787 return Builtin::BIllabs;
4788 case Builtin::BIllabs:
4789 return 0;
4790
4791 case Builtin::BIfabsf:
4792 return Builtin::BIfabs;
4793 case Builtin::BIfabs:
4794 return Builtin::BIfabsl;
4795 case Builtin::BIfabsl:
4796 return 0;
4797
4798 case Builtin::BIcabsf:
4799 return Builtin::BIcabs;
4800 case Builtin::BIcabs:
4801 return Builtin::BIcabsl;
4802 case Builtin::BIcabsl:
4803 return 0;
4804 }
4805}
4806
4807// Returns the argument type of the absolute value function.
4808static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4809 unsigned AbsType) {
4810 if (AbsType == 0)
4811 return QualType();
4812
4813 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4814 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4815 if (Error != ASTContext::GE_None)
4816 return QualType();
4817
4818 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4819 if (!FT)
4820 return QualType();
4821
4822 if (FT->getNumParams() != 1)
4823 return QualType();
4824
4825 return FT->getParamType(0);
4826}
4827
4828// Returns the best absolute value function, or zero, based on type and
4829// current absolute value function.
4830static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4831 unsigned AbsFunctionKind) {
4832 unsigned BestKind = 0;
4833 uint64_t ArgSize = Context.getTypeSize(ArgType);
4834 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4835 Kind = getLargerAbsoluteValueFunction(Kind)) {
4836 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4837 if (Context.getTypeSize(ParamType) >= ArgSize) {
4838 if (BestKind == 0)
4839 BestKind = Kind;
4840 else if (Context.hasSameType(ParamType, ArgType)) {
4841 BestKind = Kind;
4842 break;
4843 }
4844 }
4845 }
4846 return BestKind;
4847}
4848
4849enum AbsoluteValueKind {
4850 AVK_Integer,
4851 AVK_Floating,
4852 AVK_Complex
4853};
4854
4855static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4856 if (T->isIntegralOrEnumerationType())
4857 return AVK_Integer;
4858 if (T->isRealFloatingType())
4859 return AVK_Floating;
4860 if (T->isAnyComplexType())
4861 return AVK_Complex;
4862
4863 llvm_unreachable("Type not integer, floating, or complex");
4864}
4865
4866// Changes the absolute value function to a different type. Preserves whether
4867// the function is a builtin.
4868static unsigned changeAbsFunction(unsigned AbsKind,
4869 AbsoluteValueKind ValueKind) {
4870 switch (ValueKind) {
4871 case AVK_Integer:
4872 switch (AbsKind) {
4873 default:
4874 return 0;
4875 case Builtin::BI__builtin_fabsf:
4876 case Builtin::BI__builtin_fabs:
4877 case Builtin::BI__builtin_fabsl:
4878 case Builtin::BI__builtin_cabsf:
4879 case Builtin::BI__builtin_cabs:
4880 case Builtin::BI__builtin_cabsl:
4881 return Builtin::BI__builtin_abs;
4882 case Builtin::BIfabsf:
4883 case Builtin::BIfabs:
4884 case Builtin::BIfabsl:
4885 case Builtin::BIcabsf:
4886 case Builtin::BIcabs:
4887 case Builtin::BIcabsl:
4888 return Builtin::BIabs;
4889 }
4890 case AVK_Floating:
4891 switch (AbsKind) {
4892 default:
4893 return 0;
4894 case Builtin::BI__builtin_abs:
4895 case Builtin::BI__builtin_labs:
4896 case Builtin::BI__builtin_llabs:
4897 case Builtin::BI__builtin_cabsf:
4898 case Builtin::BI__builtin_cabs:
4899 case Builtin::BI__builtin_cabsl:
4900 return Builtin::BI__builtin_fabsf;
4901 case Builtin::BIabs:
4902 case Builtin::BIlabs:
4903 case Builtin::BIllabs:
4904 case Builtin::BIcabsf:
4905 case Builtin::BIcabs:
4906 case Builtin::BIcabsl:
4907 return Builtin::BIfabsf;
4908 }
4909 case AVK_Complex:
4910 switch (AbsKind) {
4911 default:
4912 return 0;
4913 case Builtin::BI__builtin_abs:
4914 case Builtin::BI__builtin_labs:
4915 case Builtin::BI__builtin_llabs:
4916 case Builtin::BI__builtin_fabsf:
4917 case Builtin::BI__builtin_fabs:
4918 case Builtin::BI__builtin_fabsl:
4919 return Builtin::BI__builtin_cabsf;
4920 case Builtin::BIabs:
4921 case Builtin::BIlabs:
4922 case Builtin::BIllabs:
4923 case Builtin::BIfabsf:
4924 case Builtin::BIfabs:
4925 case Builtin::BIfabsl:
4926 return Builtin::BIcabsf;
4927 }
4928 }
4929 llvm_unreachable("Unable to convert function");
4930}
4931
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004932static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004933 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4934 if (!FnInfo)
4935 return 0;
4936
4937 switch (FDecl->getBuiltinID()) {
4938 default:
4939 return 0;
4940 case Builtin::BI__builtin_abs:
4941 case Builtin::BI__builtin_fabs:
4942 case Builtin::BI__builtin_fabsf:
4943 case Builtin::BI__builtin_fabsl:
4944 case Builtin::BI__builtin_labs:
4945 case Builtin::BI__builtin_llabs:
4946 case Builtin::BI__builtin_cabs:
4947 case Builtin::BI__builtin_cabsf:
4948 case Builtin::BI__builtin_cabsl:
4949 case Builtin::BIabs:
4950 case Builtin::BIlabs:
4951 case Builtin::BIllabs:
4952 case Builtin::BIfabs:
4953 case Builtin::BIfabsf:
4954 case Builtin::BIfabsl:
4955 case Builtin::BIcabs:
4956 case Builtin::BIcabsf:
4957 case Builtin::BIcabsl:
4958 return FDecl->getBuiltinID();
4959 }
4960 llvm_unreachable("Unknown Builtin type");
4961}
4962
4963// If the replacement is valid, emit a note with replacement function.
4964// Additionally, suggest including the proper header if not already included.
4965static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004966 unsigned AbsKind, QualType ArgType) {
4967 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004968 const char *HeaderName = nullptr;
4969 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004970 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4971 FunctionName = "std::abs";
4972 if (ArgType->isIntegralOrEnumerationType()) {
4973 HeaderName = "cstdlib";
4974 } else if (ArgType->isRealFloatingType()) {
4975 HeaderName = "cmath";
4976 } else {
4977 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004978 }
Richard Trieubeffb832014-04-15 23:47:53 +00004979
4980 // Lookup all std::abs
4981 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004982 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004983 R.suppressDiagnostics();
4984 S.LookupQualifiedName(R, Std);
4985
4986 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004987 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004988 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4989 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4990 } else {
4991 FDecl = dyn_cast<FunctionDecl>(I);
4992 }
4993 if (!FDecl)
4994 continue;
4995
4996 // Found std::abs(), check that they are the right ones.
4997 if (FDecl->getNumParams() != 1)
4998 continue;
4999
5000 // Check that the parameter type can handle the argument.
5001 QualType ParamType = FDecl->getParamDecl(0)->getType();
5002 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5003 S.Context.getTypeSize(ArgType) <=
5004 S.Context.getTypeSize(ParamType)) {
5005 // Found a function, don't need the header hint.
5006 EmitHeaderHint = false;
5007 break;
5008 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005009 }
Richard Trieubeffb832014-04-15 23:47:53 +00005010 }
5011 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005012 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005013 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5014
5015 if (HeaderName) {
5016 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5017 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5018 R.suppressDiagnostics();
5019 S.LookupName(R, S.getCurScope());
5020
5021 if (R.isSingleResult()) {
5022 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5023 if (FD && FD->getBuiltinID() == AbsKind) {
5024 EmitHeaderHint = false;
5025 } else {
5026 return;
5027 }
5028 } else if (!R.empty()) {
5029 return;
5030 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005031 }
5032 }
5033
5034 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005035 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005036
Richard Trieubeffb832014-04-15 23:47:53 +00005037 if (!HeaderName)
5038 return;
5039
5040 if (!EmitHeaderHint)
5041 return;
5042
Alp Toker5d96e0a2014-07-11 20:53:51 +00005043 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5044 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005045}
5046
5047static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5048 if (!FDecl)
5049 return false;
5050
5051 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5052 return false;
5053
5054 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5055
5056 while (ND && ND->isInlineNamespace()) {
5057 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005058 }
Richard Trieubeffb832014-04-15 23:47:53 +00005059
5060 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5061 return false;
5062
5063 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5064 return false;
5065
5066 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005067}
5068
5069// Warn when using the wrong abs() function.
5070void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5071 const FunctionDecl *FDecl,
5072 IdentifierInfo *FnInfo) {
5073 if (Call->getNumArgs() != 1)
5074 return;
5075
5076 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005077 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5078 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005079 return;
5080
5081 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5082 QualType ParamType = Call->getArg(0)->getType();
5083
Alp Toker5d96e0a2014-07-11 20:53:51 +00005084 // Unsigned types cannot be negative. Suggest removing the absolute value
5085 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005086 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005087 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005088 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005089 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5090 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005091 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005092 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5093 return;
5094 }
5095
David Majnemer7f77eb92015-11-15 03:04:34 +00005096 // Taking the absolute value of a pointer is very suspicious, they probably
5097 // wanted to index into an array, dereference a pointer, call a function, etc.
5098 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5099 unsigned DiagType = 0;
5100 if (ArgType->isFunctionType())
5101 DiagType = 1;
5102 else if (ArgType->isArrayType())
5103 DiagType = 2;
5104
5105 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5106 return;
5107 }
5108
Richard Trieubeffb832014-04-15 23:47:53 +00005109 // std::abs has overloads which prevent most of the absolute value problems
5110 // from occurring.
5111 if (IsStdAbs)
5112 return;
5113
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005114 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5115 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5116
5117 // The argument and parameter are the same kind. Check if they are the right
5118 // size.
5119 if (ArgValueKind == ParamValueKind) {
5120 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5121 return;
5122
5123 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5124 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5125 << FDecl << ArgType << ParamType;
5126
5127 if (NewAbsKind == 0)
5128 return;
5129
5130 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005131 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005132 return;
5133 }
5134
5135 // ArgValueKind != ParamValueKind
5136 // The wrong type of absolute value function was used. Attempt to find the
5137 // proper one.
5138 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5139 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5140 if (NewAbsKind == 0)
5141 return;
5142
5143 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5144 << FDecl << ParamValueKind << ArgValueKind;
5145
5146 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005147 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005148 return;
5149}
5150
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005151//===--- CHECK: Standard memory functions ---------------------------------===//
5152
Nico Weber0e6daef2013-12-26 23:38:39 +00005153/// \brief Takes the expression passed to the size_t parameter of functions
5154/// such as memcmp, strncat, etc and warns if it's a comparison.
5155///
5156/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5157static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5158 IdentifierInfo *FnName,
5159 SourceLocation FnLoc,
5160 SourceLocation RParenLoc) {
5161 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5162 if (!Size)
5163 return false;
5164
5165 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5166 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5167 return false;
5168
Nico Weber0e6daef2013-12-26 23:38:39 +00005169 SourceRange SizeRange = Size->getSourceRange();
5170 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5171 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005172 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005173 << FnName << FixItHint::CreateInsertion(
5174 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005175 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005176 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005177 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005178 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5179 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005180
5181 return true;
5182}
5183
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005184/// \brief Determine whether the given type is or contains a dynamic class type
5185/// (e.g., whether it has a vtable).
5186static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5187 bool &IsContained) {
5188 // Look through array types while ignoring qualifiers.
5189 const Type *Ty = T->getBaseElementTypeUnsafe();
5190 IsContained = false;
5191
5192 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5193 RD = RD ? RD->getDefinition() : nullptr;
5194 if (!RD)
5195 return nullptr;
5196
5197 if (RD->isDynamicClass())
5198 return RD;
5199
5200 // Check all the fields. If any bases were dynamic, the class is dynamic.
5201 // It's impossible for a class to transitively contain itself by value, so
5202 // infinite recursion is impossible.
5203 for (auto *FD : RD->fields()) {
5204 bool SubContained;
5205 if (const CXXRecordDecl *ContainedRD =
5206 getContainedDynamicClass(FD->getType(), SubContained)) {
5207 IsContained = true;
5208 return ContainedRD;
5209 }
5210 }
5211
5212 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005213}
5214
Chandler Carruth889ed862011-06-21 23:04:20 +00005215/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005216/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005217static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005218 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005219 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5220 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5221 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005222
Craig Topperc3ec1492014-05-26 06:22:03 +00005223 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005224}
5225
Chandler Carruth889ed862011-06-21 23:04:20 +00005226/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005227static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005228 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5229 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5230 if (SizeOf->getKind() == clang::UETT_SizeOf)
5231 return SizeOf->getTypeOfArgument();
5232
5233 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005234}
5235
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005236/// \brief Check for dangerous or invalid arguments to memset().
5237///
Chandler Carruthac687262011-06-03 06:23:57 +00005238/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005239/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5240/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005241///
5242/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005243void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005244 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005245 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005246 assert(BId != 0);
5247
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005248 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005249 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005250 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005251 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005252 return;
5253
Anna Zaks22122702012-01-17 00:37:07 +00005254 unsigned LastArg = (BId == Builtin::BImemset ||
5255 BId == Builtin::BIstrndup ? 1 : 2);
5256 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005257 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005258
Nico Weber0e6daef2013-12-26 23:38:39 +00005259 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5260 Call->getLocStart(), Call->getRParenLoc()))
5261 return;
5262
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005263 // We have special checking when the length is a sizeof expression.
5264 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5265 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5266 llvm::FoldingSetNodeID SizeOfArgID;
5267
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005268 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5269 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005270 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005271
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005272 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005273 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005274 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005275 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005276
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005277 // Never warn about void type pointers. This can be used to suppress
5278 // false positives.
5279 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005280 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005281
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005282 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5283 // actually comparing the expressions for equality. Because computing the
5284 // expression IDs can be expensive, we only do this if the diagnostic is
5285 // enabled.
5286 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005287 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5288 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005289 // We only compute IDs for expressions if the warning is enabled, and
5290 // cache the sizeof arg's ID.
5291 if (SizeOfArgID == llvm::FoldingSetNodeID())
5292 SizeOfArg->Profile(SizeOfArgID, Context, true);
5293 llvm::FoldingSetNodeID DestID;
5294 Dest->Profile(DestID, Context, true);
5295 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005296 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5297 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005298 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005299 StringRef ReadableName = FnName->getName();
5300
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005301 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005302 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005303 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005304 if (!PointeeTy->isIncompleteType() &&
5305 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005306 ActionIdx = 2; // If the pointee's size is sizeof(char),
5307 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005308
5309 // If the function is defined as a builtin macro, do not show macro
5310 // expansion.
5311 SourceLocation SL = SizeOfArg->getExprLoc();
5312 SourceRange DSR = Dest->getSourceRange();
5313 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005314 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005315
5316 if (SM.isMacroArgExpansion(SL)) {
5317 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5318 SL = SM.getSpellingLoc(SL);
5319 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5320 SM.getSpellingLoc(DSR.getEnd()));
5321 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5322 SM.getSpellingLoc(SSR.getEnd()));
5323 }
5324
Anna Zaksd08d9152012-05-30 23:14:52 +00005325 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005326 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005327 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005328 << PointeeTy
5329 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005330 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005331 << SSR);
5332 DiagRuntimeBehavior(SL, SizeOfArg,
5333 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5334 << ActionIdx
5335 << SSR);
5336
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005337 break;
5338 }
5339 }
5340
5341 // Also check for cases where the sizeof argument is the exact same
5342 // type as the memory argument, and where it points to a user-defined
5343 // record type.
5344 if (SizeOfArgTy != QualType()) {
5345 if (PointeeTy->isRecordType() &&
5346 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5347 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5348 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5349 << FnName << SizeOfArgTy << ArgIdx
5350 << PointeeTy << Dest->getSourceRange()
5351 << LenExpr->getSourceRange());
5352 break;
5353 }
Nico Weberc5e73862011-06-14 16:14:58 +00005354 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005355 } else if (DestTy->isArrayType()) {
5356 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005357 }
Nico Weberc5e73862011-06-14 16:14:58 +00005358
Nico Weberc44b35e2015-03-21 17:37:46 +00005359 if (PointeeTy == QualType())
5360 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005361
Nico Weberc44b35e2015-03-21 17:37:46 +00005362 // Always complain about dynamic classes.
5363 bool IsContained;
5364 if (const CXXRecordDecl *ContainedRD =
5365 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005366
Nico Weberc44b35e2015-03-21 17:37:46 +00005367 unsigned OperationType = 0;
5368 // "overwritten" if we're warning about the destination for any call
5369 // but memcmp; otherwise a verb appropriate to the call.
5370 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5371 if (BId == Builtin::BImemcpy)
5372 OperationType = 1;
5373 else if(BId == Builtin::BImemmove)
5374 OperationType = 2;
5375 else if (BId == Builtin::BImemcmp)
5376 OperationType = 3;
5377 }
5378
John McCall31168b02011-06-15 23:02:42 +00005379 DiagRuntimeBehavior(
5380 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005381 PDiag(diag::warn_dyn_class_memaccess)
5382 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5383 << FnName << IsContained << ContainedRD << OperationType
5384 << Call->getCallee()->getSourceRange());
5385 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5386 BId != Builtin::BImemset)
5387 DiagRuntimeBehavior(
5388 Dest->getExprLoc(), Dest,
5389 PDiag(diag::warn_arc_object_memaccess)
5390 << ArgIdx << FnName << PointeeTy
5391 << Call->getCallee()->getSourceRange());
5392 else
5393 continue;
5394
5395 DiagRuntimeBehavior(
5396 Dest->getExprLoc(), Dest,
5397 PDiag(diag::note_bad_memaccess_silence)
5398 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5399 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005400 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005401
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005402}
5403
Ted Kremenek6865f772011-08-18 20:55:45 +00005404// A little helper routine: ignore addition and subtraction of integer literals.
5405// This intentionally does not ignore all integer constant expressions because
5406// we don't want to remove sizeof().
5407static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5408 Ex = Ex->IgnoreParenCasts();
5409
5410 for (;;) {
5411 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5412 if (!BO || !BO->isAdditiveOp())
5413 break;
5414
5415 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5416 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5417
5418 if (isa<IntegerLiteral>(RHS))
5419 Ex = LHS;
5420 else if (isa<IntegerLiteral>(LHS))
5421 Ex = RHS;
5422 else
5423 break;
5424 }
5425
5426 return Ex;
5427}
5428
Anna Zaks13b08572012-08-08 21:42:23 +00005429static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5430 ASTContext &Context) {
5431 // Only handle constant-sized or VLAs, but not flexible members.
5432 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5433 // Only issue the FIXIT for arrays of size > 1.
5434 if (CAT->getSize().getSExtValue() <= 1)
5435 return false;
5436 } else if (!Ty->isVariableArrayType()) {
5437 return false;
5438 }
5439 return true;
5440}
5441
Ted Kremenek6865f772011-08-18 20:55:45 +00005442// Warn if the user has made the 'size' argument to strlcpy or strlcat
5443// be the size of the source, instead of the destination.
5444void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5445 IdentifierInfo *FnName) {
5446
5447 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005448 unsigned NumArgs = Call->getNumArgs();
5449 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005450 return;
5451
5452 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5453 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005454 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005455
5456 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5457 Call->getLocStart(), Call->getRParenLoc()))
5458 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005459
5460 // Look for 'strlcpy(dst, x, sizeof(x))'
5461 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5462 CompareWithSrc = Ex;
5463 else {
5464 // Look for 'strlcpy(dst, x, strlen(x))'
5465 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005466 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5467 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005468 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5469 }
5470 }
5471
5472 if (!CompareWithSrc)
5473 return;
5474
5475 // Determine if the argument to sizeof/strlen is equal to the source
5476 // argument. In principle there's all kinds of things you could do
5477 // here, for instance creating an == expression and evaluating it with
5478 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5479 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5480 if (!SrcArgDRE)
5481 return;
5482
5483 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5484 if (!CompareWithSrcDRE ||
5485 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5486 return;
5487
5488 const Expr *OriginalSizeArg = Call->getArg(2);
5489 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5490 << OriginalSizeArg->getSourceRange() << FnName;
5491
5492 // Output a FIXIT hint if the destination is an array (rather than a
5493 // pointer to an array). This could be enhanced to handle some
5494 // pointers if we know the actual size, like if DstArg is 'array+2'
5495 // we could say 'sizeof(array)-2'.
5496 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005497 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005498 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005499
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005500 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005501 llvm::raw_svector_ostream OS(sizeString);
5502 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005503 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005504 OS << ")";
5505
5506 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5507 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5508 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005509}
5510
Anna Zaks314cd092012-02-01 19:08:57 +00005511/// Check if two expressions refer to the same declaration.
5512static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5513 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5514 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5515 return D1->getDecl() == D2->getDecl();
5516 return false;
5517}
5518
5519static const Expr *getStrlenExprArg(const Expr *E) {
5520 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5521 const FunctionDecl *FD = CE->getDirectCallee();
5522 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005523 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005524 return CE->getArg(0)->IgnoreParenCasts();
5525 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005526 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005527}
5528
5529// Warn on anti-patterns as the 'size' argument to strncat.
5530// The correct size argument should look like following:
5531// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5532void Sema::CheckStrncatArguments(const CallExpr *CE,
5533 IdentifierInfo *FnName) {
5534 // Don't crash if the user has the wrong number of arguments.
5535 if (CE->getNumArgs() < 3)
5536 return;
5537 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5538 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5539 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5540
Nico Weber0e6daef2013-12-26 23:38:39 +00005541 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5542 CE->getRParenLoc()))
5543 return;
5544
Anna Zaks314cd092012-02-01 19:08:57 +00005545 // Identify common expressions, which are wrongly used as the size argument
5546 // to strncat and may lead to buffer overflows.
5547 unsigned PatternType = 0;
5548 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5549 // - sizeof(dst)
5550 if (referToTheSameDecl(SizeOfArg, DstArg))
5551 PatternType = 1;
5552 // - sizeof(src)
5553 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5554 PatternType = 2;
5555 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5556 if (BE->getOpcode() == BO_Sub) {
5557 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5558 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5559 // - sizeof(dst) - strlen(dst)
5560 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5561 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5562 PatternType = 1;
5563 // - sizeof(src) - (anything)
5564 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5565 PatternType = 2;
5566 }
5567 }
5568
5569 if (PatternType == 0)
5570 return;
5571
Anna Zaks5069aa32012-02-03 01:27:37 +00005572 // Generate the diagnostic.
5573 SourceLocation SL = LenArg->getLocStart();
5574 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005575 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005576
5577 // If the function is defined as a builtin macro, do not show macro expansion.
5578 if (SM.isMacroArgExpansion(SL)) {
5579 SL = SM.getSpellingLoc(SL);
5580 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5581 SM.getSpellingLoc(SR.getEnd()));
5582 }
5583
Anna Zaks13b08572012-08-08 21:42:23 +00005584 // Check if the destination is an array (rather than a pointer to an array).
5585 QualType DstTy = DstArg->getType();
5586 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5587 Context);
5588 if (!isKnownSizeArray) {
5589 if (PatternType == 1)
5590 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5591 else
5592 Diag(SL, diag::warn_strncat_src_size) << SR;
5593 return;
5594 }
5595
Anna Zaks314cd092012-02-01 19:08:57 +00005596 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005597 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005598 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005599 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005600
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005601 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005602 llvm::raw_svector_ostream OS(sizeString);
5603 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005604 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005605 OS << ") - ";
5606 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005607 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005608 OS << ") - 1";
5609
Anna Zaks5069aa32012-02-03 01:27:37 +00005610 Diag(SL, diag::note_strncat_wrong_size)
5611 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005612}
5613
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005614//===--- CHECK: Return Address of Stack Variable --------------------------===//
5615
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005616static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5617 Decl *ParentDecl);
5618static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5619 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005620
5621/// CheckReturnStackAddr - Check if a return statement returns the address
5622/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005623static void
5624CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5625 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005626
Craig Topperc3ec1492014-05-26 06:22:03 +00005627 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005628 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005629
5630 // Perform checking for returned stack addresses, local blocks,
5631 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005632 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005633 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005634 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005635 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005636 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005637 }
5638
Craig Topperc3ec1492014-05-26 06:22:03 +00005639 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005640 return; // Nothing suspicious was found.
5641
5642 SourceLocation diagLoc;
5643 SourceRange diagRange;
5644 if (refVars.empty()) {
5645 diagLoc = stackE->getLocStart();
5646 diagRange = stackE->getSourceRange();
5647 } else {
5648 // We followed through a reference variable. 'stackE' contains the
5649 // problematic expression but we will warn at the return statement pointing
5650 // at the reference variable. We will later display the "trail" of
5651 // reference variables using notes.
5652 diagLoc = refVars[0]->getLocStart();
5653 diagRange = refVars[0]->getSourceRange();
5654 }
5655
5656 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Craig Topperda7b27f2015-11-17 05:40:09 +00005657 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005658 << DR->getDecl()->getDeclName() << diagRange;
5659 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005660 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005661 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005662 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005663 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005664 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5665 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005666 }
5667
5668 // Display the "trail" of reference variables that we followed until we
5669 // found the problematic expression using notes.
5670 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5671 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5672 // If this var binds to another reference var, show the range of the next
5673 // var, otherwise the var binds to the problematic expression, in which case
5674 // show the range of the expression.
5675 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5676 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005677 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5678 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005679 }
5680}
5681
5682/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5683/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005684/// to a location on the stack, a local block, an address of a label, or a
5685/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005686/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005687/// encounter a subexpression that (1) clearly does not lead to one of the
5688/// above problematic expressions (2) is something we cannot determine leads to
5689/// a problematic expression based on such local checking.
5690///
5691/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5692/// the expression that they point to. Such variables are added to the
5693/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005694///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005695/// EvalAddr processes expressions that are pointers that are used as
5696/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005697/// At the base case of the recursion is a check for the above problematic
5698/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005699///
5700/// This implementation handles:
5701///
5702/// * pointer-to-pointer casts
5703/// * implicit conversions from array references to pointers
5704/// * taking the address of fields
5705/// * arbitrary interplay between "&" and "*" operators
5706/// * pointer arithmetic from an address of a stack variable
5707/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005708static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5709 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005710 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005711 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005712
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005713 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005714 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005715 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005716 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005717 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005718
Peter Collingbourne91147592011-04-15 00:35:48 +00005719 E = E->IgnoreParens();
5720
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005721 // Our "symbolic interpreter" is just a dispatch off the currently
5722 // viewed AST node. We then recursively traverse the AST by calling
5723 // EvalAddr and EvalVal appropriately.
5724 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005725 case Stmt::DeclRefExprClass: {
5726 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5727
Richard Smith40f08eb2014-01-30 22:05:38 +00005728 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005729 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005730 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005731
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005732 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5733 // If this is a reference variable, follow through to the expression that
5734 // it points to.
5735 if (V->hasLocalStorage() &&
5736 V->getType()->isReferenceType() && V->hasInit()) {
5737 // Add the reference variable to the "trail".
5738 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005739 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005740 }
5741
Craig Topperc3ec1492014-05-26 06:22:03 +00005742 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005743 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005744
Chris Lattner934edb22007-12-28 05:31:15 +00005745 case Stmt::UnaryOperatorClass: {
5746 // The only unary operator that make sense to handle here
5747 // is AddrOf. All others don't make sense as pointers.
5748 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005749
John McCalle3027922010-08-25 11:45:40 +00005750 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005751 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005752 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005753 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005754 }
Mike Stump11289f42009-09-09 15:08:12 +00005755
Chris Lattner934edb22007-12-28 05:31:15 +00005756 case Stmt::BinaryOperatorClass: {
5757 // Handle pointer arithmetic. All other binary operators are not valid
5758 // in this context.
5759 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005760 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005761
John McCalle3027922010-08-25 11:45:40 +00005762 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005763 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005764
Chris Lattner934edb22007-12-28 05:31:15 +00005765 Expr *Base = B->getLHS();
5766
5767 // Determine which argument is the real pointer base. It could be
5768 // the RHS argument instead of the LHS.
5769 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005770
Chris Lattner934edb22007-12-28 05:31:15 +00005771 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005772 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005773 }
Steve Naroff2752a172008-09-10 19:17:48 +00005774
Chris Lattner934edb22007-12-28 05:31:15 +00005775 // For conditional operators we need to see if either the LHS or RHS are
5776 // valid DeclRefExpr*s. If one of them is valid, we return it.
5777 case Stmt::ConditionalOperatorClass: {
5778 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005779
Chris Lattner934edb22007-12-28 05:31:15 +00005780 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005781 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5782 if (Expr *LHSExpr = C->getLHS()) {
5783 // In C++, we can have a throw-expression, which has 'void' type.
5784 if (!LHSExpr->getType()->isVoidType())
5785 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005786 return LHS;
5787 }
Chris Lattner934edb22007-12-28 05:31:15 +00005788
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005789 // In C++, we can have a throw-expression, which has 'void' type.
5790 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005791 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005792
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005793 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005794 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005795
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005796 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005797 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005798 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005799 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005800
5801 case Stmt::AddrLabelExprClass:
5802 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005803
John McCall28fc7092011-11-10 05:35:25 +00005804 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005805 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5806 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005807
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005808 // For casts, we need to handle conversions from arrays to
5809 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005810 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005811 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005812 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005813 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005814 case Stmt::CXXStaticCastExprClass:
5815 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005816 case Stmt::CXXConstCastExprClass:
5817 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005818 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5819 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005820 case CK_LValueToRValue:
5821 case CK_NoOp:
5822 case CK_BaseToDerived:
5823 case CK_DerivedToBase:
5824 case CK_UncheckedDerivedToBase:
5825 case CK_Dynamic:
5826 case CK_CPointerToObjCPointerCast:
5827 case CK_BlockPointerToObjCPointerCast:
5828 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005829 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005830
5831 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005832 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005833
Richard Trieudadefde2014-07-02 04:39:38 +00005834 case CK_BitCast:
5835 if (SubExpr->getType()->isAnyPointerType() ||
5836 SubExpr->getType()->isBlockPointerType() ||
5837 SubExpr->getType()->isObjCQualifiedIdType())
5838 return EvalAddr(SubExpr, refVars, ParentDecl);
5839 else
5840 return nullptr;
5841
Eli Friedman8195ad72012-02-23 23:04:32 +00005842 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005843 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005844 }
Chris Lattner934edb22007-12-28 05:31:15 +00005845 }
Mike Stump11289f42009-09-09 15:08:12 +00005846
Douglas Gregorfe314812011-06-21 17:03:29 +00005847 case Stmt::MaterializeTemporaryExprClass:
5848 if (Expr *Result = EvalAddr(
5849 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005850 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005851 return Result;
5852
5853 return E;
5854
Chris Lattner934edb22007-12-28 05:31:15 +00005855 // Everything else: we simply don't reason about them.
5856 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005857 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005858 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005859}
Mike Stump11289f42009-09-09 15:08:12 +00005860
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005861
5862/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5863/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005864static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5865 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005866do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005867 // We should only be called for evaluating non-pointer expressions, or
5868 // expressions with a pointer type that are not used as references but instead
5869 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005870
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005871 // Our "symbolic interpreter" is just a dispatch off the currently
5872 // viewed AST node. We then recursively traverse the AST by calling
5873 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005874
5875 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005876 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005877 case Stmt::ImplicitCastExprClass: {
5878 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005879 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005880 E = IE->getSubExpr();
5881 continue;
5882 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005883 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005884 }
5885
John McCall28fc7092011-11-10 05:35:25 +00005886 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005887 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005888
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005889 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005890 // When we hit a DeclRefExpr we are looking at code that refers to a
5891 // variable's name. If it's not a reference variable we check if it has
5892 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005893 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005894
Richard Smith40f08eb2014-01-30 22:05:38 +00005895 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005896 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005897 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005898
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005899 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5900 // Check if it refers to itself, e.g. "int& i = i;".
5901 if (V == ParentDecl)
5902 return DR;
5903
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005904 if (V->hasLocalStorage()) {
5905 if (!V->getType()->isReferenceType())
5906 return DR;
5907
5908 // Reference variable, follow through to the expression that
5909 // it points to.
5910 if (V->hasInit()) {
5911 // Add the reference variable to the "trail".
5912 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005913 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005914 }
5915 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005916 }
Mike Stump11289f42009-09-09 15:08:12 +00005917
Craig Topperc3ec1492014-05-26 06:22:03 +00005918 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005919 }
Mike Stump11289f42009-09-09 15:08:12 +00005920
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005921 case Stmt::UnaryOperatorClass: {
5922 // The only unary operator that make sense to handle here
5923 // is Deref. All others don't resolve to a "name." This includes
5924 // handling all sorts of rvalues passed to a unary operator.
5925 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005926
John McCalle3027922010-08-25 11:45:40 +00005927 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005928 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005929
Craig Topperc3ec1492014-05-26 06:22:03 +00005930 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005931 }
Mike Stump11289f42009-09-09 15:08:12 +00005932
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005933 case Stmt::ArraySubscriptExprClass: {
5934 // Array subscripts are potential references to data on the stack. We
5935 // retrieve the DeclRefExpr* for the array variable if it indeed
5936 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005937 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005938 }
Mike Stump11289f42009-09-09 15:08:12 +00005939
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005940 case Stmt::OMPArraySectionExprClass: {
5941 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5942 ParentDecl);
5943 }
5944
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005945 case Stmt::ConditionalOperatorClass: {
5946 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005947 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005948 ConditionalOperator *C = cast<ConditionalOperator>(E);
5949
Anders Carlsson801c5c72007-11-30 19:04:31 +00005950 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005951 if (Expr *LHSExpr = C->getLHS()) {
5952 // In C++, we can have a throw-expression, which has 'void' type.
5953 if (!LHSExpr->getType()->isVoidType())
5954 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5955 return LHS;
5956 }
5957
5958 // In C++, we can have a throw-expression, which has 'void' type.
5959 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005960 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005961
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005962 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005963 }
Mike Stump11289f42009-09-09 15:08:12 +00005964
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005965 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005966 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005967 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005968
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005969 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005970 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005971 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005972
5973 // Check whether the member type is itself a reference, in which case
5974 // we're not going to refer to the member, but to what the member refers to.
5975 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005976 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005977
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005978 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005979 }
Mike Stump11289f42009-09-09 15:08:12 +00005980
Douglas Gregorfe314812011-06-21 17:03:29 +00005981 case Stmt::MaterializeTemporaryExprClass:
5982 if (Expr *Result = EvalVal(
5983 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005984 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005985 return Result;
5986
5987 return E;
5988
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005989 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005990 // Check that we don't return or take the address of a reference to a
5991 // temporary. This is only useful in C++.
5992 if (!E->isTypeDependent() && E->isRValue())
5993 return E;
5994
5995 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005996 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005997 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005998} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005999}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006000
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006001void
6002Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6003 SourceLocation ReturnLoc,
6004 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006005 const AttrVec *Attrs,
6006 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006007 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6008
6009 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006010 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6011 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006012 CheckNonNullExpr(*this, RetValExp))
6013 Diag(ReturnLoc, diag::warn_null_ret)
6014 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006015
6016 // C++11 [basic.stc.dynamic.allocation]p4:
6017 // If an allocation function declared with a non-throwing
6018 // exception-specification fails to allocate storage, it shall return
6019 // a null pointer. Any other allocation function that fails to allocate
6020 // storage shall indicate failure only by throwing an exception [...]
6021 if (FD) {
6022 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6023 if (Op == OO_New || Op == OO_Array_New) {
6024 const FunctionProtoType *Proto
6025 = FD->getType()->castAs<FunctionProtoType>();
6026 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6027 CheckNonNullExpr(*this, RetValExp))
6028 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6029 << FD << getLangOpts().CPlusPlus11;
6030 }
6031 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006032}
6033
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006034//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6035
6036/// Check for comparisons of floating point operands using != and ==.
6037/// Issue a warning if these are no self-comparisons, as they are not likely
6038/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006039void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006040 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6041 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006042
6043 // Special case: check for x == x (which is OK).
6044 // Do not emit warnings for such cases.
6045 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6046 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6047 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006048 return;
Mike Stump11289f42009-09-09 15:08:12 +00006049
6050
Ted Kremenekeda40e22007-11-29 00:59:04 +00006051 // Special case: check for comparisons against literals that can be exactly
6052 // represented by APFloat. In such cases, do not emit a warning. This
6053 // is a heuristic: often comparison against such literals are used to
6054 // detect if a value in a variable has not changed. This clearly can
6055 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006056 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6057 if (FLL->isExact())
6058 return;
6059 } else
6060 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6061 if (FLR->isExact())
6062 return;
Mike Stump11289f42009-09-09 15:08:12 +00006063
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006064 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006065 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006066 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006067 return;
Mike Stump11289f42009-09-09 15:08:12 +00006068
David Blaikie1f4ff152012-07-16 20:47:22 +00006069 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006070 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006071 return;
Mike Stump11289f42009-09-09 15:08:12 +00006072
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006073 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006074 Diag(Loc, diag::warn_floatingpoint_eq)
6075 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006076}
John McCallca01b222010-01-04 23:21:16 +00006077
John McCall70aa5392010-01-06 05:24:50 +00006078//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6079//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006080
John McCall70aa5392010-01-06 05:24:50 +00006081namespace {
John McCallca01b222010-01-04 23:21:16 +00006082
John McCall70aa5392010-01-06 05:24:50 +00006083/// Structure recording the 'active' range of an integer-valued
6084/// expression.
6085struct IntRange {
6086 /// The number of bits active in the int.
6087 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006088
John McCall70aa5392010-01-06 05:24:50 +00006089 /// True if the int is known not to have negative values.
6090 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006091
John McCall70aa5392010-01-06 05:24:50 +00006092 IntRange(unsigned Width, bool NonNegative)
6093 : Width(Width), NonNegative(NonNegative)
6094 {}
John McCallca01b222010-01-04 23:21:16 +00006095
John McCall817d4af2010-11-10 23:38:19 +00006096 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006097 static IntRange forBoolType() {
6098 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006099 }
6100
John McCall817d4af2010-11-10 23:38:19 +00006101 /// Returns the range of an opaque value of the given integral type.
6102 static IntRange forValueOfType(ASTContext &C, QualType T) {
6103 return forValueOfCanonicalType(C,
6104 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006105 }
6106
John McCall817d4af2010-11-10 23:38:19 +00006107 /// Returns the range of an opaque value of a canonical integral type.
6108 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006109 assert(T->isCanonicalUnqualified());
6110
6111 if (const VectorType *VT = dyn_cast<VectorType>(T))
6112 T = VT->getElementType().getTypePtr();
6113 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6114 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006115 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6116 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006117
David Majnemer6a426652013-06-07 22:07:20 +00006118 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006119 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006120 EnumDecl *Enum = ET->getDecl();
6121 if (!Enum->isCompleteDefinition())
6122 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006123
David Majnemer6a426652013-06-07 22:07:20 +00006124 unsigned NumPositive = Enum->getNumPositiveBits();
6125 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006126
David Majnemer6a426652013-06-07 22:07:20 +00006127 if (NumNegative == 0)
6128 return IntRange(NumPositive, true/*NonNegative*/);
6129 else
6130 return IntRange(std::max(NumPositive + 1, NumNegative),
6131 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006132 }
John McCall70aa5392010-01-06 05:24:50 +00006133
6134 const BuiltinType *BT = cast<BuiltinType>(T);
6135 assert(BT->isInteger());
6136
6137 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6138 }
6139
John McCall817d4af2010-11-10 23:38:19 +00006140 /// Returns the "target" range of a canonical integral type, i.e.
6141 /// the range of values expressible in the type.
6142 ///
6143 /// This matches forValueOfCanonicalType except that enums have the
6144 /// full range of their type, not the range of their enumerators.
6145 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6146 assert(T->isCanonicalUnqualified());
6147
6148 if (const VectorType *VT = dyn_cast<VectorType>(T))
6149 T = VT->getElementType().getTypePtr();
6150 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6151 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006152 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6153 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006154 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006155 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006156
6157 const BuiltinType *BT = cast<BuiltinType>(T);
6158 assert(BT->isInteger());
6159
6160 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6161 }
6162
6163 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006164 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006165 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006166 L.NonNegative && R.NonNegative);
6167 }
6168
John McCall817d4af2010-11-10 23:38:19 +00006169 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006170 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006171 return IntRange(std::min(L.Width, R.Width),
6172 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006173 }
6174};
6175
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006176static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6177 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006178 if (value.isSigned() && value.isNegative())
6179 return IntRange(value.getMinSignedBits(), false);
6180
6181 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006182 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006183
6184 // isNonNegative() just checks the sign bit without considering
6185 // signedness.
6186 return IntRange(value.getActiveBits(), true);
6187}
6188
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006189static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6190 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006191 if (result.isInt())
6192 return GetValueRange(C, result.getInt(), MaxWidth);
6193
6194 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006195 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6196 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6197 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6198 R = IntRange::join(R, El);
6199 }
John McCall70aa5392010-01-06 05:24:50 +00006200 return R;
6201 }
6202
6203 if (result.isComplexInt()) {
6204 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6205 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6206 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006207 }
6208
6209 // This can happen with lossless casts to intptr_t of "based" lvalues.
6210 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006211 // FIXME: The only reason we need to pass the type in here is to get
6212 // the sign right on this one case. It would be nice if APValue
6213 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006214 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006215 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006216}
John McCall70aa5392010-01-06 05:24:50 +00006217
Eli Friedmane6d33952013-07-08 20:20:06 +00006218static QualType GetExprType(Expr *E) {
6219 QualType Ty = E->getType();
6220 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6221 Ty = AtomicRHS->getValueType();
6222 return Ty;
6223}
6224
John McCall70aa5392010-01-06 05:24:50 +00006225/// Pseudo-evaluate the given integer expression, estimating the
6226/// range of values it might take.
6227///
6228/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006229static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006230 E = E->IgnoreParens();
6231
6232 // Try a full evaluation first.
6233 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006234 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006235 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006236
6237 // I think we only want to look through implicit casts here; if the
6238 // user has an explicit widening cast, we should treat the value as
6239 // being of the new, wider type.
6240 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006241 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006242 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6243
Eli Friedmane6d33952013-07-08 20:20:06 +00006244 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006245
John McCalle3027922010-08-25 11:45:40 +00006246 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006247
John McCall70aa5392010-01-06 05:24:50 +00006248 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006249 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006250 return OutputTypeRange;
6251
6252 IntRange SubRange
6253 = GetExprRange(C, CE->getSubExpr(),
6254 std::min(MaxWidth, OutputTypeRange.Width));
6255
6256 // Bail out if the subexpr's range is as wide as the cast type.
6257 if (SubRange.Width >= OutputTypeRange.Width)
6258 return OutputTypeRange;
6259
6260 // Otherwise, we take the smaller width, and we're non-negative if
6261 // either the output type or the subexpr is.
6262 return IntRange(SubRange.Width,
6263 SubRange.NonNegative || OutputTypeRange.NonNegative);
6264 }
6265
6266 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6267 // If we can fold the condition, just take that operand.
6268 bool CondResult;
6269 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6270 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6271 : CO->getFalseExpr(),
6272 MaxWidth);
6273
6274 // Otherwise, conservatively merge.
6275 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6276 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6277 return IntRange::join(L, R);
6278 }
6279
6280 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6281 switch (BO->getOpcode()) {
6282
6283 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006284 case BO_LAnd:
6285 case BO_LOr:
6286 case BO_LT:
6287 case BO_GT:
6288 case BO_LE:
6289 case BO_GE:
6290 case BO_EQ:
6291 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006292 return IntRange::forBoolType();
6293
John McCallc3688382011-07-13 06:35:24 +00006294 // The type of the assignments is the type of the LHS, so the RHS
6295 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006296 case BO_MulAssign:
6297 case BO_DivAssign:
6298 case BO_RemAssign:
6299 case BO_AddAssign:
6300 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006301 case BO_XorAssign:
6302 case BO_OrAssign:
6303 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006304 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006305
John McCallc3688382011-07-13 06:35:24 +00006306 // Simple assignments just pass through the RHS, which will have
6307 // been coerced to the LHS type.
6308 case BO_Assign:
6309 // TODO: bitfields?
6310 return GetExprRange(C, BO->getRHS(), MaxWidth);
6311
John McCall70aa5392010-01-06 05:24:50 +00006312 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006313 case BO_PtrMemD:
6314 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006315 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006316
John McCall2ce81ad2010-01-06 22:07:33 +00006317 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006318 case BO_And:
6319 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006320 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6321 GetExprRange(C, BO->getRHS(), MaxWidth));
6322
John McCall70aa5392010-01-06 05:24:50 +00006323 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006324 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006325 // ...except that we want to treat '1 << (blah)' as logically
6326 // positive. It's an important idiom.
6327 if (IntegerLiteral *I
6328 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6329 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006330 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006331 return IntRange(R.Width, /*NonNegative*/ true);
6332 }
6333 }
6334 // fallthrough
6335
John McCalle3027922010-08-25 11:45:40 +00006336 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006337 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006338
John McCall2ce81ad2010-01-06 22:07:33 +00006339 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006340 case BO_Shr:
6341 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006342 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6343
6344 // If the shift amount is a positive constant, drop the width by
6345 // that much.
6346 llvm::APSInt shift;
6347 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6348 shift.isNonNegative()) {
6349 unsigned zext = shift.getZExtValue();
6350 if (zext >= L.Width)
6351 L.Width = (L.NonNegative ? 0 : 1);
6352 else
6353 L.Width -= zext;
6354 }
6355
6356 return L;
6357 }
6358
6359 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006360 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006361 return GetExprRange(C, BO->getRHS(), MaxWidth);
6362
John McCall2ce81ad2010-01-06 22:07:33 +00006363 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006364 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006365 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006366 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006367 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006368
John McCall51431812011-07-14 22:39:48 +00006369 // The width of a division result is mostly determined by the size
6370 // of the LHS.
6371 case BO_Div: {
6372 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006373 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006374 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6375
6376 // If the divisor is constant, use that.
6377 llvm::APSInt divisor;
6378 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6379 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6380 if (log2 >= L.Width)
6381 L.Width = (L.NonNegative ? 0 : 1);
6382 else
6383 L.Width = std::min(L.Width - log2, MaxWidth);
6384 return L;
6385 }
6386
6387 // Otherwise, just use the LHS's width.
6388 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6389 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6390 }
6391
6392 // The result of a remainder can't be larger than the result of
6393 // either side.
6394 case BO_Rem: {
6395 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006396 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006397 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6398 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6399
6400 IntRange meet = IntRange::meet(L, R);
6401 meet.Width = std::min(meet.Width, MaxWidth);
6402 return meet;
6403 }
6404
6405 // The default behavior is okay for these.
6406 case BO_Mul:
6407 case BO_Add:
6408 case BO_Xor:
6409 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006410 break;
6411 }
6412
John McCall51431812011-07-14 22:39:48 +00006413 // The default case is to treat the operation as if it were closed
6414 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006415 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6416 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6417 return IntRange::join(L, R);
6418 }
6419
6420 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6421 switch (UO->getOpcode()) {
6422 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006423 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006424 return IntRange::forBoolType();
6425
6426 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006427 case UO_Deref:
6428 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006429 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006430
6431 default:
6432 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6433 }
6434 }
6435
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006436 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6437 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6438
John McCalld25db7e2013-05-06 21:39:12 +00006439 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006440 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006441 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006442
Eli Friedmane6d33952013-07-08 20:20:06 +00006443 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006444}
John McCall263a48b2010-01-04 23:31:57 +00006445
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006446static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006447 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006448}
6449
John McCall263a48b2010-01-04 23:31:57 +00006450/// Checks whether the given value, which currently has the given
6451/// source semantics, has the same value when coerced through the
6452/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006453static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6454 const llvm::fltSemantics &Src,
6455 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006456 llvm::APFloat truncated = value;
6457
6458 bool ignored;
6459 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6460 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6461
6462 return truncated.bitwiseIsEqual(value);
6463}
6464
6465/// Checks whether the given value, which currently has the given
6466/// source semantics, has the same value when coerced through the
6467/// target semantics.
6468///
6469/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006470static bool IsSameFloatAfterCast(const APValue &value,
6471 const llvm::fltSemantics &Src,
6472 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006473 if (value.isFloat())
6474 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6475
6476 if (value.isVector()) {
6477 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6478 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6479 return false;
6480 return true;
6481 }
6482
6483 assert(value.isComplexFloat());
6484 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6485 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6486}
6487
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006488static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006489
Ted Kremenek6274be42010-09-23 21:43:44 +00006490static bool IsZero(Sema &S, Expr *E) {
6491 // Suppress cases where we are comparing against an enum constant.
6492 if (const DeclRefExpr *DR =
6493 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6494 if (isa<EnumConstantDecl>(DR->getDecl()))
6495 return false;
6496
6497 // Suppress cases where the '0' value is expanded from a macro.
6498 if (E->getLocStart().isMacroID())
6499 return false;
6500
John McCallcc7e5bf2010-05-06 08:58:33 +00006501 llvm::APSInt Value;
6502 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6503}
6504
John McCall2551c1b2010-10-06 00:25:24 +00006505static bool HasEnumType(Expr *E) {
6506 // Strip off implicit integral promotions.
6507 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006508 if (ICE->getCastKind() != CK_IntegralCast &&
6509 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006510 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006511 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006512 }
6513
6514 return E->getType()->isEnumeralType();
6515}
6516
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006517static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006518 // Disable warning in template instantiations.
6519 if (!S.ActiveTemplateInstantiations.empty())
6520 return;
6521
John McCalle3027922010-08-25 11:45:40 +00006522 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006523 if (E->isValueDependent())
6524 return;
6525
John McCalle3027922010-08-25 11:45:40 +00006526 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006527 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006528 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006529 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006530 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006531 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006532 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006533 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006534 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006535 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006536 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006537 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006538 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006539 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006540 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006541 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6542 }
6543}
6544
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006545static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006546 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006547 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006548 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006549 // Disable warning in template instantiations.
6550 if (!S.ActiveTemplateInstantiations.empty())
6551 return;
6552
Richard Trieu0f097742014-04-04 04:13:47 +00006553 // TODO: Investigate using GetExprRange() to get tighter bounds
6554 // on the bit ranges.
6555 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006556 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006557 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006558 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6559 unsigned OtherWidth = OtherRange.Width;
6560
6561 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6562
Richard Trieu560910c2012-11-14 22:50:24 +00006563 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006564 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006565 return;
6566
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006567 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006568 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006569
Richard Trieu0f097742014-04-04 04:13:47 +00006570 // Used for diagnostic printout.
6571 enum {
6572 LiteralConstant = 0,
6573 CXXBoolLiteralTrue,
6574 CXXBoolLiteralFalse
6575 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006576
Richard Trieu0f097742014-04-04 04:13:47 +00006577 if (!OtherIsBooleanType) {
6578 QualType ConstantT = Constant->getType();
6579 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006580
Richard Trieu0f097742014-04-04 04:13:47 +00006581 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6582 return;
6583 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6584 "comparison with non-integer type");
6585
6586 bool ConstantSigned = ConstantT->isSignedIntegerType();
6587 bool CommonSigned = CommonT->isSignedIntegerType();
6588
6589 bool EqualityOnly = false;
6590
6591 if (CommonSigned) {
6592 // The common type is signed, therefore no signed to unsigned conversion.
6593 if (!OtherRange.NonNegative) {
6594 // Check that the constant is representable in type OtherT.
6595 if (ConstantSigned) {
6596 if (OtherWidth >= Value.getMinSignedBits())
6597 return;
6598 } else { // !ConstantSigned
6599 if (OtherWidth >= Value.getActiveBits() + 1)
6600 return;
6601 }
6602 } else { // !OtherSigned
6603 // Check that the constant is representable in type OtherT.
6604 // Negative values are out of range.
6605 if (ConstantSigned) {
6606 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6607 return;
6608 } else { // !ConstantSigned
6609 if (OtherWidth >= Value.getActiveBits())
6610 return;
6611 }
Richard Trieu560910c2012-11-14 22:50:24 +00006612 }
Richard Trieu0f097742014-04-04 04:13:47 +00006613 } else { // !CommonSigned
6614 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006615 if (OtherWidth >= Value.getActiveBits())
6616 return;
Craig Toppercf360162014-06-18 05:13:11 +00006617 } else { // OtherSigned
6618 assert(!ConstantSigned &&
6619 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006620 // Check to see if the constant is representable in OtherT.
6621 if (OtherWidth > Value.getActiveBits())
6622 return;
6623 // Check to see if the constant is equivalent to a negative value
6624 // cast to CommonT.
6625 if (S.Context.getIntWidth(ConstantT) ==
6626 S.Context.getIntWidth(CommonT) &&
6627 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6628 return;
6629 // The constant value rests between values that OtherT can represent
6630 // after conversion. Relational comparison still works, but equality
6631 // comparisons will be tautological.
6632 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006633 }
6634 }
Richard Trieu0f097742014-04-04 04:13:47 +00006635
6636 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6637
6638 if (op == BO_EQ || op == BO_NE) {
6639 IsTrue = op == BO_NE;
6640 } else if (EqualityOnly) {
6641 return;
6642 } else if (RhsConstant) {
6643 if (op == BO_GT || op == BO_GE)
6644 IsTrue = !PositiveConstant;
6645 else // op == BO_LT || op == BO_LE
6646 IsTrue = PositiveConstant;
6647 } else {
6648 if (op == BO_LT || op == BO_LE)
6649 IsTrue = !PositiveConstant;
6650 else // op == BO_GT || op == BO_GE
6651 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006652 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006653 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006654 // Other isKnownToHaveBooleanValue
6655 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6656 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6657 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6658
6659 static const struct LinkedConditions {
6660 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6661 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6662 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6663 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6664 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6665 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6666
6667 } TruthTable = {
6668 // Constant on LHS. | Constant on RHS. |
6669 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6670 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6671 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6672 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6673 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6674 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6675 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6676 };
6677
6678 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6679
6680 enum ConstantValue ConstVal = Zero;
6681 if (Value.isUnsigned() || Value.isNonNegative()) {
6682 if (Value == 0) {
6683 LiteralOrBoolConstant =
6684 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6685 ConstVal = Zero;
6686 } else if (Value == 1) {
6687 LiteralOrBoolConstant =
6688 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6689 ConstVal = One;
6690 } else {
6691 LiteralOrBoolConstant = LiteralConstant;
6692 ConstVal = GT_One;
6693 }
6694 } else {
6695 ConstVal = LT_Zero;
6696 }
6697
6698 CompareBoolWithConstantResult CmpRes;
6699
6700 switch (op) {
6701 case BO_LT:
6702 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6703 break;
6704 case BO_GT:
6705 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6706 break;
6707 case BO_LE:
6708 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6709 break;
6710 case BO_GE:
6711 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6712 break;
6713 case BO_EQ:
6714 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6715 break;
6716 case BO_NE:
6717 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6718 break;
6719 default:
6720 CmpRes = Unkwn;
6721 break;
6722 }
6723
6724 if (CmpRes == AFals) {
6725 IsTrue = false;
6726 } else if (CmpRes == ATrue) {
6727 IsTrue = true;
6728 } else {
6729 return;
6730 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006731 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006732
6733 // If this is a comparison to an enum constant, include that
6734 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006735 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006736 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6737 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6738
6739 SmallString<64> PrettySourceValue;
6740 llvm::raw_svector_ostream OS(PrettySourceValue);
6741 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006742 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006743 else
6744 OS << Value;
6745
Richard Trieu0f097742014-04-04 04:13:47 +00006746 S.DiagRuntimeBehavior(
6747 E->getOperatorLoc(), E,
6748 S.PDiag(diag::warn_out_of_range_compare)
6749 << OS.str() << LiteralOrBoolConstant
6750 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6751 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006752}
6753
John McCallcc7e5bf2010-05-06 08:58:33 +00006754/// Analyze the operands of the given comparison. Implements the
6755/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006756static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006757 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6758 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006759}
John McCall263a48b2010-01-04 23:31:57 +00006760
John McCallca01b222010-01-04 23:21:16 +00006761/// \brief Implements -Wsign-compare.
6762///
Richard Trieu82402a02011-09-15 21:56:47 +00006763/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006764static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006765 // The type the comparison is being performed in.
6766 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006767
6768 // Only analyze comparison operators where both sides have been converted to
6769 // the same type.
6770 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6771 return AnalyzeImpConvsInComparison(S, E);
6772
6773 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006774 if (E->isValueDependent())
6775 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006776
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006777 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6778 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006779
6780 bool IsComparisonConstant = false;
6781
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006782 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006783 // of 'true' or 'false'.
6784 if (T->isIntegralType(S.Context)) {
6785 llvm::APSInt RHSValue;
6786 bool IsRHSIntegralLiteral =
6787 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6788 llvm::APSInt LHSValue;
6789 bool IsLHSIntegralLiteral =
6790 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6791 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6792 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6793 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6794 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6795 else
6796 IsComparisonConstant =
6797 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006798 } else if (!T->hasUnsignedIntegerRepresentation())
6799 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006800
John McCallcc7e5bf2010-05-06 08:58:33 +00006801 // We don't do anything special if this isn't an unsigned integral
6802 // comparison: we're only interested in integral comparisons, and
6803 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006804 //
6805 // We also don't care about value-dependent expressions or expressions
6806 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006807 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006808 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006809
John McCallcc7e5bf2010-05-06 08:58:33 +00006810 // Check to see if one of the (unmodified) operands is of different
6811 // signedness.
6812 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006813 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6814 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006815 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006816 signedOperand = LHS;
6817 unsignedOperand = RHS;
6818 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6819 signedOperand = RHS;
6820 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006821 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006822 CheckTrivialUnsignedComparison(S, E);
6823 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006824 }
6825
John McCallcc7e5bf2010-05-06 08:58:33 +00006826 // Otherwise, calculate the effective range of the signed operand.
6827 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006828
John McCallcc7e5bf2010-05-06 08:58:33 +00006829 // Go ahead and analyze implicit conversions in the operands. Note
6830 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006831 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6832 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006833
John McCallcc7e5bf2010-05-06 08:58:33 +00006834 // If the signed range is non-negative, -Wsign-compare won't fire,
6835 // but we should still check for comparisons which are always true
6836 // or false.
6837 if (signedRange.NonNegative)
6838 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006839
6840 // For (in)equality comparisons, if the unsigned operand is a
6841 // constant which cannot collide with a overflowed signed operand,
6842 // then reinterpreting the signed operand as unsigned will not
6843 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006844 if (E->isEqualityOp()) {
6845 unsigned comparisonWidth = S.Context.getIntWidth(T);
6846 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006847
John McCallcc7e5bf2010-05-06 08:58:33 +00006848 // We should never be unable to prove that the unsigned operand is
6849 // non-negative.
6850 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6851
6852 if (unsignedRange.Width < comparisonWidth)
6853 return;
6854 }
6855
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006856 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6857 S.PDiag(diag::warn_mixed_sign_comparison)
6858 << LHS->getType() << RHS->getType()
6859 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006860}
6861
John McCall1f425642010-11-11 03:21:53 +00006862/// Analyzes an attempt to assign the given value to a bitfield.
6863///
6864/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006865static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6866 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006867 assert(Bitfield->isBitField());
6868 if (Bitfield->isInvalidDecl())
6869 return false;
6870
John McCalldeebbcf2010-11-11 05:33:51 +00006871 // White-list bool bitfields.
6872 if (Bitfield->getType()->isBooleanType())
6873 return false;
6874
Douglas Gregor789adec2011-02-04 13:09:01 +00006875 // Ignore value- or type-dependent expressions.
6876 if (Bitfield->getBitWidth()->isValueDependent() ||
6877 Bitfield->getBitWidth()->isTypeDependent() ||
6878 Init->isValueDependent() ||
6879 Init->isTypeDependent())
6880 return false;
6881
John McCall1f425642010-11-11 03:21:53 +00006882 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6883
Richard Smith5fab0c92011-12-28 19:48:30 +00006884 llvm::APSInt Value;
6885 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006886 return false;
6887
John McCall1f425642010-11-11 03:21:53 +00006888 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006889 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006890
6891 if (OriginalWidth <= FieldWidth)
6892 return false;
6893
Eli Friedmanc267a322012-01-26 23:11:39 +00006894 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006895 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006896 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006897
Eli Friedmanc267a322012-01-26 23:11:39 +00006898 // Check whether the stored value is equal to the original value.
6899 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006900 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006901 return false;
6902
Eli Friedmanc267a322012-01-26 23:11:39 +00006903 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006904 // therefore don't strictly fit into a signed bitfield of width 1.
6905 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006906 return false;
6907
John McCall1f425642010-11-11 03:21:53 +00006908 std::string PrettyValue = Value.toString(10);
6909 std::string PrettyTrunc = TruncatedValue.toString(10);
6910
6911 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6912 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6913 << Init->getSourceRange();
6914
6915 return true;
6916}
6917
John McCalld2a53122010-11-09 23:24:47 +00006918/// Analyze the given simple or compound assignment for warning-worthy
6919/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006920static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006921 // Just recurse on the LHS.
6922 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6923
6924 // We want to recurse on the RHS as normal unless we're assigning to
6925 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006926 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006927 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006928 E->getOperatorLoc())) {
6929 // Recurse, ignoring any implicit conversions on the RHS.
6930 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6931 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006932 }
6933 }
6934
6935 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6936}
6937
John McCall263a48b2010-01-04 23:31:57 +00006938/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006939static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006940 SourceLocation CContext, unsigned diag,
6941 bool pruneControlFlow = false) {
6942 if (pruneControlFlow) {
6943 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6944 S.PDiag(diag)
6945 << SourceType << T << E->getSourceRange()
6946 << SourceRange(CContext));
6947 return;
6948 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006949 S.Diag(E->getExprLoc(), diag)
6950 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6951}
6952
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006953/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006954static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006955 SourceLocation CContext, unsigned diag,
6956 bool pruneControlFlow = false) {
6957 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006958}
6959
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006960/// Diagnose an implicit cast from a literal expression. Does not warn when the
6961/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006962void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6963 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006964 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006965 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006966 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006967 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6968 T->hasUnsignedIntegerRepresentation());
6969 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006970 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006971 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006972 return;
6973
Eli Friedman07185912013-08-29 23:44:43 +00006974 // FIXME: Force the precision of the source value down so we don't print
6975 // digits which are usually useless (we don't really care here if we
6976 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6977 // would automatically print the shortest representation, but it's a bit
6978 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006979 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006980 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6981 precision = (precision * 59 + 195) / 196;
6982 Value.toString(PrettySourceValue, precision);
6983
David Blaikie9b88cc02012-05-15 17:18:27 +00006984 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006985 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00006986 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00006987 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006988 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006989
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006990 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006991 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6992 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006993}
6994
John McCall18a2c2c2010-11-09 22:22:12 +00006995std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6996 if (!Range.Width) return "0";
6997
6998 llvm::APSInt ValueInRange = Value;
6999 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007000 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007001 return ValueInRange.toString(10);
7002}
7003
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007004static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
7005 if (!isa<ImplicitCastExpr>(Ex))
7006 return false;
7007
7008 Expr *InnerE = Ex->IgnoreParenImpCasts();
7009 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7010 const Type *Source =
7011 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7012 if (Target->isDependentType())
7013 return false;
7014
7015 const BuiltinType *FloatCandidateBT =
7016 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7017 const Type *BoolCandidateType = ToBool ? Target : Source;
7018
7019 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7020 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7021}
7022
7023void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7024 SourceLocation CC) {
7025 unsigned NumArgs = TheCall->getNumArgs();
7026 for (unsigned i = 0; i < NumArgs; ++i) {
7027 Expr *CurrA = TheCall->getArg(i);
7028 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7029 continue;
7030
7031 bool IsSwapped = ((i > 0) &&
7032 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7033 IsSwapped |= ((i < (NumArgs - 1)) &&
7034 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7035 if (IsSwapped) {
7036 // Warn on this floating-point to bool conversion.
7037 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7038 CurrA->getType(), CC,
7039 diag::warn_impcast_floating_point_to_bool);
7040 }
7041 }
7042}
7043
Richard Trieu5b993502014-10-15 03:42:06 +00007044static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7045 SourceLocation CC) {
7046 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7047 E->getExprLoc()))
7048 return;
7049
Richard Trieu09d6b802016-01-08 23:35:06 +00007050 // Don't warn on functions which have return type nullptr_t.
7051 if (isa<CallExpr>(E))
7052 return;
7053
Richard Trieu5b993502014-10-15 03:42:06 +00007054 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7055 const Expr::NullPointerConstantKind NullKind =
7056 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7057 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7058 return;
7059
7060 // Return if target type is a safe conversion.
7061 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7062 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7063 return;
7064
7065 SourceLocation Loc = E->getSourceRange().getBegin();
7066
7067 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7068 if (NullKind == Expr::NPCK_GNUNull) {
Richard Trieufc014f22016-01-09 01:10:17 +00007069 if (Loc.isMacroID()) {
7070 StringRef MacroName =
7071 Lexer::getImmediateMacroName(Loc, S.SourceMgr, S.getLangOpts());
7072 if (MacroName == "NULL")
7073 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7074 }
Richard Trieu5b993502014-10-15 03:42:06 +00007075 }
7076
7077 // Only warn if the null and context location are in the same macro expansion.
7078 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7079 return;
7080
7081 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7082 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7083 << FixItHint::CreateReplacement(Loc,
7084 S.getFixItZeroLiteralForType(T, Loc));
7085}
7086
Douglas Gregor5054cb02015-07-07 03:58:22 +00007087static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7088 ObjCArrayLiteral *ArrayLiteral);
7089static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7090 ObjCDictionaryLiteral *DictionaryLiteral);
7091
7092/// Check a single element within a collection literal against the
7093/// target element type.
7094static void checkObjCCollectionLiteralElement(Sema &S,
7095 QualType TargetElementType,
7096 Expr *Element,
7097 unsigned ElementKind) {
7098 // Skip a bitcast to 'id' or qualified 'id'.
7099 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7100 if (ICE->getCastKind() == CK_BitCast &&
7101 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7102 Element = ICE->getSubExpr();
7103 }
7104
7105 QualType ElementType = Element->getType();
7106 ExprResult ElementResult(Element);
7107 if (ElementType->getAs<ObjCObjectPointerType>() &&
7108 S.CheckSingleAssignmentConstraints(TargetElementType,
7109 ElementResult,
7110 false, false)
7111 != Sema::Compatible) {
7112 S.Diag(Element->getLocStart(),
7113 diag::warn_objc_collection_literal_element)
7114 << ElementType << ElementKind << TargetElementType
7115 << Element->getSourceRange();
7116 }
7117
7118 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7119 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7120 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7121 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7122}
7123
7124/// Check an Objective-C array literal being converted to the given
7125/// target type.
7126static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7127 ObjCArrayLiteral *ArrayLiteral) {
7128 if (!S.NSArrayDecl)
7129 return;
7130
7131 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7132 if (!TargetObjCPtr)
7133 return;
7134
7135 if (TargetObjCPtr->isUnspecialized() ||
7136 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7137 != S.NSArrayDecl->getCanonicalDecl())
7138 return;
7139
7140 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7141 if (TypeArgs.size() != 1)
7142 return;
7143
7144 QualType TargetElementType = TypeArgs[0];
7145 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7146 checkObjCCollectionLiteralElement(S, TargetElementType,
7147 ArrayLiteral->getElement(I),
7148 0);
7149 }
7150}
7151
7152/// Check an Objective-C dictionary literal being converted to the given
7153/// target type.
7154static void checkObjCDictionaryLiteral(
7155 Sema &S, QualType TargetType,
7156 ObjCDictionaryLiteral *DictionaryLiteral) {
7157 if (!S.NSDictionaryDecl)
7158 return;
7159
7160 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7161 if (!TargetObjCPtr)
7162 return;
7163
7164 if (TargetObjCPtr->isUnspecialized() ||
7165 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7166 != S.NSDictionaryDecl->getCanonicalDecl())
7167 return;
7168
7169 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7170 if (TypeArgs.size() != 2)
7171 return;
7172
7173 QualType TargetKeyType = TypeArgs[0];
7174 QualType TargetObjectType = TypeArgs[1];
7175 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7176 auto Element = DictionaryLiteral->getKeyValueElement(I);
7177 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7178 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7179 }
7180}
7181
John McCallcc7e5bf2010-05-06 08:58:33 +00007182void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007183 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007184 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007185
John McCallcc7e5bf2010-05-06 08:58:33 +00007186 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7187 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7188 if (Source == Target) return;
7189 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007190
Chandler Carruthc22845a2011-07-26 05:40:03 +00007191 // If the conversion context location is invalid don't complain. We also
7192 // don't want to emit a warning if the issue occurs from the expansion of
7193 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7194 // delay this check as long as possible. Once we detect we are in that
7195 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007196 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007197 return;
7198
Richard Trieu021baa32011-09-23 20:10:00 +00007199 // Diagnose implicit casts to bool.
7200 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7201 if (isa<StringLiteral>(E))
7202 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007203 // and expressions, for instance, assert(0 && "error here"), are
7204 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007205 return DiagnoseImpCast(S, E, T, CC,
7206 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007207 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7208 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7209 // This covers the literal expressions that evaluate to Objective-C
7210 // objects.
7211 return DiagnoseImpCast(S, E, T, CC,
7212 diag::warn_impcast_objective_c_literal_to_bool);
7213 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007214 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7215 // Warn on pointer to bool conversion that is always true.
7216 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7217 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007218 }
Richard Trieu021baa32011-09-23 20:10:00 +00007219 }
John McCall263a48b2010-01-04 23:31:57 +00007220
Douglas Gregor5054cb02015-07-07 03:58:22 +00007221 // Check implicit casts from Objective-C collection literals to specialized
7222 // collection types, e.g., NSArray<NSString *> *.
7223 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7224 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7225 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7226 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7227
John McCall263a48b2010-01-04 23:31:57 +00007228 // Strip vector types.
7229 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007230 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007231 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007232 return;
John McCallacf0ee52010-10-08 02:01:28 +00007233 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007234 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007235
7236 // If the vector cast is cast between two vectors of the same size, it is
7237 // a bitcast, not a conversion.
7238 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7239 return;
John McCall263a48b2010-01-04 23:31:57 +00007240
7241 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7242 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7243 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007244 if (auto VecTy = dyn_cast<VectorType>(Target))
7245 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007246
7247 // Strip complex types.
7248 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007249 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007250 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007251 return;
7252
John McCallacf0ee52010-10-08 02:01:28 +00007253 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007254 }
John McCall263a48b2010-01-04 23:31:57 +00007255
7256 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7257 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7258 }
7259
7260 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7261 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7262
7263 // If the source is floating point...
7264 if (SourceBT && SourceBT->isFloatingPoint()) {
7265 // ...and the target is floating point...
7266 if (TargetBT && TargetBT->isFloatingPoint()) {
7267 // ...then warn if we're dropping FP rank.
7268
7269 // Builtin FP kinds are ordered by increasing FP rank.
7270 if (SourceBT->getKind() > TargetBT->getKind()) {
7271 // Don't warn about float constants that are precisely
7272 // representable in the target type.
7273 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007274 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007275 // Value might be a float, a float vector, or a float complex.
7276 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007277 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7278 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007279 return;
7280 }
7281
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007282 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007283 return;
7284
John McCallacf0ee52010-10-08 02:01:28 +00007285 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007286
7287 }
7288 // ... or possibly if we're increasing rank, too
7289 else if (TargetBT->getKind() > SourceBT->getKind()) {
7290 if (S.SourceMgr.isInSystemMacro(CC))
7291 return;
7292
7293 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007294 }
7295 return;
7296 }
7297
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007298 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007299 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007300 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007301 return;
7302
Chandler Carruth22c7a792011-02-17 11:05:49 +00007303 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007304 // We also want to warn on, e.g., "int i = -1.234"
7305 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7306 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7307 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7308
Chandler Carruth016ef402011-04-10 08:36:24 +00007309 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7310 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007311 } else {
7312 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7313 }
7314 }
John McCall263a48b2010-01-04 23:31:57 +00007315
Richard Smith54894fd2015-12-30 01:06:52 +00007316 // Detect the case where a call result is converted from floating-point to
7317 // to bool, and the final argument to the call is converted from bool, to
7318 // discover this typo:
7319 //
7320 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7321 //
7322 // FIXME: This is an incredibly special case; is there some more general
7323 // way to detect this class of misplaced-parentheses bug?
7324 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007325 // Check last argument of function call to see if it is an
7326 // implicit cast from a type matching the type the result
7327 // is being cast to.
7328 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007329 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007330 Expr *LastA = CEx->getArg(NumArgs - 1);
7331 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007332 if (isa<ImplicitCastExpr>(LastA) &&
7333 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007334 // Warn on this floating-point to bool conversion
7335 DiagnoseImpCast(S, E, T, CC,
7336 diag::warn_impcast_floating_point_to_bool);
7337 }
7338 }
7339 }
John McCall263a48b2010-01-04 23:31:57 +00007340 return;
7341 }
7342
Richard Trieu5b993502014-10-15 03:42:06 +00007343 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007344
David Blaikie9366d2b2012-06-19 21:19:06 +00007345 if (!Source->isIntegerType() || !Target->isIntegerType())
7346 return;
7347
David Blaikie7555b6a2012-05-15 16:56:36 +00007348 // TODO: remove this early return once the false positives for constant->bool
7349 // in templates, macros, etc, are reduced or removed.
7350 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7351 return;
7352
John McCallcc7e5bf2010-05-06 08:58:33 +00007353 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007354 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007355
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007356 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007357 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007358 // TODO: this should happen for bitfield stores, too.
7359 llvm::APSInt Value(32);
7360 if (E->isIntegerConstantExpr(Value, S.Context)) {
7361 if (S.SourceMgr.isInSystemMacro(CC))
7362 return;
7363
John McCall18a2c2c2010-11-09 22:22:12 +00007364 std::string PrettySourceValue = Value.toString(10);
7365 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007366
Ted Kremenek33ba9952011-10-22 02:37:33 +00007367 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7368 S.PDiag(diag::warn_impcast_integer_precision_constant)
7369 << PrettySourceValue << PrettyTargetValue
7370 << E->getType() << T << E->getSourceRange()
7371 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007372 return;
7373 }
7374
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007375 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7376 if (S.SourceMgr.isInSystemMacro(CC))
7377 return;
7378
David Blaikie9455da02012-04-12 22:40:54 +00007379 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007380 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7381 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007382 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007383 }
7384
7385 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7386 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7387 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007388
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007389 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007390 return;
7391
John McCallcc7e5bf2010-05-06 08:58:33 +00007392 unsigned DiagID = diag::warn_impcast_integer_sign;
7393
7394 // Traditionally, gcc has warned about this under -Wsign-compare.
7395 // We also want to warn about it in -Wconversion.
7396 // So if -Wconversion is off, use a completely identical diagnostic
7397 // in the sign-compare group.
7398 // The conditional-checking code will
7399 if (ICContext) {
7400 DiagID = diag::warn_impcast_integer_sign_conditional;
7401 *ICContext = true;
7402 }
7403
John McCallacf0ee52010-10-08 02:01:28 +00007404 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007405 }
7406
Douglas Gregora78f1932011-02-22 02:45:07 +00007407 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007408 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7409 // type, to give us better diagnostics.
7410 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007411 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007412 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7413 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7414 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7415 SourceType = S.Context.getTypeDeclType(Enum);
7416 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7417 }
7418 }
7419
Douglas Gregora78f1932011-02-22 02:45:07 +00007420 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7421 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007422 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7423 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007424 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007425 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007426 return;
7427
Douglas Gregor364f7db2011-03-12 00:14:31 +00007428 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007429 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007430 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007431
John McCall263a48b2010-01-04 23:31:57 +00007432 return;
7433}
7434
David Blaikie18e9ac72012-05-15 21:57:38 +00007435void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7436 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007437
7438void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007439 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007440 E = E->IgnoreParenImpCasts();
7441
7442 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007443 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007444
John McCallacf0ee52010-10-08 02:01:28 +00007445 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007446 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007447 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007448 return;
7449}
7450
David Blaikie18e9ac72012-05-15 21:57:38 +00007451void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7452 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007453 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007454
7455 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007456 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7457 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007458
7459 // If -Wconversion would have warned about either of the candidates
7460 // for a signedness conversion to the context type...
7461 if (!Suspicious) return;
7462
7463 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007464 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007465 return;
7466
John McCallcc7e5bf2010-05-06 08:58:33 +00007467 // ...then check whether it would have warned about either of the
7468 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007469 if (E->getType() == T) return;
7470
7471 Suspicious = false;
7472 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7473 E->getType(), CC, &Suspicious);
7474 if (!Suspicious)
7475 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007476 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007477}
7478
Richard Trieu65724892014-11-15 06:37:39 +00007479/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7480/// Input argument E is a logical expression.
7481static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7482 if (S.getLangOpts().Bool)
7483 return;
7484 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7485}
7486
John McCallcc7e5bf2010-05-06 08:58:33 +00007487/// AnalyzeImplicitConversions - Find and report any interesting
7488/// implicit conversions in the given expression. There are a couple
7489/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007490void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007491 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007492 Expr *E = OrigE->IgnoreParenImpCasts();
7493
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007494 if (E->isTypeDependent() || E->isValueDependent())
7495 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007496
John McCallcc7e5bf2010-05-06 08:58:33 +00007497 // For conditional operators, we analyze the arguments as if they
7498 // were being fed directly into the output.
7499 if (isa<ConditionalOperator>(E)) {
7500 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007501 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007502 return;
7503 }
7504
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007505 // Check implicit argument conversions for function calls.
7506 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7507 CheckImplicitArgumentConversions(S, Call, CC);
7508
John McCallcc7e5bf2010-05-06 08:58:33 +00007509 // Go ahead and check any implicit conversions we might have skipped.
7510 // The non-canonical typecheck is just an optimization;
7511 // CheckImplicitConversion will filter out dead implicit conversions.
7512 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007513 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007514
7515 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007516
7517 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7518 // The bound subexpressions in a PseudoObjectExpr are not reachable
7519 // as transitive children.
7520 // FIXME: Use a more uniform representation for this.
7521 for (auto *SE : POE->semantics())
7522 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7523 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007524 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007525
John McCallcc7e5bf2010-05-06 08:58:33 +00007526 // Skip past explicit casts.
7527 if (isa<ExplicitCastExpr>(E)) {
7528 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007529 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007530 }
7531
John McCalld2a53122010-11-09 23:24:47 +00007532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7533 // Do a somewhat different check with comparison operators.
7534 if (BO->isComparisonOp())
7535 return AnalyzeComparison(S, BO);
7536
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007537 // And with simple assignments.
7538 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007539 return AnalyzeAssignment(S, BO);
7540 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007541
7542 // These break the otherwise-useful invariant below. Fortunately,
7543 // we don't really need to recurse into them, because any internal
7544 // expressions should have been analyzed already when they were
7545 // built into statements.
7546 if (isa<StmtExpr>(E)) return;
7547
7548 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007549 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007550
7551 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007552 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007553 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007554 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007555 for (Stmt *SubStmt : E->children()) {
7556 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007557 if (!ChildExpr)
7558 continue;
7559
Richard Trieu955231d2014-01-25 01:10:35 +00007560 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007561 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007562 // Ignore checking string literals that are in logical and operators.
7563 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007564 continue;
7565 AnalyzeImplicitConversions(S, ChildExpr, CC);
7566 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007567
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007568 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007569 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7570 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007571 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007572
7573 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7574 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007575 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007576 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007577
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007578 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7579 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007580 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007581}
7582
7583} // end anonymous namespace
7584
Richard Trieuc1888e02014-06-28 23:25:37 +00007585// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7586// Returns true when emitting a warning about taking the address of a reference.
7587static bool CheckForReference(Sema &SemaRef, const Expr *E,
7588 PartialDiagnostic PD) {
7589 E = E->IgnoreParenImpCasts();
7590
7591 const FunctionDecl *FD = nullptr;
7592
7593 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7594 if (!DRE->getDecl()->getType()->isReferenceType())
7595 return false;
7596 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7597 if (!M->getMemberDecl()->getType()->isReferenceType())
7598 return false;
7599 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007600 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007601 return false;
7602 FD = Call->getDirectCallee();
7603 } else {
7604 return false;
7605 }
7606
7607 SemaRef.Diag(E->getExprLoc(), PD);
7608
7609 // If possible, point to location of function.
7610 if (FD) {
7611 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7612 }
7613
7614 return true;
7615}
7616
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007617// Returns true if the SourceLocation is expanded from any macro body.
7618// Returns false if the SourceLocation is invalid, is from not in a macro
7619// expansion, or is from expanded from a top-level macro argument.
7620static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7621 if (Loc.isInvalid())
7622 return false;
7623
7624 while (Loc.isMacroID()) {
7625 if (SM.isMacroBodyExpansion(Loc))
7626 return true;
7627 Loc = SM.getImmediateMacroCallerLoc(Loc);
7628 }
7629
7630 return false;
7631}
7632
Richard Trieu3bb8b562014-02-26 02:36:06 +00007633/// \brief Diagnose pointers that are always non-null.
7634/// \param E the expression containing the pointer
7635/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7636/// compared to a null pointer
7637/// \param IsEqual True when the comparison is equal to a null pointer
7638/// \param Range Extra SourceRange to highlight in the diagnostic
7639void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7640 Expr::NullPointerConstantKind NullKind,
7641 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007642 if (!E)
7643 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007644
7645 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007646 if (E->getExprLoc().isMacroID()) {
7647 const SourceManager &SM = getSourceManager();
7648 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7649 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007650 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007651 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007652 E = E->IgnoreImpCasts();
7653
7654 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7655
Richard Trieuf7432752014-06-06 21:39:26 +00007656 if (isa<CXXThisExpr>(E)) {
7657 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7658 : diag::warn_this_bool_conversion;
7659 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7660 return;
7661 }
7662
Richard Trieu3bb8b562014-02-26 02:36:06 +00007663 bool IsAddressOf = false;
7664
7665 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7666 if (UO->getOpcode() != UO_AddrOf)
7667 return;
7668 IsAddressOf = true;
7669 E = UO->getSubExpr();
7670 }
7671
Richard Trieuc1888e02014-06-28 23:25:37 +00007672 if (IsAddressOf) {
7673 unsigned DiagID = IsCompare
7674 ? diag::warn_address_of_reference_null_compare
7675 : diag::warn_address_of_reference_bool_conversion;
7676 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7677 << IsEqual;
7678 if (CheckForReference(*this, E, PD)) {
7679 return;
7680 }
7681 }
7682
George Burgess IV850269a2015-12-08 22:02:00 +00007683 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7684 std::string Str;
7685 llvm::raw_string_ostream S(Str);
7686 E->printPretty(S, nullptr, getPrintingPolicy());
7687 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7688 : diag::warn_cast_nonnull_to_bool;
7689 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7690 << E->getSourceRange() << Range << IsEqual;
7691 };
7692
7693 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
7694 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
7695 if (auto *Callee = Call->getDirectCallee()) {
7696 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7697 ComplainAboutNonnullParamOrCall(false);
7698 return;
7699 }
7700 }
7701 }
7702
Richard Trieu3bb8b562014-02-26 02:36:06 +00007703 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007704 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007705 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7706 D = R->getDecl();
7707 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7708 D = M->getMemberDecl();
7709 }
7710
7711 // Weak Decls can be null.
7712 if (!D || D->isWeak())
7713 return;
George Burgess IV850269a2015-12-08 22:02:00 +00007714
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007715 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00007716 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
7717 if (getCurFunction() &&
7718 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
7719 if (PV->hasAttr<NonNullAttr>()) {
7720 ComplainAboutNonnullParamOrCall(true);
7721 return;
7722 }
7723
7724 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7725 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
7726 assert(ParamIter != FD->param_end());
7727 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
7728
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007729 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7730 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00007731 ComplainAboutNonnullParamOrCall(true);
7732 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007733 }
George Burgess IV850269a2015-12-08 22:02:00 +00007734
7735 for (unsigned ArgNo : NonNull->args()) {
7736 if (ArgNo == ParamNo) {
7737 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007738 return;
7739 }
George Burgess IV850269a2015-12-08 22:02:00 +00007740 }
7741 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007742 }
7743 }
George Burgess IV850269a2015-12-08 22:02:00 +00007744 }
7745
Richard Trieu3bb8b562014-02-26 02:36:06 +00007746 QualType T = D->getType();
7747 const bool IsArray = T->isArrayType();
7748 const bool IsFunction = T->isFunctionType();
7749
Richard Trieuc1888e02014-06-28 23:25:37 +00007750 // Address of function is used to silence the function warning.
7751 if (IsAddressOf && IsFunction) {
7752 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007753 }
7754
7755 // Found nothing.
7756 if (!IsAddressOf && !IsFunction && !IsArray)
7757 return;
7758
7759 // Pretty print the expression for the diagnostic.
7760 std::string Str;
7761 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007762 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007763
7764 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7765 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00007766 enum {
7767 AddressOf,
7768 FunctionPointer,
7769 ArrayPointer
7770 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007771 if (IsAddressOf)
7772 DiagType = AddressOf;
7773 else if (IsFunction)
7774 DiagType = FunctionPointer;
7775 else if (IsArray)
7776 DiagType = ArrayPointer;
7777 else
7778 llvm_unreachable("Could not determine diagnostic.");
7779 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7780 << Range << IsEqual;
7781
7782 if (!IsFunction)
7783 return;
7784
7785 // Suggest '&' to silence the function warning.
7786 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7787 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7788
7789 // Check to see if '()' fixit should be emitted.
7790 QualType ReturnType;
7791 UnresolvedSet<4> NonTemplateOverloads;
7792 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7793 if (ReturnType.isNull())
7794 return;
7795
7796 if (IsCompare) {
7797 // There are two cases here. If there is null constant, the only suggest
7798 // for a pointer return type. If the null is 0, then suggest if the return
7799 // type is a pointer or an integer type.
7800 if (!ReturnType->isPointerType()) {
7801 if (NullKind == Expr::NPCK_ZeroExpression ||
7802 NullKind == Expr::NPCK_ZeroLiteral) {
7803 if (!ReturnType->isIntegerType())
7804 return;
7805 } else {
7806 return;
7807 }
7808 }
7809 } else { // !IsCompare
7810 // For function to bool, only suggest if the function pointer has bool
7811 // return type.
7812 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7813 return;
7814 }
7815 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007816 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007817}
7818
7819
John McCallcc7e5bf2010-05-06 08:58:33 +00007820/// Diagnoses "dangerous" implicit conversions within the given
7821/// expression (which is a full expression). Implements -Wconversion
7822/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007823///
7824/// \param CC the "context" location of the implicit conversion, i.e.
7825/// the most location of the syntactic entity requiring the implicit
7826/// conversion
7827void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007828 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007829 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007830 return;
7831
7832 // Don't diagnose for value- or type-dependent expressions.
7833 if (E->isTypeDependent() || E->isValueDependent())
7834 return;
7835
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007836 // Check for array bounds violations in cases where the check isn't triggered
7837 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7838 // ArraySubscriptExpr is on the RHS of a variable initialization.
7839 CheckArrayAccess(E);
7840
John McCallacf0ee52010-10-08 02:01:28 +00007841 // This is not the right CC for (e.g.) a variable initialization.
7842 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007843}
7844
Richard Trieu65724892014-11-15 06:37:39 +00007845/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7846/// Input argument E is a logical expression.
7847void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7848 ::CheckBoolLikeConversion(*this, E, CC);
7849}
7850
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007851/// Diagnose when expression is an integer constant expression and its evaluation
7852/// results in integer overflow
7853void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007854 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7855 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Akira Hatanakaf5c13612016-01-11 17:22:01 +00007856 else if (auto InitList = dyn_cast<InitListExpr>(E))
7857 for (Expr *E : InitList->inits())
7858 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7859 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007860}
7861
Richard Smithc406cb72013-01-17 01:17:56 +00007862namespace {
7863/// \brief Visitor for expressions which looks for unsequenced operations on the
7864/// same object.
7865class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007866 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7867
Richard Smithc406cb72013-01-17 01:17:56 +00007868 /// \brief A tree of sequenced regions within an expression. Two regions are
7869 /// unsequenced if one is an ancestor or a descendent of the other. When we
7870 /// finish processing an expression with sequencing, such as a comma
7871 /// expression, we fold its tree nodes into its parent, since they are
7872 /// unsequenced with respect to nodes we will visit later.
7873 class SequenceTree {
7874 struct Value {
7875 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7876 unsigned Parent : 31;
7877 bool Merged : 1;
7878 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007879 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007880
7881 public:
7882 /// \brief A region within an expression which may be sequenced with respect
7883 /// to some other region.
7884 class Seq {
7885 explicit Seq(unsigned N) : Index(N) {}
7886 unsigned Index;
7887 friend class SequenceTree;
7888 public:
7889 Seq() : Index(0) {}
7890 };
7891
7892 SequenceTree() { Values.push_back(Value(0)); }
7893 Seq root() const { return Seq(0); }
7894
7895 /// \brief Create a new sequence of operations, which is an unsequenced
7896 /// subset of \p Parent. This sequence of operations is sequenced with
7897 /// respect to other children of \p Parent.
7898 Seq allocate(Seq Parent) {
7899 Values.push_back(Value(Parent.Index));
7900 return Seq(Values.size() - 1);
7901 }
7902
7903 /// \brief Merge a sequence of operations into its parent.
7904 void merge(Seq S) {
7905 Values[S.Index].Merged = true;
7906 }
7907
7908 /// \brief Determine whether two operations are unsequenced. This operation
7909 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7910 /// should have been merged into its parent as appropriate.
7911 bool isUnsequenced(Seq Cur, Seq Old) {
7912 unsigned C = representative(Cur.Index);
7913 unsigned Target = representative(Old.Index);
7914 while (C >= Target) {
7915 if (C == Target)
7916 return true;
7917 C = Values[C].Parent;
7918 }
7919 return false;
7920 }
7921
7922 private:
7923 /// \brief Pick a representative for a sequence.
7924 unsigned representative(unsigned K) {
7925 if (Values[K].Merged)
7926 // Perform path compression as we go.
7927 return Values[K].Parent = representative(Values[K].Parent);
7928 return K;
7929 }
7930 };
7931
7932 /// An object for which we can track unsequenced uses.
7933 typedef NamedDecl *Object;
7934
7935 /// Different flavors of object usage which we track. We only track the
7936 /// least-sequenced usage of each kind.
7937 enum UsageKind {
7938 /// A read of an object. Multiple unsequenced reads are OK.
7939 UK_Use,
7940 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007941 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007942 UK_ModAsValue,
7943 /// A modification of an object which is not sequenced before the value
7944 /// computation of the expression, such as n++.
7945 UK_ModAsSideEffect,
7946
7947 UK_Count = UK_ModAsSideEffect + 1
7948 };
7949
7950 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007951 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007952 Expr *Use;
7953 SequenceTree::Seq Seq;
7954 };
7955
7956 struct UsageInfo {
7957 UsageInfo() : Diagnosed(false) {}
7958 Usage Uses[UK_Count];
7959 /// Have we issued a diagnostic for this variable already?
7960 bool Diagnosed;
7961 };
7962 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7963
7964 Sema &SemaRef;
7965 /// Sequenced regions within the expression.
7966 SequenceTree Tree;
7967 /// Declaration modifications and references which we have seen.
7968 UsageInfoMap UsageMap;
7969 /// The region we are currently within.
7970 SequenceTree::Seq Region;
7971 /// Filled in with declarations which were modified as a side-effect
7972 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007973 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007974 /// Expressions to check later. We defer checking these to reduce
7975 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007976 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007977
7978 /// RAII object wrapping the visitation of a sequenced subexpression of an
7979 /// expression. At the end of this process, the side-effects of the evaluation
7980 /// become sequenced with respect to the value computation of the result, so
7981 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7982 /// UK_ModAsValue.
7983 struct SequencedSubexpression {
7984 SequencedSubexpression(SequenceChecker &Self)
7985 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7986 Self.ModAsSideEffect = &ModAsSideEffect;
7987 }
7988 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007989 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7990 MI != ME; ++MI) {
7991 UsageInfo &U = Self.UsageMap[MI->first];
7992 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7993 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7994 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007995 }
7996 Self.ModAsSideEffect = OldModAsSideEffect;
7997 }
7998
7999 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008000 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8001 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008002 };
8003
Richard Smith40238f02013-06-20 22:21:56 +00008004 /// RAII object wrapping the visitation of a subexpression which we might
8005 /// choose to evaluate as a constant. If any subexpression is evaluated and
8006 /// found to be non-constant, this allows us to suppress the evaluation of
8007 /// the outer expression.
8008 class EvaluationTracker {
8009 public:
8010 EvaluationTracker(SequenceChecker &Self)
8011 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8012 Self.EvalTracker = this;
8013 }
8014 ~EvaluationTracker() {
8015 Self.EvalTracker = Prev;
8016 if (Prev)
8017 Prev->EvalOK &= EvalOK;
8018 }
8019
8020 bool evaluate(const Expr *E, bool &Result) {
8021 if (!EvalOK || E->isValueDependent())
8022 return false;
8023 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8024 return EvalOK;
8025 }
8026
8027 private:
8028 SequenceChecker &Self;
8029 EvaluationTracker *Prev;
8030 bool EvalOK;
8031 } *EvalTracker;
8032
Richard Smithc406cb72013-01-17 01:17:56 +00008033 /// \brief Find the object which is produced by the specified expression,
8034 /// if any.
8035 Object getObject(Expr *E, bool Mod) const {
8036 E = E->IgnoreParenCasts();
8037 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8038 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8039 return getObject(UO->getSubExpr(), Mod);
8040 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8041 if (BO->getOpcode() == BO_Comma)
8042 return getObject(BO->getRHS(), Mod);
8043 if (Mod && BO->isAssignmentOp())
8044 return getObject(BO->getLHS(), Mod);
8045 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8046 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8047 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8048 return ME->getMemberDecl();
8049 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8050 // FIXME: If this is a reference, map through to its value.
8051 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008052 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008053 }
8054
8055 /// \brief Note that an object was modified or used by an expression.
8056 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8057 Usage &U = UI.Uses[UK];
8058 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8059 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8060 ModAsSideEffect->push_back(std::make_pair(O, U));
8061 U.Use = Ref;
8062 U.Seq = Region;
8063 }
8064 }
8065 /// \brief Check whether a modification or use conflicts with a prior usage.
8066 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8067 bool IsModMod) {
8068 if (UI.Diagnosed)
8069 return;
8070
8071 const Usage &U = UI.Uses[OtherKind];
8072 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8073 return;
8074
8075 Expr *Mod = U.Use;
8076 Expr *ModOrUse = Ref;
8077 if (OtherKind == UK_Use)
8078 std::swap(Mod, ModOrUse);
8079
8080 SemaRef.Diag(Mod->getExprLoc(),
8081 IsModMod ? diag::warn_unsequenced_mod_mod
8082 : diag::warn_unsequenced_mod_use)
8083 << O << SourceRange(ModOrUse->getExprLoc());
8084 UI.Diagnosed = true;
8085 }
8086
8087 void notePreUse(Object O, Expr *Use) {
8088 UsageInfo &U = UsageMap[O];
8089 // Uses conflict with other modifications.
8090 checkUsage(O, U, Use, UK_ModAsValue, false);
8091 }
8092 void notePostUse(Object O, Expr *Use) {
8093 UsageInfo &U = UsageMap[O];
8094 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8095 addUsage(U, O, Use, UK_Use);
8096 }
8097
8098 void notePreMod(Object O, Expr *Mod) {
8099 UsageInfo &U = UsageMap[O];
8100 // Modifications conflict with other modifications and with uses.
8101 checkUsage(O, U, Mod, UK_ModAsValue, true);
8102 checkUsage(O, U, Mod, UK_Use, false);
8103 }
8104 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8105 UsageInfo &U = UsageMap[O];
8106 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8107 addUsage(U, O, Use, UK);
8108 }
8109
8110public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008111 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008112 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8113 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008114 Visit(E);
8115 }
8116
8117 void VisitStmt(Stmt *S) {
8118 // Skip all statements which aren't expressions for now.
8119 }
8120
8121 void VisitExpr(Expr *E) {
8122 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008123 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008124 }
8125
8126 void VisitCastExpr(CastExpr *E) {
8127 Object O = Object();
8128 if (E->getCastKind() == CK_LValueToRValue)
8129 O = getObject(E->getSubExpr(), false);
8130
8131 if (O)
8132 notePreUse(O, E);
8133 VisitExpr(E);
8134 if (O)
8135 notePostUse(O, E);
8136 }
8137
8138 void VisitBinComma(BinaryOperator *BO) {
8139 // C++11 [expr.comma]p1:
8140 // Every value computation and side effect associated with the left
8141 // expression is sequenced before every value computation and side
8142 // effect associated with the right expression.
8143 SequenceTree::Seq LHS = Tree.allocate(Region);
8144 SequenceTree::Seq RHS = Tree.allocate(Region);
8145 SequenceTree::Seq OldRegion = Region;
8146
8147 {
8148 SequencedSubexpression SeqLHS(*this);
8149 Region = LHS;
8150 Visit(BO->getLHS());
8151 }
8152
8153 Region = RHS;
8154 Visit(BO->getRHS());
8155
8156 Region = OldRegion;
8157
8158 // Forget that LHS and RHS are sequenced. They are both unsequenced
8159 // with respect to other stuff.
8160 Tree.merge(LHS);
8161 Tree.merge(RHS);
8162 }
8163
8164 void VisitBinAssign(BinaryOperator *BO) {
8165 // The modification is sequenced after the value computation of the LHS
8166 // and RHS, so check it before inspecting the operands and update the
8167 // map afterwards.
8168 Object O = getObject(BO->getLHS(), true);
8169 if (!O)
8170 return VisitExpr(BO);
8171
8172 notePreMod(O, BO);
8173
8174 // C++11 [expr.ass]p7:
8175 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8176 // only once.
8177 //
8178 // Therefore, for a compound assignment operator, O is considered used
8179 // everywhere except within the evaluation of E1 itself.
8180 if (isa<CompoundAssignOperator>(BO))
8181 notePreUse(O, BO);
8182
8183 Visit(BO->getLHS());
8184
8185 if (isa<CompoundAssignOperator>(BO))
8186 notePostUse(O, BO);
8187
8188 Visit(BO->getRHS());
8189
Richard Smith83e37bee2013-06-26 23:16:51 +00008190 // C++11 [expr.ass]p1:
8191 // the assignment is sequenced [...] before the value computation of the
8192 // assignment expression.
8193 // C11 6.5.16/3 has no such rule.
8194 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8195 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008196 }
8197 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8198 VisitBinAssign(CAO);
8199 }
8200
8201 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8202 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8203 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8204 Object O = getObject(UO->getSubExpr(), true);
8205 if (!O)
8206 return VisitExpr(UO);
8207
8208 notePreMod(O, UO);
8209 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008210 // C++11 [expr.pre.incr]p1:
8211 // the expression ++x is equivalent to x+=1
8212 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8213 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008214 }
8215
8216 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8217 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8218 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8219 Object O = getObject(UO->getSubExpr(), true);
8220 if (!O)
8221 return VisitExpr(UO);
8222
8223 notePreMod(O, UO);
8224 Visit(UO->getSubExpr());
8225 notePostMod(O, UO, UK_ModAsSideEffect);
8226 }
8227
8228 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8229 void VisitBinLOr(BinaryOperator *BO) {
8230 // The side-effects of the LHS of an '&&' are sequenced before the
8231 // value computation of the RHS, and hence before the value computation
8232 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8233 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008234 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008235 {
8236 SequencedSubexpression Sequenced(*this);
8237 Visit(BO->getLHS());
8238 }
8239
8240 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008241 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008242 if (!Result)
8243 Visit(BO->getRHS());
8244 } else {
8245 // Check for unsequenced operations in the RHS, treating it as an
8246 // entirely separate evaluation.
8247 //
8248 // FIXME: If there are operations in the RHS which are unsequenced
8249 // with respect to operations outside the RHS, and those operations
8250 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008251 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008252 }
Richard Smithc406cb72013-01-17 01:17:56 +00008253 }
8254 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008255 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008256 {
8257 SequencedSubexpression Sequenced(*this);
8258 Visit(BO->getLHS());
8259 }
8260
8261 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008262 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008263 if (Result)
8264 Visit(BO->getRHS());
8265 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008266 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008267 }
Richard Smithc406cb72013-01-17 01:17:56 +00008268 }
8269
8270 // Only visit the condition, unless we can be sure which subexpression will
8271 // be chosen.
8272 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008273 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008274 {
8275 SequencedSubexpression Sequenced(*this);
8276 Visit(CO->getCond());
8277 }
Richard Smithc406cb72013-01-17 01:17:56 +00008278
8279 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008280 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008281 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008282 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008283 WorkList.push_back(CO->getTrueExpr());
8284 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008285 }
Richard Smithc406cb72013-01-17 01:17:56 +00008286 }
8287
Richard Smithe3dbfe02013-06-30 10:40:20 +00008288 void VisitCallExpr(CallExpr *CE) {
8289 // C++11 [intro.execution]p15:
8290 // When calling a function [...], every value computation and side effect
8291 // associated with any argument expression, or with the postfix expression
8292 // designating the called function, is sequenced before execution of every
8293 // expression or statement in the body of the function [and thus before
8294 // the value computation of its result].
8295 SequencedSubexpression Sequenced(*this);
8296 Base::VisitCallExpr(CE);
8297
8298 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8299 }
8300
Richard Smithc406cb72013-01-17 01:17:56 +00008301 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008302 // This is a call, so all subexpressions are sequenced before the result.
8303 SequencedSubexpression Sequenced(*this);
8304
Richard Smithc406cb72013-01-17 01:17:56 +00008305 if (!CCE->isListInitialization())
8306 return VisitExpr(CCE);
8307
8308 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008309 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008310 SequenceTree::Seq Parent = Region;
8311 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8312 E = CCE->arg_end();
8313 I != E; ++I) {
8314 Region = Tree.allocate(Parent);
8315 Elts.push_back(Region);
8316 Visit(*I);
8317 }
8318
8319 // Forget that the initializers are sequenced.
8320 Region = Parent;
8321 for (unsigned I = 0; I < Elts.size(); ++I)
8322 Tree.merge(Elts[I]);
8323 }
8324
8325 void VisitInitListExpr(InitListExpr *ILE) {
8326 if (!SemaRef.getLangOpts().CPlusPlus11)
8327 return VisitExpr(ILE);
8328
8329 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008330 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008331 SequenceTree::Seq Parent = Region;
8332 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8333 Expr *E = ILE->getInit(I);
8334 if (!E) continue;
8335 Region = Tree.allocate(Parent);
8336 Elts.push_back(Region);
8337 Visit(E);
8338 }
8339
8340 // Forget that the initializers are sequenced.
8341 Region = Parent;
8342 for (unsigned I = 0; I < Elts.size(); ++I)
8343 Tree.merge(Elts[I]);
8344 }
8345};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008346}
Richard Smithc406cb72013-01-17 01:17:56 +00008347
8348void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008349 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008350 WorkList.push_back(E);
8351 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008352 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008353 SequenceChecker(*this, Item, WorkList);
8354 }
Richard Smithc406cb72013-01-17 01:17:56 +00008355}
8356
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008357void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8358 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008359 CheckImplicitConversions(E, CheckLoc);
8360 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008361 if (!IsConstexpr && !E->isValueDependent())
8362 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008363}
8364
John McCall1f425642010-11-11 03:21:53 +00008365void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8366 FieldDecl *BitField,
8367 Expr *Init) {
8368 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8369}
8370
David Majnemer61a5bbf2015-04-07 22:08:51 +00008371static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8372 SourceLocation Loc) {
8373 if (!PType->isVariablyModifiedType())
8374 return;
8375 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8376 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8377 return;
8378 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008379 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8380 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8381 return;
8382 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008383 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8384 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8385 return;
8386 }
8387
8388 const ArrayType *AT = S.Context.getAsArrayType(PType);
8389 if (!AT)
8390 return;
8391
8392 if (AT->getSizeModifier() != ArrayType::Star) {
8393 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8394 return;
8395 }
8396
8397 S.Diag(Loc, diag::err_array_star_in_function_definition);
8398}
8399
Mike Stump0c2ec772010-01-21 03:59:47 +00008400/// CheckParmsForFunctionDef - Check that the parameters of the given
8401/// function are appropriate for the definition of a function. This
8402/// takes care of any checks that cannot be performed on the
8403/// declaration itself, e.g., that the types of each of the function
8404/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008405bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8406 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008407 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008408 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008409 for (; P != PEnd; ++P) {
8410 ParmVarDecl *Param = *P;
8411
Mike Stump0c2ec772010-01-21 03:59:47 +00008412 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8413 // function declarator that is part of a function definition of
8414 // that function shall not have incomplete type.
8415 //
8416 // This is also C++ [dcl.fct]p6.
8417 if (!Param->isInvalidDecl() &&
8418 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008419 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008420 Param->setInvalidDecl();
8421 HasInvalidParm = true;
8422 }
8423
8424 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8425 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008426 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008427 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008428 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008429 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008430 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008431
8432 // C99 6.7.5.3p12:
8433 // If the function declarator is not part of a definition of that
8434 // function, parameters may have incomplete type and may use the [*]
8435 // notation in their sequences of declarator specifiers to specify
8436 // variable length array types.
8437 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008438 // FIXME: This diagnostic should point the '[*]' if source-location
8439 // information is added for it.
8440 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008441
8442 // MSVC destroys objects passed by value in the callee. Therefore a
8443 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008444 // object's destructor. However, we don't perform any direct access check
8445 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008446 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8447 .getCXXABI()
8448 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008449 if (!Param->isInvalidDecl()) {
8450 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8451 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8452 if (!ClassDecl->isInvalidDecl() &&
8453 !ClassDecl->hasIrrelevantDestructor() &&
8454 !ClassDecl->isDependentContext()) {
8455 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8456 MarkFunctionReferenced(Param->getLocation(), Destructor);
8457 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8458 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008459 }
8460 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008461 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008462
8463 // Parameters with the pass_object_size attribute only need to be marked
8464 // constant at function definitions. Because we lack information about
8465 // whether we're on a declaration or definition when we're instantiating the
8466 // attribute, we need to check for constness here.
8467 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8468 if (!Param->getType().isConstQualified())
8469 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8470 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008471 }
8472
8473 return HasInvalidParm;
8474}
John McCall2b5c1b22010-08-12 21:44:57 +00008475
8476/// CheckCastAlign - Implements -Wcast-align, which warns when a
8477/// pointer cast increases the alignment requirements.
8478void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8479 // This is actually a lot of work to potentially be doing on every
8480 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008481 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008482 return;
8483
8484 // Ignore dependent types.
8485 if (T->isDependentType() || Op->getType()->isDependentType())
8486 return;
8487
8488 // Require that the destination be a pointer type.
8489 const PointerType *DestPtr = T->getAs<PointerType>();
8490 if (!DestPtr) return;
8491
8492 // If the destination has alignment 1, we're done.
8493 QualType DestPointee = DestPtr->getPointeeType();
8494 if (DestPointee->isIncompleteType()) return;
8495 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8496 if (DestAlign.isOne()) return;
8497
8498 // Require that the source be a pointer type.
8499 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8500 if (!SrcPtr) return;
8501 QualType SrcPointee = SrcPtr->getPointeeType();
8502
8503 // Whitelist casts from cv void*. We already implicitly
8504 // whitelisted casts to cv void*, since they have alignment 1.
8505 // Also whitelist casts involving incomplete types, which implicitly
8506 // includes 'void'.
8507 if (SrcPointee->isIncompleteType()) return;
8508
8509 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8510 if (SrcAlign >= DestAlign) return;
8511
8512 Diag(TRange.getBegin(), diag::warn_cast_align)
8513 << Op->getType() << T
8514 << static_cast<unsigned>(SrcAlign.getQuantity())
8515 << static_cast<unsigned>(DestAlign.getQuantity())
8516 << TRange << Op->getSourceRange();
8517}
8518
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008519static const Type* getElementType(const Expr *BaseExpr) {
8520 const Type* EltType = BaseExpr->getType().getTypePtr();
8521 if (EltType->isAnyPointerType())
8522 return EltType->getPointeeType().getTypePtr();
8523 else if (EltType->isArrayType())
8524 return EltType->getBaseElementTypeUnsafe();
8525 return EltType;
8526}
8527
Chandler Carruth28389f02011-08-05 09:10:50 +00008528/// \brief Check whether this array fits the idiom of a size-one tail padded
8529/// array member of a struct.
8530///
8531/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8532/// commonly used to emulate flexible arrays in C89 code.
8533static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8534 const NamedDecl *ND) {
8535 if (Size != 1 || !ND) return false;
8536
8537 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8538 if (!FD) return false;
8539
8540 // Don't consider sizes resulting from macro expansions or template argument
8541 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008542
8543 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008544 while (TInfo) {
8545 TypeLoc TL = TInfo->getTypeLoc();
8546 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008547 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8548 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008549 TInfo = TDL->getTypeSourceInfo();
8550 continue;
8551 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008552 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8553 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008554 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8555 return false;
8556 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008557 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008558 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008559
8560 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008561 if (!RD) return false;
8562 if (RD->isUnion()) return false;
8563 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8564 if (!CRD->isStandardLayout()) return false;
8565 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008566
Benjamin Kramer8c543672011-08-06 03:04:42 +00008567 // See if this is the last field decl in the record.
8568 const Decl *D = FD;
8569 while ((D = D->getNextDeclInContext()))
8570 if (isa<FieldDecl>(D))
8571 return false;
8572 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008573}
8574
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008575void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008576 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008577 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008578 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008579 if (IndexExpr->isValueDependent())
8580 return;
8581
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008582 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008583 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008584 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008585 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008586 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008587 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008588
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008589 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008590 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008591 return;
Richard Smith13f67182011-12-16 19:31:14 +00008592 if (IndexNegated)
8593 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008594
Craig Topperc3ec1492014-05-26 06:22:03 +00008595 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008596 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8597 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008598 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008599 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008600
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008601 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008602 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008603 if (!size.isStrictlyPositive())
8604 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008605
8606 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008607 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008608 // Make sure we're comparing apples to apples when comparing index to size
8609 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8610 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008611 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008612 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008613 if (ptrarith_typesize != array_typesize) {
8614 // There's a cast to a different size type involved
8615 uint64_t ratio = array_typesize / ptrarith_typesize;
8616 // TODO: Be smarter about handling cases where array_typesize is not a
8617 // multiple of ptrarith_typesize
8618 if (ptrarith_typesize * ratio == array_typesize)
8619 size *= llvm::APInt(size.getBitWidth(), ratio);
8620 }
8621 }
8622
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008623 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008624 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008625 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008626 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008627
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008628 // For array subscripting the index must be less than size, but for pointer
8629 // arithmetic also allow the index (offset) to be equal to size since
8630 // computing the next address after the end of the array is legal and
8631 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008632 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008633 return;
8634
8635 // Also don't warn for arrays of size 1 which are members of some
8636 // structure. These are often used to approximate flexible arrays in C89
8637 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008638 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008639 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008640
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008641 // Suppress the warning if the subscript expression (as identified by the
8642 // ']' location) and the index expression are both from macro expansions
8643 // within a system header.
8644 if (ASE) {
8645 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8646 ASE->getRBracketLoc());
8647 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8648 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8649 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008650 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008651 return;
8652 }
8653 }
8654
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008655 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008656 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008657 DiagID = diag::warn_array_index_exceeds_bounds;
8658
8659 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8660 PDiag(DiagID) << index.toString(10, true)
8661 << size.toString(10, true)
8662 << (unsigned)size.getLimitedValue(~0U)
8663 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008664 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008665 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008666 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008667 DiagID = diag::warn_ptr_arith_precedes_bounds;
8668 if (index.isNegative()) index = -index;
8669 }
8670
8671 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8672 PDiag(DiagID) << index.toString(10, true)
8673 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008674 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008675
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008676 if (!ND) {
8677 // Try harder to find a NamedDecl to point at in the note.
8678 while (const ArraySubscriptExpr *ASE =
8679 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8680 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8682 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8683 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8684 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8685 }
8686
Chandler Carruth1af88f12011-02-17 21:10:52 +00008687 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008688 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8689 PDiag(diag::note_array_index_out_of_bounds)
8690 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008691}
8692
Ted Kremenekdf26df72011-03-01 18:41:00 +00008693void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008694 int AllowOnePastEnd = 0;
8695 while (expr) {
8696 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008697 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008698 case Stmt::ArraySubscriptExprClass: {
8699 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008700 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008701 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008702 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008703 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008704 case Stmt::OMPArraySectionExprClass: {
8705 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8706 if (ASE->getLowerBound())
8707 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8708 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8709 return;
8710 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008711 case Stmt::UnaryOperatorClass: {
8712 // Only unwrap the * and & unary operators
8713 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8714 expr = UO->getSubExpr();
8715 switch (UO->getOpcode()) {
8716 case UO_AddrOf:
8717 AllowOnePastEnd++;
8718 break;
8719 case UO_Deref:
8720 AllowOnePastEnd--;
8721 break;
8722 default:
8723 return;
8724 }
8725 break;
8726 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008727 case Stmt::ConditionalOperatorClass: {
8728 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8729 if (const Expr *lhs = cond->getLHS())
8730 CheckArrayAccess(lhs);
8731 if (const Expr *rhs = cond->getRHS())
8732 CheckArrayAccess(rhs);
8733 return;
8734 }
8735 default:
8736 return;
8737 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008738 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008739}
John McCall31168b02011-06-15 23:02:42 +00008740
8741//===--- CHECK: Objective-C retain cycles ----------------------------------//
8742
8743namespace {
8744 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008745 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008746 VarDecl *Variable;
8747 SourceRange Range;
8748 SourceLocation Loc;
8749 bool Indirect;
8750
8751 void setLocsFrom(Expr *e) {
8752 Loc = e->getExprLoc();
8753 Range = e->getSourceRange();
8754 }
8755 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008756}
John McCall31168b02011-06-15 23:02:42 +00008757
8758/// Consider whether capturing the given variable can possibly lead to
8759/// a retain cycle.
8760static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008761 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008762 // lifetime. In MRR, it's captured strongly if the variable is
8763 // __block and has an appropriate type.
8764 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8765 return false;
8766
8767 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008768 if (ref)
8769 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008770 return true;
8771}
8772
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008773static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008774 while (true) {
8775 e = e->IgnoreParens();
8776 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8777 switch (cast->getCastKind()) {
8778 case CK_BitCast:
8779 case CK_LValueBitCast:
8780 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008781 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008782 e = cast->getSubExpr();
8783 continue;
8784
John McCall31168b02011-06-15 23:02:42 +00008785 default:
8786 return false;
8787 }
8788 }
8789
8790 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8791 ObjCIvarDecl *ivar = ref->getDecl();
8792 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8793 return false;
8794
8795 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008796 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008797 return false;
8798
8799 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8800 owner.Indirect = true;
8801 return true;
8802 }
8803
8804 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8805 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8806 if (!var) return false;
8807 return considerVariable(var, ref, owner);
8808 }
8809
John McCall31168b02011-06-15 23:02:42 +00008810 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8811 if (member->isArrow()) return false;
8812
8813 // Don't count this as an indirect ownership.
8814 e = member->getBase();
8815 continue;
8816 }
8817
John McCallfe96e0b2011-11-06 09:01:30 +00008818 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8819 // Only pay attention to pseudo-objects on property references.
8820 ObjCPropertyRefExpr *pre
8821 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8822 ->IgnoreParens());
8823 if (!pre) return false;
8824 if (pre->isImplicitProperty()) return false;
8825 ObjCPropertyDecl *property = pre->getExplicitProperty();
8826 if (!property->isRetaining() &&
8827 !(property->getPropertyIvarDecl() &&
8828 property->getPropertyIvarDecl()->getType()
8829 .getObjCLifetime() == Qualifiers::OCL_Strong))
8830 return false;
8831
8832 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008833 if (pre->isSuperReceiver()) {
8834 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8835 if (!owner.Variable)
8836 return false;
8837 owner.Loc = pre->getLocation();
8838 owner.Range = pre->getSourceRange();
8839 return true;
8840 }
John McCallfe96e0b2011-11-06 09:01:30 +00008841 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8842 ->getSourceExpr());
8843 continue;
8844 }
8845
John McCall31168b02011-06-15 23:02:42 +00008846 // Array ivars?
8847
8848 return false;
8849 }
8850}
8851
8852namespace {
8853 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8854 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8855 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008856 Context(Context), Variable(variable), Capturer(nullptr),
8857 VarWillBeReased(false) {}
8858 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008859 VarDecl *Variable;
8860 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008861 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008862
8863 void VisitDeclRefExpr(DeclRefExpr *ref) {
8864 if (ref->getDecl() == Variable && !Capturer)
8865 Capturer = ref;
8866 }
8867
John McCall31168b02011-06-15 23:02:42 +00008868 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8869 if (Capturer) return;
8870 Visit(ref->getBase());
8871 if (Capturer && ref->isFreeIvar())
8872 Capturer = ref;
8873 }
8874
8875 void VisitBlockExpr(BlockExpr *block) {
8876 // Look inside nested blocks
8877 if (block->getBlockDecl()->capturesVariable(Variable))
8878 Visit(block->getBlockDecl()->getBody());
8879 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008880
8881 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8882 if (Capturer) return;
8883 if (OVE->getSourceExpr())
8884 Visit(OVE->getSourceExpr());
8885 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008886 void VisitBinaryOperator(BinaryOperator *BinOp) {
8887 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8888 return;
8889 Expr *LHS = BinOp->getLHS();
8890 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8891 if (DRE->getDecl() != Variable)
8892 return;
8893 if (Expr *RHS = BinOp->getRHS()) {
8894 RHS = RHS->IgnoreParenCasts();
8895 llvm::APSInt Value;
8896 VarWillBeReased =
8897 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8898 }
8899 }
8900 }
John McCall31168b02011-06-15 23:02:42 +00008901 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008902}
John McCall31168b02011-06-15 23:02:42 +00008903
8904/// Check whether the given argument is a block which captures a
8905/// variable.
8906static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8907 assert(owner.Variable && owner.Loc.isValid());
8908
8909 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008910
8911 // Look through [^{...} copy] and Block_copy(^{...}).
8912 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8913 Selector Cmd = ME->getSelector();
8914 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8915 e = ME->getInstanceReceiver();
8916 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008917 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008918 e = e->IgnoreParenCasts();
8919 }
8920 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8921 if (CE->getNumArgs() == 1) {
8922 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008923 if (Fn) {
8924 const IdentifierInfo *FnI = Fn->getIdentifier();
8925 if (FnI && FnI->isStr("_Block_copy")) {
8926 e = CE->getArg(0)->IgnoreParenCasts();
8927 }
8928 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008929 }
8930 }
8931
John McCall31168b02011-06-15 23:02:42 +00008932 BlockExpr *block = dyn_cast<BlockExpr>(e);
8933 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008934 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008935
8936 FindCaptureVisitor visitor(S.Context, owner.Variable);
8937 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008938 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008939}
8940
8941static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8942 RetainCycleOwner &owner) {
8943 assert(capturer);
8944 assert(owner.Variable && owner.Loc.isValid());
8945
8946 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8947 << owner.Variable << capturer->getSourceRange();
8948 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8949 << owner.Indirect << owner.Range;
8950}
8951
8952/// Check for a keyword selector that starts with the word 'add' or
8953/// 'set'.
8954static bool isSetterLikeSelector(Selector sel) {
8955 if (sel.isUnarySelector()) return false;
8956
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008957 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008958 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008959 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008960 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008961 else if (str.startswith("add")) {
8962 // Specially whitelist 'addOperationWithBlock:'.
8963 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8964 return false;
8965 str = str.substr(3);
8966 }
John McCall31168b02011-06-15 23:02:42 +00008967 else
8968 return false;
8969
8970 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008971 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008972}
8973
Benjamin Kramer3a743452015-03-09 15:03:32 +00008974static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8975 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008976 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8977 Message->getReceiverInterface(),
8978 NSAPI::ClassId_NSMutableArray);
8979 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008980 return None;
8981 }
8982
8983 Selector Sel = Message->getSelector();
8984
8985 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8986 S.NSAPIObj->getNSArrayMethodKind(Sel);
8987 if (!MKOpt) {
8988 return None;
8989 }
8990
8991 NSAPI::NSArrayMethodKind MK = *MKOpt;
8992
8993 switch (MK) {
8994 case NSAPI::NSMutableArr_addObject:
8995 case NSAPI::NSMutableArr_insertObjectAtIndex:
8996 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8997 return 0;
8998 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8999 return 1;
9000
9001 default:
9002 return None;
9003 }
9004
9005 return None;
9006}
9007
9008static
9009Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9010 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009011 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9012 Message->getReceiverInterface(),
9013 NSAPI::ClassId_NSMutableDictionary);
9014 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009015 return None;
9016 }
9017
9018 Selector Sel = Message->getSelector();
9019
9020 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9021 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9022 if (!MKOpt) {
9023 return None;
9024 }
9025
9026 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9027
9028 switch (MK) {
9029 case NSAPI::NSMutableDict_setObjectForKey:
9030 case NSAPI::NSMutableDict_setValueForKey:
9031 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9032 return 0;
9033
9034 default:
9035 return None;
9036 }
9037
9038 return None;
9039}
9040
9041static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009042 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9043 Message->getReceiverInterface(),
9044 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009045
Alex Denisov5dfac812015-08-06 04:51:14 +00009046 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9047 Message->getReceiverInterface(),
9048 NSAPI::ClassId_NSMutableOrderedSet);
9049 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009050 return None;
9051 }
9052
9053 Selector Sel = Message->getSelector();
9054
9055 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9056 if (!MKOpt) {
9057 return None;
9058 }
9059
9060 NSAPI::NSSetMethodKind MK = *MKOpt;
9061
9062 switch (MK) {
9063 case NSAPI::NSMutableSet_addObject:
9064 case NSAPI::NSOrderedSet_setObjectAtIndex:
9065 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9066 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9067 return 0;
9068 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9069 return 1;
9070 }
9071
9072 return None;
9073}
9074
9075void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9076 if (!Message->isInstanceMessage()) {
9077 return;
9078 }
9079
9080 Optional<int> ArgOpt;
9081
9082 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9083 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9084 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9085 return;
9086 }
9087
9088 int ArgIndex = *ArgOpt;
9089
Alex Denisove1d882c2015-03-04 17:55:52 +00009090 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9091 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9092 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9093 }
9094
Alex Denisov5dfac812015-08-06 04:51:14 +00009095 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009096 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009097 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009098 Diag(Message->getSourceRange().getBegin(),
9099 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009100 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009101 }
9102 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009103 } else {
9104 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9105
9106 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9107 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9108 }
9109
9110 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9111 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9112 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9113 ValueDecl *Decl = ReceiverRE->getDecl();
9114 Diag(Message->getSourceRange().getBegin(),
9115 diag::warn_objc_circular_container)
9116 << Decl->getName() << Decl->getName();
9117 if (!ArgRE->isObjCSelfExpr()) {
9118 Diag(Decl->getLocation(),
9119 diag::note_objc_circular_container_declared_here)
9120 << Decl->getName();
9121 }
9122 }
9123 }
9124 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9125 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9126 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9127 ObjCIvarDecl *Decl = IvarRE->getDecl();
9128 Diag(Message->getSourceRange().getBegin(),
9129 diag::warn_objc_circular_container)
9130 << Decl->getName() << Decl->getName();
9131 Diag(Decl->getLocation(),
9132 diag::note_objc_circular_container_declared_here)
9133 << Decl->getName();
9134 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009135 }
9136 }
9137 }
9138
9139}
9140
John McCall31168b02011-06-15 23:02:42 +00009141/// Check a message send to see if it's likely to cause a retain cycle.
9142void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9143 // Only check instance methods whose selector looks like a setter.
9144 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9145 return;
9146
9147 // Try to find a variable that the receiver is strongly owned by.
9148 RetainCycleOwner owner;
9149 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009150 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009151 return;
9152 } else {
9153 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9154 owner.Variable = getCurMethodDecl()->getSelfDecl();
9155 owner.Loc = msg->getSuperLoc();
9156 owner.Range = msg->getSuperLoc();
9157 }
9158
9159 // Check whether the receiver is captured by any of the arguments.
9160 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9161 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9162 return diagnoseRetainCycle(*this, capturer, owner);
9163}
9164
9165/// Check a property assign to see if it's likely to cause a retain cycle.
9166void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9167 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009168 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009169 return;
9170
9171 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9172 diagnoseRetainCycle(*this, capturer, owner);
9173}
9174
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009175void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9176 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009177 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009178 return;
9179
9180 // Because we don't have an expression for the variable, we have to set the
9181 // location explicitly here.
9182 Owner.Loc = Var->getLocation();
9183 Owner.Range = Var->getSourceRange();
9184
9185 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9186 diagnoseRetainCycle(*this, Capturer, Owner);
9187}
9188
Ted Kremenek9304da92012-12-21 08:04:28 +00009189static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9190 Expr *RHS, bool isProperty) {
9191 // Check if RHS is an Objective-C object literal, which also can get
9192 // immediately zapped in a weak reference. Note that we explicitly
9193 // allow ObjCStringLiterals, since those are designed to never really die.
9194 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009195
Ted Kremenek64873352012-12-21 22:46:35 +00009196 // This enum needs to match with the 'select' in
9197 // warn_objc_arc_literal_assign (off-by-1).
9198 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9199 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9200 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009201
9202 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009203 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009204 << (isProperty ? 0 : 1)
9205 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009206
9207 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009208}
9209
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009210static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9211 Qualifiers::ObjCLifetime LT,
9212 Expr *RHS, bool isProperty) {
9213 // Strip off any implicit cast added to get to the one ARC-specific.
9214 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9215 if (cast->getCastKind() == CK_ARCConsumeObject) {
9216 S.Diag(Loc, diag::warn_arc_retained_assign)
9217 << (LT == Qualifiers::OCL_ExplicitNone)
9218 << (isProperty ? 0 : 1)
9219 << RHS->getSourceRange();
9220 return true;
9221 }
9222 RHS = cast->getSubExpr();
9223 }
9224
9225 if (LT == Qualifiers::OCL_Weak &&
9226 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9227 return true;
9228
9229 return false;
9230}
9231
Ted Kremenekb36234d2012-12-21 08:04:20 +00009232bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9233 QualType LHS, Expr *RHS) {
9234 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9235
9236 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9237 return false;
9238
9239 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9240 return true;
9241
9242 return false;
9243}
9244
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009245void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9246 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009247 QualType LHSType;
9248 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009249 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009250 ObjCPropertyRefExpr *PRE
9251 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9252 if (PRE && !PRE->isImplicitProperty()) {
9253 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9254 if (PD)
9255 LHSType = PD->getType();
9256 }
9257
9258 if (LHSType.isNull())
9259 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009260
9261 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9262
9263 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009264 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009265 getCurFunction()->markSafeWeakUse(LHS);
9266 }
9267
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009268 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9269 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009270
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009271 // FIXME. Check for other life times.
9272 if (LT != Qualifiers::OCL_None)
9273 return;
9274
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009275 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009276 if (PRE->isImplicitProperty())
9277 return;
9278 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9279 if (!PD)
9280 return;
9281
Bill Wendling44426052012-12-20 19:22:21 +00009282 unsigned Attributes = PD->getPropertyAttributes();
9283 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009284 // when 'assign' attribute was not explicitly specified
9285 // by user, ignore it and rely on property type itself
9286 // for lifetime info.
9287 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9288 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9289 LHSType->isObjCRetainableType())
9290 return;
9291
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009292 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009293 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009294 Diag(Loc, diag::warn_arc_retained_property_assign)
9295 << RHS->getSourceRange();
9296 return;
9297 }
9298 RHS = cast->getSubExpr();
9299 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009300 }
Bill Wendling44426052012-12-20 19:22:21 +00009301 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009302 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9303 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009304 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009305 }
9306}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009307
9308//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9309
9310namespace {
9311bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9312 SourceLocation StmtLoc,
9313 const NullStmt *Body) {
9314 // Do not warn if the body is a macro that expands to nothing, e.g:
9315 //
9316 // #define CALL(x)
9317 // if (condition)
9318 // CALL(0);
9319 //
9320 if (Body->hasLeadingEmptyMacro())
9321 return false;
9322
9323 // Get line numbers of statement and body.
9324 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009325 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009326 &StmtLineInvalid);
9327 if (StmtLineInvalid)
9328 return false;
9329
9330 bool BodyLineInvalid;
9331 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9332 &BodyLineInvalid);
9333 if (BodyLineInvalid)
9334 return false;
9335
9336 // Warn if null statement and body are on the same line.
9337 if (StmtLine != BodyLine)
9338 return false;
9339
9340 return true;
9341}
9342} // Unnamed namespace
9343
9344void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9345 const Stmt *Body,
9346 unsigned DiagID) {
9347 // Since this is a syntactic check, don't emit diagnostic for template
9348 // instantiations, this just adds noise.
9349 if (CurrentInstantiationScope)
9350 return;
9351
9352 // The body should be a null statement.
9353 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9354 if (!NBody)
9355 return;
9356
9357 // Do the usual checks.
9358 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9359 return;
9360
9361 Diag(NBody->getSemiLoc(), DiagID);
9362 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9363}
9364
9365void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9366 const Stmt *PossibleBody) {
9367 assert(!CurrentInstantiationScope); // Ensured by caller
9368
9369 SourceLocation StmtLoc;
9370 const Stmt *Body;
9371 unsigned DiagID;
9372 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9373 StmtLoc = FS->getRParenLoc();
9374 Body = FS->getBody();
9375 DiagID = diag::warn_empty_for_body;
9376 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9377 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9378 Body = WS->getBody();
9379 DiagID = diag::warn_empty_while_body;
9380 } else
9381 return; // Neither `for' nor `while'.
9382
9383 // The body should be a null statement.
9384 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9385 if (!NBody)
9386 return;
9387
9388 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009389 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009390 return;
9391
9392 // Do the usual checks.
9393 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9394 return;
9395
9396 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9397 // noise level low, emit diagnostics only if for/while is followed by a
9398 // CompoundStmt, e.g.:
9399 // for (int i = 0; i < n; i++);
9400 // {
9401 // a(i);
9402 // }
9403 // or if for/while is followed by a statement with more indentation
9404 // than for/while itself:
9405 // for (int i = 0; i < n; i++);
9406 // a(i);
9407 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9408 if (!ProbableTypo) {
9409 bool BodyColInvalid;
9410 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9411 PossibleBody->getLocStart(),
9412 &BodyColInvalid);
9413 if (BodyColInvalid)
9414 return;
9415
9416 bool StmtColInvalid;
9417 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9418 S->getLocStart(),
9419 &StmtColInvalid);
9420 if (StmtColInvalid)
9421 return;
9422
9423 if (BodyCol > StmtCol)
9424 ProbableTypo = true;
9425 }
9426
9427 if (ProbableTypo) {
9428 Diag(NBody->getSemiLoc(), DiagID);
9429 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9430 }
9431}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009432
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009433//===--- CHECK: Warn on self move with std::move. -------------------------===//
9434
9435/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9436void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9437 SourceLocation OpLoc) {
9438
9439 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9440 return;
9441
9442 if (!ActiveTemplateInstantiations.empty())
9443 return;
9444
9445 // Strip parens and casts away.
9446 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9447 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9448
9449 // Check for a call expression
9450 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9451 if (!CE || CE->getNumArgs() != 1)
9452 return;
9453
9454 // Check for a call to std::move
9455 const FunctionDecl *FD = CE->getDirectCallee();
9456 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9457 !FD->getIdentifier()->isStr("move"))
9458 return;
9459
9460 // Get argument from std::move
9461 RHSExpr = CE->getArg(0);
9462
9463 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9464 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9465
9466 // Two DeclRefExpr's, check that the decls are the same.
9467 if (LHSDeclRef && RHSDeclRef) {
9468 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9469 return;
9470 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9471 RHSDeclRef->getDecl()->getCanonicalDecl())
9472 return;
9473
9474 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9475 << LHSExpr->getSourceRange()
9476 << RHSExpr->getSourceRange();
9477 return;
9478 }
9479
9480 // Member variables require a different approach to check for self moves.
9481 // MemberExpr's are the same if every nested MemberExpr refers to the same
9482 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9483 // the base Expr's are CXXThisExpr's.
9484 const Expr *LHSBase = LHSExpr;
9485 const Expr *RHSBase = RHSExpr;
9486 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9487 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9488 if (!LHSME || !RHSME)
9489 return;
9490
9491 while (LHSME && RHSME) {
9492 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9493 RHSME->getMemberDecl()->getCanonicalDecl())
9494 return;
9495
9496 LHSBase = LHSME->getBase();
9497 RHSBase = RHSME->getBase();
9498 LHSME = dyn_cast<MemberExpr>(LHSBase);
9499 RHSME = dyn_cast<MemberExpr>(RHSBase);
9500 }
9501
9502 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9503 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9504 if (LHSDeclRef && RHSDeclRef) {
9505 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9506 return;
9507 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9508 RHSDeclRef->getDecl()->getCanonicalDecl())
9509 return;
9510
9511 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9512 << LHSExpr->getSourceRange()
9513 << RHSExpr->getSourceRange();
9514 return;
9515 }
9516
9517 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9518 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9519 << LHSExpr->getSourceRange()
9520 << RHSExpr->getSourceRange();
9521}
9522
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009523//===--- Layout compatibility ----------------------------------------------//
9524
9525namespace {
9526
9527bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9528
9529/// \brief Check if two enumeration types are layout-compatible.
9530bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9531 // C++11 [dcl.enum] p8:
9532 // Two enumeration types are layout-compatible if they have the same
9533 // underlying type.
9534 return ED1->isComplete() && ED2->isComplete() &&
9535 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9536}
9537
9538/// \brief Check if two fields are layout-compatible.
9539bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9540 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9541 return false;
9542
9543 if (Field1->isBitField() != Field2->isBitField())
9544 return false;
9545
9546 if (Field1->isBitField()) {
9547 // Make sure that the bit-fields are the same length.
9548 unsigned Bits1 = Field1->getBitWidthValue(C);
9549 unsigned Bits2 = Field2->getBitWidthValue(C);
9550
9551 if (Bits1 != Bits2)
9552 return false;
9553 }
9554
9555 return true;
9556}
9557
9558/// \brief Check if two standard-layout structs are layout-compatible.
9559/// (C++11 [class.mem] p17)
9560bool isLayoutCompatibleStruct(ASTContext &C,
9561 RecordDecl *RD1,
9562 RecordDecl *RD2) {
9563 // If both records are C++ classes, check that base classes match.
9564 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9565 // If one of records is a CXXRecordDecl we are in C++ mode,
9566 // thus the other one is a CXXRecordDecl, too.
9567 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9568 // Check number of base classes.
9569 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9570 return false;
9571
9572 // Check the base classes.
9573 for (CXXRecordDecl::base_class_const_iterator
9574 Base1 = D1CXX->bases_begin(),
9575 BaseEnd1 = D1CXX->bases_end(),
9576 Base2 = D2CXX->bases_begin();
9577 Base1 != BaseEnd1;
9578 ++Base1, ++Base2) {
9579 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9580 return false;
9581 }
9582 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9583 // If only RD2 is a C++ class, it should have zero base classes.
9584 if (D2CXX->getNumBases() > 0)
9585 return false;
9586 }
9587
9588 // Check the fields.
9589 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9590 Field2End = RD2->field_end(),
9591 Field1 = RD1->field_begin(),
9592 Field1End = RD1->field_end();
9593 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9594 if (!isLayoutCompatible(C, *Field1, *Field2))
9595 return false;
9596 }
9597 if (Field1 != Field1End || Field2 != Field2End)
9598 return false;
9599
9600 return true;
9601}
9602
9603/// \brief Check if two standard-layout unions are layout-compatible.
9604/// (C++11 [class.mem] p18)
9605bool isLayoutCompatibleUnion(ASTContext &C,
9606 RecordDecl *RD1,
9607 RecordDecl *RD2) {
9608 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009609 for (auto *Field2 : RD2->fields())
9610 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009611
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009612 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009613 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9614 I = UnmatchedFields.begin(),
9615 E = UnmatchedFields.end();
9616
9617 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009618 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009619 bool Result = UnmatchedFields.erase(*I);
9620 (void) Result;
9621 assert(Result);
9622 break;
9623 }
9624 }
9625 if (I == E)
9626 return false;
9627 }
9628
9629 return UnmatchedFields.empty();
9630}
9631
9632bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9633 if (RD1->isUnion() != RD2->isUnion())
9634 return false;
9635
9636 if (RD1->isUnion())
9637 return isLayoutCompatibleUnion(C, RD1, RD2);
9638 else
9639 return isLayoutCompatibleStruct(C, RD1, RD2);
9640}
9641
9642/// \brief Check if two types are layout-compatible in C++11 sense.
9643bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9644 if (T1.isNull() || T2.isNull())
9645 return false;
9646
9647 // C++11 [basic.types] p11:
9648 // If two types T1 and T2 are the same type, then T1 and T2 are
9649 // layout-compatible types.
9650 if (C.hasSameType(T1, T2))
9651 return true;
9652
9653 T1 = T1.getCanonicalType().getUnqualifiedType();
9654 T2 = T2.getCanonicalType().getUnqualifiedType();
9655
9656 const Type::TypeClass TC1 = T1->getTypeClass();
9657 const Type::TypeClass TC2 = T2->getTypeClass();
9658
9659 if (TC1 != TC2)
9660 return false;
9661
9662 if (TC1 == Type::Enum) {
9663 return isLayoutCompatible(C,
9664 cast<EnumType>(T1)->getDecl(),
9665 cast<EnumType>(T2)->getDecl());
9666 } else if (TC1 == Type::Record) {
9667 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9668 return false;
9669
9670 return isLayoutCompatible(C,
9671 cast<RecordType>(T1)->getDecl(),
9672 cast<RecordType>(T2)->getDecl());
9673 }
9674
9675 return false;
9676}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009677}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009678
9679//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9680
9681namespace {
9682/// \brief Given a type tag expression find the type tag itself.
9683///
9684/// \param TypeExpr Type tag expression, as it appears in user's code.
9685///
9686/// \param VD Declaration of an identifier that appears in a type tag.
9687///
9688/// \param MagicValue Type tag magic value.
9689bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9690 const ValueDecl **VD, uint64_t *MagicValue) {
9691 while(true) {
9692 if (!TypeExpr)
9693 return false;
9694
9695 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9696
9697 switch (TypeExpr->getStmtClass()) {
9698 case Stmt::UnaryOperatorClass: {
9699 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9700 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9701 TypeExpr = UO->getSubExpr();
9702 continue;
9703 }
9704 return false;
9705 }
9706
9707 case Stmt::DeclRefExprClass: {
9708 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9709 *VD = DRE->getDecl();
9710 return true;
9711 }
9712
9713 case Stmt::IntegerLiteralClass: {
9714 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9715 llvm::APInt MagicValueAPInt = IL->getValue();
9716 if (MagicValueAPInt.getActiveBits() <= 64) {
9717 *MagicValue = MagicValueAPInt.getZExtValue();
9718 return true;
9719 } else
9720 return false;
9721 }
9722
9723 case Stmt::BinaryConditionalOperatorClass:
9724 case Stmt::ConditionalOperatorClass: {
9725 const AbstractConditionalOperator *ACO =
9726 cast<AbstractConditionalOperator>(TypeExpr);
9727 bool Result;
9728 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9729 if (Result)
9730 TypeExpr = ACO->getTrueExpr();
9731 else
9732 TypeExpr = ACO->getFalseExpr();
9733 continue;
9734 }
9735 return false;
9736 }
9737
9738 case Stmt::BinaryOperatorClass: {
9739 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9740 if (BO->getOpcode() == BO_Comma) {
9741 TypeExpr = BO->getRHS();
9742 continue;
9743 }
9744 return false;
9745 }
9746
9747 default:
9748 return false;
9749 }
9750 }
9751}
9752
9753/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9754///
9755/// \param TypeExpr Expression that specifies a type tag.
9756///
9757/// \param MagicValues Registered magic values.
9758///
9759/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9760/// kind.
9761///
9762/// \param TypeInfo Information about the corresponding C type.
9763///
9764/// \returns true if the corresponding C type was found.
9765bool GetMatchingCType(
9766 const IdentifierInfo *ArgumentKind,
9767 const Expr *TypeExpr, const ASTContext &Ctx,
9768 const llvm::DenseMap<Sema::TypeTagMagicValue,
9769 Sema::TypeTagData> *MagicValues,
9770 bool &FoundWrongKind,
9771 Sema::TypeTagData &TypeInfo) {
9772 FoundWrongKind = false;
9773
9774 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009775 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009776
9777 uint64_t MagicValue;
9778
9779 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9780 return false;
9781
9782 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009783 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009784 if (I->getArgumentKind() != ArgumentKind) {
9785 FoundWrongKind = true;
9786 return false;
9787 }
9788 TypeInfo.Type = I->getMatchingCType();
9789 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9790 TypeInfo.MustBeNull = I->getMustBeNull();
9791 return true;
9792 }
9793 return false;
9794 }
9795
9796 if (!MagicValues)
9797 return false;
9798
9799 llvm::DenseMap<Sema::TypeTagMagicValue,
9800 Sema::TypeTagData>::const_iterator I =
9801 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9802 if (I == MagicValues->end())
9803 return false;
9804
9805 TypeInfo = I->second;
9806 return true;
9807}
9808} // unnamed namespace
9809
9810void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9811 uint64_t MagicValue, QualType Type,
9812 bool LayoutCompatible,
9813 bool MustBeNull) {
9814 if (!TypeTagForDatatypeMagicValues)
9815 TypeTagForDatatypeMagicValues.reset(
9816 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9817
9818 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9819 (*TypeTagForDatatypeMagicValues)[Magic] =
9820 TypeTagData(Type, LayoutCompatible, MustBeNull);
9821}
9822
9823namespace {
9824bool IsSameCharType(QualType T1, QualType T2) {
9825 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9826 if (!BT1)
9827 return false;
9828
9829 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9830 if (!BT2)
9831 return false;
9832
9833 BuiltinType::Kind T1Kind = BT1->getKind();
9834 BuiltinType::Kind T2Kind = BT2->getKind();
9835
9836 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9837 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9838 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9839 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9840}
9841} // unnamed namespace
9842
9843void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9844 const Expr * const *ExprArgs) {
9845 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9846 bool IsPointerAttr = Attr->getIsPointer();
9847
9848 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9849 bool FoundWrongKind;
9850 TypeTagData TypeInfo;
9851 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9852 TypeTagForDatatypeMagicValues.get(),
9853 FoundWrongKind, TypeInfo)) {
9854 if (FoundWrongKind)
9855 Diag(TypeTagExpr->getExprLoc(),
9856 diag::warn_type_tag_for_datatype_wrong_kind)
9857 << TypeTagExpr->getSourceRange();
9858 return;
9859 }
9860
9861 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9862 if (IsPointerAttr) {
9863 // Skip implicit cast of pointer to `void *' (as a function argument).
9864 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009865 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009866 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009867 ArgumentExpr = ICE->getSubExpr();
9868 }
9869 QualType ArgumentType = ArgumentExpr->getType();
9870
9871 // Passing a `void*' pointer shouldn't trigger a warning.
9872 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9873 return;
9874
9875 if (TypeInfo.MustBeNull) {
9876 // Type tag with matching void type requires a null pointer.
9877 if (!ArgumentExpr->isNullPointerConstant(Context,
9878 Expr::NPC_ValueDependentIsNotNull)) {
9879 Diag(ArgumentExpr->getExprLoc(),
9880 diag::warn_type_safety_null_pointer_required)
9881 << ArgumentKind->getName()
9882 << ArgumentExpr->getSourceRange()
9883 << TypeTagExpr->getSourceRange();
9884 }
9885 return;
9886 }
9887
9888 QualType RequiredType = TypeInfo.Type;
9889 if (IsPointerAttr)
9890 RequiredType = Context.getPointerType(RequiredType);
9891
9892 bool mismatch = false;
9893 if (!TypeInfo.LayoutCompatible) {
9894 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9895
9896 // C++11 [basic.fundamental] p1:
9897 // Plain char, signed char, and unsigned char are three distinct types.
9898 //
9899 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9900 // char' depending on the current char signedness mode.
9901 if (mismatch)
9902 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9903 RequiredType->getPointeeType())) ||
9904 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9905 mismatch = false;
9906 } else
9907 if (IsPointerAttr)
9908 mismatch = !isLayoutCompatible(Context,
9909 ArgumentType->getPointeeType(),
9910 RequiredType->getPointeeType());
9911 else
9912 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9913
9914 if (mismatch)
9915 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009916 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009917 << TypeInfo.LayoutCompatible << RequiredType
9918 << ArgumentExpr->getSourceRange()
9919 << TypeTagExpr->getSourceRange();
9920}