blob: 8d9a1b23bb47d757e4027063bc9b4cfb63c573f4 [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
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000115static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
116 CallExpr *TheCall, unsigned SizeIdx,
117 unsigned DstSizeIdx) {
118 if (TheCall->getNumArgs() <= SizeIdx ||
119 TheCall->getNumArgs() <= DstSizeIdx)
120 return;
121
122 const Expr *SizeArg = TheCall->getArg(SizeIdx);
123 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
124
125 llvm::APSInt Size, DstSize;
126
127 // find out if both sizes are known at compile time
128 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
129 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
130 return;
131
132 if (Size.ule(DstSize))
133 return;
134
135 // confirmed overflow so generate the diagnostic.
136 IdentifierInfo *FnName = FDecl->getIdentifier();
137 SourceLocation SL = TheCall->getLocStart();
138 SourceRange SR = TheCall->getSourceRange();
139
140 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
141}
142
Peter Collingbournef7706832014-12-12 23:41:25 +0000143static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
144 if (checkArgCount(S, BuiltinCall, 2))
145 return true;
146
147 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
148 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
149 Expr *Call = BuiltinCall->getArg(0);
150 Expr *Chain = BuiltinCall->getArg(1);
151
152 if (Call->getStmtClass() != Stmt::CallExprClass) {
153 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
154 << Call->getSourceRange();
155 return true;
156 }
157
158 auto CE = cast<CallExpr>(Call);
159 if (CE->getCallee()->getType()->isBlockPointerType()) {
160 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
161 << Call->getSourceRange();
162 return true;
163 }
164
165 const Decl *TargetDecl = CE->getCalleeDecl();
166 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
167 if (FD->getBuiltinID()) {
168 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
169 << Call->getSourceRange();
170 return true;
171 }
172
173 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
174 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
175 << Call->getSourceRange();
176 return true;
177 }
178
179 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
180 if (ChainResult.isInvalid())
181 return true;
182 if (!ChainResult.get()->getType()->isPointerType()) {
183 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
184 << Chain->getSourceRange();
185 return true;
186 }
187
David Majnemerced8bdf2015-02-25 17:36:15 +0000188 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000189 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
190 QualType BuiltinTy = S.Context.getFunctionType(
191 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
192 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
193
194 Builtin =
195 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
196
197 BuiltinCall->setType(CE->getType());
198 BuiltinCall->setValueKind(CE->getValueKind());
199 BuiltinCall->setObjectKind(CE->getObjectKind());
200 BuiltinCall->setCallee(Builtin);
201 BuiltinCall->setArg(1, ChainResult.get());
202
203 return false;
204}
205
Reid Kleckner1d59f992015-01-22 01:36:17 +0000206static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
207 Scope::ScopeFlags NeededScopeFlags,
208 unsigned DiagID) {
209 // Scopes aren't available during instantiation. Fortunately, builtin
210 // functions cannot be template args so they cannot be formed through template
211 // instantiation. Therefore checking once during the parse is sufficient.
212 if (!SemaRef.ActiveTemplateInstantiations.empty())
213 return false;
214
215 Scope *S = SemaRef.getCurScope();
216 while (S && !S->isSEHExceptScope())
217 S = S->getParent();
218 if (!S || !(S->getFlags() & NeededScopeFlags)) {
219 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
220 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
221 << DRE->getDecl()->getIdentifier();
222 return true;
223 }
224
225 return false;
226}
227
John McCalldadc5752010-08-24 06:29:42 +0000228ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000229Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
230 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000231 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000232
Chris Lattner3be167f2010-10-01 23:23:24 +0000233 // Find out if any arguments are required to be integer constant expressions.
234 unsigned ICEArguments = 0;
235 ASTContext::GetBuiltinTypeError Error;
236 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
237 if (Error != ASTContext::GE_None)
238 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
239
240 // If any arguments are required to be ICE's, check and diagnose.
241 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
242 // Skip arguments not required to be ICE's.
243 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
244
245 llvm::APSInt Result;
246 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 return true;
248 ICEArguments &= ~(1 << ArgNo);
249 }
250
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000251 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000252 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000253 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000254 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000255 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000256 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000257 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000258 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000259 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000260 if (SemaBuiltinVAStart(TheCall))
261 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000262 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000263 case Builtin::BI__va_start: {
264 switch (Context.getTargetInfo().getTriple().getArch()) {
265 case llvm::Triple::arm:
266 case llvm::Triple::thumb:
267 if (SemaBuiltinVAStartARM(TheCall))
268 return ExprError();
269 break;
270 default:
271 if (SemaBuiltinVAStart(TheCall))
272 return ExprError();
273 break;
274 }
275 break;
276 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000277 case Builtin::BI__builtin_isgreater:
278 case Builtin::BI__builtin_isgreaterequal:
279 case Builtin::BI__builtin_isless:
280 case Builtin::BI__builtin_islessequal:
281 case Builtin::BI__builtin_islessgreater:
282 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000283 if (SemaBuiltinUnorderedCompare(TheCall))
284 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000285 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000286 case Builtin::BI__builtin_fpclassify:
287 if (SemaBuiltinFPClassification(TheCall, 6))
288 return ExprError();
289 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000290 case Builtin::BI__builtin_isfinite:
291 case Builtin::BI__builtin_isinf:
292 case Builtin::BI__builtin_isinf_sign:
293 case Builtin::BI__builtin_isnan:
294 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000295 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000296 return ExprError();
297 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000298 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000299 return SemaBuiltinShuffleVector(TheCall);
300 // TheCall will be freed by the smart pointer here, but that's fine, since
301 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000302 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000303 if (SemaBuiltinPrefetch(TheCall))
304 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000305 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000306 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000307 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000308 if (SemaBuiltinAssume(TheCall))
309 return ExprError();
310 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000311 case Builtin::BI__builtin_assume_aligned:
312 if (SemaBuiltinAssumeAligned(TheCall))
313 return ExprError();
314 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000315 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000316 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000317 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000318 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000319 case Builtin::BI__builtin_longjmp:
320 if (SemaBuiltinLongjmp(TheCall))
321 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000322 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000323 case Builtin::BI__builtin_setjmp:
324 if (SemaBuiltinSetjmp(TheCall))
325 return ExprError();
326 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000327 case Builtin::BI_setjmp:
328 case Builtin::BI_setjmpex:
329 if (checkArgCount(*this, TheCall, 1))
330 return true;
331 break;
John McCallbebede42011-02-26 05:39:39 +0000332
333 case Builtin::BI__builtin_classify_type:
334 if (checkArgCount(*this, TheCall, 1)) return true;
335 TheCall->setType(Context.IntTy);
336 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000337 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000338 if (checkArgCount(*this, TheCall, 1)) return true;
339 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000340 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000341 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000342 case Builtin::BI__sync_fetch_and_add_1:
343 case Builtin::BI__sync_fetch_and_add_2:
344 case Builtin::BI__sync_fetch_and_add_4:
345 case Builtin::BI__sync_fetch_and_add_8:
346 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000347 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000348 case Builtin::BI__sync_fetch_and_sub_1:
349 case Builtin::BI__sync_fetch_and_sub_2:
350 case Builtin::BI__sync_fetch_and_sub_4:
351 case Builtin::BI__sync_fetch_and_sub_8:
352 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000353 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000354 case Builtin::BI__sync_fetch_and_or_1:
355 case Builtin::BI__sync_fetch_and_or_2:
356 case Builtin::BI__sync_fetch_and_or_4:
357 case Builtin::BI__sync_fetch_and_or_8:
358 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000359 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000360 case Builtin::BI__sync_fetch_and_and_1:
361 case Builtin::BI__sync_fetch_and_and_2:
362 case Builtin::BI__sync_fetch_and_and_4:
363 case Builtin::BI__sync_fetch_and_and_8:
364 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000365 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000366 case Builtin::BI__sync_fetch_and_xor_1:
367 case Builtin::BI__sync_fetch_and_xor_2:
368 case Builtin::BI__sync_fetch_and_xor_4:
369 case Builtin::BI__sync_fetch_and_xor_8:
370 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000371 case Builtin::BI__sync_fetch_and_nand:
372 case Builtin::BI__sync_fetch_and_nand_1:
373 case Builtin::BI__sync_fetch_and_nand_2:
374 case Builtin::BI__sync_fetch_and_nand_4:
375 case Builtin::BI__sync_fetch_and_nand_8:
376 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000377 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000378 case Builtin::BI__sync_add_and_fetch_1:
379 case Builtin::BI__sync_add_and_fetch_2:
380 case Builtin::BI__sync_add_and_fetch_4:
381 case Builtin::BI__sync_add_and_fetch_8:
382 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000383 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000384 case Builtin::BI__sync_sub_and_fetch_1:
385 case Builtin::BI__sync_sub_and_fetch_2:
386 case Builtin::BI__sync_sub_and_fetch_4:
387 case Builtin::BI__sync_sub_and_fetch_8:
388 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000389 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000390 case Builtin::BI__sync_and_and_fetch_1:
391 case Builtin::BI__sync_and_and_fetch_2:
392 case Builtin::BI__sync_and_and_fetch_4:
393 case Builtin::BI__sync_and_and_fetch_8:
394 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000395 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000396 case Builtin::BI__sync_or_and_fetch_1:
397 case Builtin::BI__sync_or_and_fetch_2:
398 case Builtin::BI__sync_or_and_fetch_4:
399 case Builtin::BI__sync_or_and_fetch_8:
400 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000401 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000402 case Builtin::BI__sync_xor_and_fetch_1:
403 case Builtin::BI__sync_xor_and_fetch_2:
404 case Builtin::BI__sync_xor_and_fetch_4:
405 case Builtin::BI__sync_xor_and_fetch_8:
406 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000407 case Builtin::BI__sync_nand_and_fetch:
408 case Builtin::BI__sync_nand_and_fetch_1:
409 case Builtin::BI__sync_nand_and_fetch_2:
410 case Builtin::BI__sync_nand_and_fetch_4:
411 case Builtin::BI__sync_nand_and_fetch_8:
412 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000413 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000414 case Builtin::BI__sync_val_compare_and_swap_1:
415 case Builtin::BI__sync_val_compare_and_swap_2:
416 case Builtin::BI__sync_val_compare_and_swap_4:
417 case Builtin::BI__sync_val_compare_and_swap_8:
418 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000419 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000420 case Builtin::BI__sync_bool_compare_and_swap_1:
421 case Builtin::BI__sync_bool_compare_and_swap_2:
422 case Builtin::BI__sync_bool_compare_and_swap_4:
423 case Builtin::BI__sync_bool_compare_and_swap_8:
424 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000425 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000426 case Builtin::BI__sync_lock_test_and_set_1:
427 case Builtin::BI__sync_lock_test_and_set_2:
428 case Builtin::BI__sync_lock_test_and_set_4:
429 case Builtin::BI__sync_lock_test_and_set_8:
430 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000431 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000432 case Builtin::BI__sync_lock_release_1:
433 case Builtin::BI__sync_lock_release_2:
434 case Builtin::BI__sync_lock_release_4:
435 case Builtin::BI__sync_lock_release_8:
436 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000437 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000438 case Builtin::BI__sync_swap_1:
439 case Builtin::BI__sync_swap_2:
440 case Builtin::BI__sync_swap_4:
441 case Builtin::BI__sync_swap_8:
442 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000443 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000444 case Builtin::BI__builtin_nontemporal_load:
445 case Builtin::BI__builtin_nontemporal_store:
446 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000447#define BUILTIN(ID, TYPE, ATTRS)
448#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
449 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000450 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000451#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000452 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000453 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000454 return ExprError();
455 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000456 case Builtin::BI__builtin_addressof:
457 if (SemaBuiltinAddressof(*this, TheCall))
458 return ExprError();
459 break;
Richard Smith760520b2014-06-03 23:27:44 +0000460 case Builtin::BI__builtin_operator_new:
461 case Builtin::BI__builtin_operator_delete:
462 if (!getLangOpts().CPlusPlus) {
463 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
464 << (BuiltinID == Builtin::BI__builtin_operator_new
465 ? "__builtin_operator_new"
466 : "__builtin_operator_delete")
467 << "C++";
468 return ExprError();
469 }
470 // CodeGen assumes it can find the global new and delete to call,
471 // so ensure that they are declared.
472 DeclareGlobalNewDelete();
473 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000474
475 // check secure string manipulation functions where overflows
476 // are detectable at compile time
477 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000478 case Builtin::BI__builtin___memmove_chk:
479 case Builtin::BI__builtin___memset_chk:
480 case Builtin::BI__builtin___strlcat_chk:
481 case Builtin::BI__builtin___strlcpy_chk:
482 case Builtin::BI__builtin___strncat_chk:
483 case Builtin::BI__builtin___strncpy_chk:
484 case Builtin::BI__builtin___stpncpy_chk:
485 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
486 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000487 case Builtin::BI__builtin___memccpy_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
489 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000490 case Builtin::BI__builtin___snprintf_chk:
491 case Builtin::BI__builtin___vsnprintf_chk:
492 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
493 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000494
495 case Builtin::BI__builtin_call_with_static_chain:
496 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
497 return ExprError();
498 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000499
500 case Builtin::BI__exception_code:
501 case Builtin::BI_exception_code: {
502 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
503 diag::err_seh___except_block))
504 return ExprError();
505 break;
506 }
507 case Builtin::BI__exception_info:
508 case Builtin::BI_exception_info: {
509 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
510 diag::err_seh___except_filter))
511 return ExprError();
512 break;
513 }
514
David Majnemerba3e5ec2015-03-13 18:26:17 +0000515 case Builtin::BI__GetExceptionInfo:
516 if (checkArgCount(*this, TheCall, 1))
517 return ExprError();
518
519 if (CheckCXXThrowOperand(
520 TheCall->getLocStart(),
521 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
522 TheCall))
523 return ExprError();
524
525 TheCall->setType(Context.VoidPtrTy);
526 break;
527
Nate Begeman4904e322010-06-08 02:47:44 +0000528 }
Richard Smith760520b2014-06-03 23:27:44 +0000529
Nate Begeman4904e322010-06-08 02:47:44 +0000530 // Since the target specific builtins for each arch overlap, only check those
531 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000532 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000533 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000534 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000535 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000536 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000537 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000538 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
539 return ExprError();
540 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000541 case llvm::Triple::aarch64:
542 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000543 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000544 return ExprError();
545 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000546 case llvm::Triple::mips:
547 case llvm::Triple::mipsel:
548 case llvm::Triple::mips64:
549 case llvm::Triple::mips64el:
550 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
551 return ExprError();
552 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000553 case llvm::Triple::systemz:
554 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
555 return ExprError();
556 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000557 case llvm::Triple::x86:
558 case llvm::Triple::x86_64:
559 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
560 return ExprError();
561 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000562 case llvm::Triple::ppc:
563 case llvm::Triple::ppc64:
564 case llvm::Triple::ppc64le:
565 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
566 return ExprError();
567 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000568 default:
569 break;
570 }
571 }
572
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000573 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000574}
575
Nate Begeman91e1fea2010-06-14 05:21:25 +0000576// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000577static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000578 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000579 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000580 switch (Type.getEltType()) {
581 case NeonTypeFlags::Int8:
582 case NeonTypeFlags::Poly8:
583 return shift ? 7 : (8 << IsQuad) - 1;
584 case NeonTypeFlags::Int16:
585 case NeonTypeFlags::Poly16:
586 return shift ? 15 : (4 << IsQuad) - 1;
587 case NeonTypeFlags::Int32:
588 return shift ? 31 : (2 << IsQuad) - 1;
589 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000590 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000591 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000592 case NeonTypeFlags::Poly128:
593 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000594 case NeonTypeFlags::Float16:
595 assert(!shift && "cannot shift float types!");
596 return (4 << IsQuad) - 1;
597 case NeonTypeFlags::Float32:
598 assert(!shift && "cannot shift float types!");
599 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000600 case NeonTypeFlags::Float64:
601 assert(!shift && "cannot shift float types!");
602 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000603 }
David Blaikie8a40f702012-01-17 06:56:22 +0000604 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000605}
606
Bob Wilsone4d77232011-11-08 05:04:11 +0000607/// getNeonEltType - Return the QualType corresponding to the elements of
608/// the vector type specified by the NeonTypeFlags. This is used to check
609/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000610static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000611 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000612 switch (Flags.getEltType()) {
613 case NeonTypeFlags::Int8:
614 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
615 case NeonTypeFlags::Int16:
616 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
617 case NeonTypeFlags::Int32:
618 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
619 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000620 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000621 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
622 else
623 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
624 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000625 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000626 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000627 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000628 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000629 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000630 if (IsInt64Long)
631 return Context.UnsignedLongTy;
632 else
633 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000634 case NeonTypeFlags::Poly128:
635 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000636 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000637 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000638 case NeonTypeFlags::Float32:
639 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000640 case NeonTypeFlags::Float64:
641 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000642 }
David Blaikie8a40f702012-01-17 06:56:22 +0000643 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000644}
645
Tim Northover12670412014-02-19 10:37:05 +0000646bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000647 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000648 uint64_t mask = 0;
649 unsigned TV = 0;
650 int PtrArgNum = -1;
651 bool HasConstPtr = false;
652 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000653#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000654#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000655#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000656 }
657
658 // For NEON intrinsics which are overloaded on vector element type, validate
659 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000660 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000661 if (mask) {
662 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
663 return true;
664
665 TV = Result.getLimitedValue(64);
666 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
667 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000668 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000669 }
670
671 if (PtrArgNum >= 0) {
672 // Check that pointer arguments have the specified type.
673 Expr *Arg = TheCall->getArg(PtrArgNum);
674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
675 Arg = ICE->getSubExpr();
676 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
677 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000678
Tim Northovera2ee4332014-03-29 15:09:45 +0000679 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000680 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000681 bool IsInt64Long =
682 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
683 QualType EltTy =
684 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000685 if (HasConstPtr)
686 EltTy = EltTy.withConst();
687 QualType LHSTy = Context.getPointerType(EltTy);
688 AssignConvertType ConvTy;
689 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
690 if (RHS.isInvalid())
691 return true;
692 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
693 RHS.get(), AA_Assigning))
694 return true;
695 }
696
697 // For NEON intrinsics which take an immediate value as part of the
698 // instruction, range check them here.
699 unsigned i = 0, l = 0, u = 0;
700 switch (BuiltinID) {
701 default:
702 return false;
Tim Northover12670412014-02-19 10:37:05 +0000703#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000704#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000705#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000706 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000707
Richard Sandiford28940af2014-04-16 08:47:51 +0000708 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000709}
710
Tim Northovera2ee4332014-03-29 15:09:45 +0000711bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
712 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000713 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000714 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000715 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000716 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000717 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000718 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
719 BuiltinID == AArch64::BI__builtin_arm_strex ||
720 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000721 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000722 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000723 BuiltinID == ARM::BI__builtin_arm_ldaex ||
724 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
725 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000726
727 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
728
729 // Ensure that we have the proper number of arguments.
730 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
731 return true;
732
733 // Inspect the pointer argument of the atomic builtin. This should always be
734 // a pointer type, whose element is an integral scalar or pointer type.
735 // Because it is a pointer type, we don't have to worry about any implicit
736 // casts here.
737 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
738 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
739 if (PointerArgRes.isInvalid())
740 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000741 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000742
743 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
744 if (!pointerType) {
745 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
746 << PointerArg->getType() << PointerArg->getSourceRange();
747 return true;
748 }
749
750 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
751 // task is to insert the appropriate casts into the AST. First work out just
752 // what the appropriate type is.
753 QualType ValType = pointerType->getPointeeType();
754 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
755 if (IsLdrex)
756 AddrType.addConst();
757
758 // Issue a warning if the cast is dodgy.
759 CastKind CastNeeded = CK_NoOp;
760 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
761 CastNeeded = CK_BitCast;
762 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
763 << PointerArg->getType()
764 << Context.getPointerType(AddrType)
765 << AA_Passing << PointerArg->getSourceRange();
766 }
767
768 // Finally, do the cast and replace the argument with the corrected version.
769 AddrType = Context.getPointerType(AddrType);
770 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
771 if (PointerArgRes.isInvalid())
772 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000773 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000774
775 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
776
777 // In general, we allow ints, floats and pointers to be loaded and stored.
778 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
779 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
780 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
781 << PointerArg->getType() << PointerArg->getSourceRange();
782 return true;
783 }
784
785 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000786 if (Context.getTypeSize(ValType) > MaxWidth) {
787 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000788 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
789 << PointerArg->getType() << PointerArg->getSourceRange();
790 return true;
791 }
792
793 switch (ValType.getObjCLifetime()) {
794 case Qualifiers::OCL_None:
795 case Qualifiers::OCL_ExplicitNone:
796 // okay
797 break;
798
799 case Qualifiers::OCL_Weak:
800 case Qualifiers::OCL_Strong:
801 case Qualifiers::OCL_Autoreleasing:
802 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
803 << ValType << PointerArg->getSourceRange();
804 return true;
805 }
806
807
808 if (IsLdrex) {
809 TheCall->setType(ValType);
810 return false;
811 }
812
813 // Initialize the argument to be stored.
814 ExprResult ValArg = TheCall->getArg(0);
815 InitializedEntity Entity = InitializedEntity::InitializeParameter(
816 Context, ValType, /*consume*/ false);
817 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
818 if (ValArg.isInvalid())
819 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000820 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000821
822 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
823 // but the custom checker bypasses all default analysis.
824 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000825 return false;
826}
827
Nate Begeman4904e322010-06-08 02:47:44 +0000828bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000829 llvm::APSInt Result;
830
Tim Northover6aacd492013-07-16 09:47:53 +0000831 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000832 BuiltinID == ARM::BI__builtin_arm_ldaex ||
833 BuiltinID == ARM::BI__builtin_arm_strex ||
834 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000835 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000836 }
837
Yi Kong26d104a2014-08-13 19:18:14 +0000838 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
839 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
840 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
841 }
842
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000843 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
844 BuiltinID == ARM::BI__builtin_arm_wsr64)
845 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
846
847 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
848 BuiltinID == ARM::BI__builtin_arm_rsrp ||
849 BuiltinID == ARM::BI__builtin_arm_wsr ||
850 BuiltinID == ARM::BI__builtin_arm_wsrp)
851 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
852
Tim Northover12670412014-02-19 10:37:05 +0000853 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
854 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000855
Yi Kong4efadfb2014-07-03 16:01:25 +0000856 // For intrinsics which take an immediate value as part of the instruction,
857 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000858 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000859 switch (BuiltinID) {
860 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000861 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
862 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000863 case ARM::BI__builtin_arm_vcvtr_f:
864 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000865 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000866 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000867 case ARM::BI__builtin_arm_isb:
868 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000869 }
Nate Begemand773fe62010-06-13 04:47:52 +0000870
Nate Begemanf568b072010-08-03 21:32:34 +0000871 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000872 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000873}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000874
Tim Northover573cbee2014-05-24 12:52:07 +0000875bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000876 CallExpr *TheCall) {
877 llvm::APSInt Result;
878
Tim Northover573cbee2014-05-24 12:52:07 +0000879 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000880 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
881 BuiltinID == AArch64::BI__builtin_arm_strex ||
882 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000883 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
884 }
885
Yi Konga5548432014-08-13 19:18:20 +0000886 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
887 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
888 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
889 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
890 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
891 }
892
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000893 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
894 BuiltinID == AArch64::BI__builtin_arm_wsr64)
895 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
896
897 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
898 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
899 BuiltinID == AArch64::BI__builtin_arm_wsr ||
900 BuiltinID == AArch64::BI__builtin_arm_wsrp)
901 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
902
Tim Northovera2ee4332014-03-29 15:09:45 +0000903 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
904 return true;
905
Yi Kong19a29ac2014-07-17 10:52:06 +0000906 // For intrinsics which take an immediate value as part of the instruction,
907 // range check them here.
908 unsigned i = 0, l = 0, u = 0;
909 switch (BuiltinID) {
910 default: return false;
911 case AArch64::BI__builtin_arm_dmb:
912 case AArch64::BI__builtin_arm_dsb:
913 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
914 }
915
Yi Kong19a29ac2014-07-17 10:52:06 +0000916 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000917}
918
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000919bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
920 unsigned i = 0, l = 0, u = 0;
921 switch (BuiltinID) {
922 default: return false;
923 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
924 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000925 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
926 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
927 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
928 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
929 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000930 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000931
Richard Sandiford28940af2014-04-16 08:47:51 +0000932 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000933}
934
Kit Bartone50adcb2015-03-30 19:40:59 +0000935bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
936 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000937 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
938 BuiltinID == PPC::BI__builtin_divdeu ||
939 BuiltinID == PPC::BI__builtin_bpermd;
940 bool IsTarget64Bit = Context.getTargetInfo()
941 .getTypeWidth(Context
942 .getTargetInfo()
943 .getIntPtrType()) == 64;
944 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
945 BuiltinID == PPC::BI__builtin_divweu ||
946 BuiltinID == PPC::BI__builtin_divde ||
947 BuiltinID == PPC::BI__builtin_divdeu;
948
949 if (Is64BitBltin && !IsTarget64Bit)
950 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
951 << TheCall->getSourceRange();
952
953 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
954 (BuiltinID == PPC::BI__builtin_bpermd &&
955 !Context.getTargetInfo().hasFeature("bpermd")))
956 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
957 << TheCall->getSourceRange();
958
Kit Bartone50adcb2015-03-30 19:40:59 +0000959 switch (BuiltinID) {
960 default: return false;
961 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
962 case PPC::BI__builtin_altivec_crypto_vshasigmad:
963 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
964 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
965 case PPC::BI__builtin_tbegin:
966 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
967 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
968 case PPC::BI__builtin_tabortwc:
969 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
970 case PPC::BI__builtin_tabortwci:
971 case PPC::BI__builtin_tabortdci:
972 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
973 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
974 }
975 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
976}
977
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000978bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
979 CallExpr *TheCall) {
980 if (BuiltinID == SystemZ::BI__builtin_tabort) {
981 Expr *Arg = TheCall->getArg(0);
982 llvm::APSInt AbortCode(32);
983 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
984 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
985 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
986 << Arg->getSourceRange();
987 }
988
Ulrich Weigand5722c0f2015-05-05 19:36:42 +0000989 // For intrinsics which take an immediate value as part of the instruction,
990 // range check them here.
991 unsigned i = 0, l = 0, u = 0;
992 switch (BuiltinID) {
993 default: return false;
994 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
995 case SystemZ::BI__builtin_s390_verimb:
996 case SystemZ::BI__builtin_s390_verimh:
997 case SystemZ::BI__builtin_s390_verimf:
998 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
999 case SystemZ::BI__builtin_s390_vfaeb:
1000 case SystemZ::BI__builtin_s390_vfaeh:
1001 case SystemZ::BI__builtin_s390_vfaef:
1002 case SystemZ::BI__builtin_s390_vfaebs:
1003 case SystemZ::BI__builtin_s390_vfaehs:
1004 case SystemZ::BI__builtin_s390_vfaefs:
1005 case SystemZ::BI__builtin_s390_vfaezb:
1006 case SystemZ::BI__builtin_s390_vfaezh:
1007 case SystemZ::BI__builtin_s390_vfaezf:
1008 case SystemZ::BI__builtin_s390_vfaezbs:
1009 case SystemZ::BI__builtin_s390_vfaezhs:
1010 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1011 case SystemZ::BI__builtin_s390_vfidb:
1012 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1013 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1014 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1015 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1016 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1017 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1018 case SystemZ::BI__builtin_s390_vstrcb:
1019 case SystemZ::BI__builtin_s390_vstrch:
1020 case SystemZ::BI__builtin_s390_vstrcf:
1021 case SystemZ::BI__builtin_s390_vstrczb:
1022 case SystemZ::BI__builtin_s390_vstrczh:
1023 case SystemZ::BI__builtin_s390_vstrczf:
1024 case SystemZ::BI__builtin_s390_vstrcbs:
1025 case SystemZ::BI__builtin_s390_vstrchs:
1026 case SystemZ::BI__builtin_s390_vstrcfs:
1027 case SystemZ::BI__builtin_s390_vstrczbs:
1028 case SystemZ::BI__builtin_s390_vstrczhs:
1029 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1030 }
1031 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001032}
1033
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001034bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001035 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001036 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001037 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001038 case X86::BI__builtin_cpu_supports:
1039 return SemaBuiltinCpuSupports(TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001040 case X86::BI__builtin_ms_va_start:
1041 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001042 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001043 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001044 case X86::BI__builtin_ia32_vpermil2pd:
1045 case X86::BI__builtin_ia32_vpermil2pd256:
1046 case X86::BI__builtin_ia32_vpermil2ps:
1047 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001048 case X86::BI__builtin_ia32_cmpb128_mask:
1049 case X86::BI__builtin_ia32_cmpw128_mask:
1050 case X86::BI__builtin_ia32_cmpd128_mask:
1051 case X86::BI__builtin_ia32_cmpq128_mask:
1052 case X86::BI__builtin_ia32_cmpb256_mask:
1053 case X86::BI__builtin_ia32_cmpw256_mask:
1054 case X86::BI__builtin_ia32_cmpd256_mask:
1055 case X86::BI__builtin_ia32_cmpq256_mask:
1056 case X86::BI__builtin_ia32_cmpb512_mask:
1057 case X86::BI__builtin_ia32_cmpw512_mask:
1058 case X86::BI__builtin_ia32_cmpd512_mask:
1059 case X86::BI__builtin_ia32_cmpq512_mask:
1060 case X86::BI__builtin_ia32_ucmpb128_mask:
1061 case X86::BI__builtin_ia32_ucmpw128_mask:
1062 case X86::BI__builtin_ia32_ucmpd128_mask:
1063 case X86::BI__builtin_ia32_ucmpq128_mask:
1064 case X86::BI__builtin_ia32_ucmpb256_mask:
1065 case X86::BI__builtin_ia32_ucmpw256_mask:
1066 case X86::BI__builtin_ia32_ucmpd256_mask:
1067 case X86::BI__builtin_ia32_ucmpq256_mask:
1068 case X86::BI__builtin_ia32_ucmpb512_mask:
1069 case X86::BI__builtin_ia32_ucmpw512_mask:
1070 case X86::BI__builtin_ia32_ucmpd512_mask:
1071 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001072 case X86::BI__builtin_ia32_roundps:
1073 case X86::BI__builtin_ia32_roundpd:
1074 case X86::BI__builtin_ia32_roundps256:
1075 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1076 case X86::BI__builtin_ia32_roundss:
1077 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1078 case X86::BI__builtin_ia32_cmpps:
1079 case X86::BI__builtin_ia32_cmpss:
1080 case X86::BI__builtin_ia32_cmppd:
1081 case X86::BI__builtin_ia32_cmpsd:
1082 case X86::BI__builtin_ia32_cmpps256:
1083 case X86::BI__builtin_ia32_cmppd256:
1084 case X86::BI__builtin_ia32_cmpps512_mask:
1085 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001086 case X86::BI__builtin_ia32_vpcomub:
1087 case X86::BI__builtin_ia32_vpcomuw:
1088 case X86::BI__builtin_ia32_vpcomud:
1089 case X86::BI__builtin_ia32_vpcomuq:
1090 case X86::BI__builtin_ia32_vpcomb:
1091 case X86::BI__builtin_ia32_vpcomw:
1092 case X86::BI__builtin_ia32_vpcomd:
1093 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001094 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001095 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001096}
1097
Richard Smith55ce3522012-06-25 20:30:08 +00001098/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1099/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1100/// Returns true when the format fits the function and the FormatStringInfo has
1101/// been populated.
1102bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1103 FormatStringInfo *FSI) {
1104 FSI->HasVAListArg = Format->getFirstArg() == 0;
1105 FSI->FormatIdx = Format->getFormatIdx() - 1;
1106 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001107
Richard Smith55ce3522012-06-25 20:30:08 +00001108 // The way the format attribute works in GCC, the implicit this argument
1109 // of member functions is counted. However, it doesn't appear in our own
1110 // lists, so decrement format_idx in that case.
1111 if (IsCXXMember) {
1112 if(FSI->FormatIdx == 0)
1113 return false;
1114 --FSI->FormatIdx;
1115 if (FSI->FirstDataArg != 0)
1116 --FSI->FirstDataArg;
1117 }
1118 return true;
1119}
Mike Stump11289f42009-09-09 15:08:12 +00001120
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001121/// Checks if a the given expression evaluates to null.
1122///
1123/// \brief Returns true if the value evaluates to null.
1124static bool CheckNonNullExpr(Sema &S,
1125 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001126 // If the expression has non-null type, it doesn't evaluate to null.
1127 if (auto nullability
1128 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1129 if (*nullability == NullabilityKind::NonNull)
1130 return false;
1131 }
1132
Ted Kremeneka146db32014-01-17 06:24:47 +00001133 // As a special case, transparent unions initialized with zero are
1134 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001135 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001136 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1137 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001138 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001139 if (const InitListExpr *ILE =
1140 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001141 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001142 }
1143
1144 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001145 return (!Expr->isValueDependent() &&
1146 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1147 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001148}
1149
1150static void CheckNonNullArgument(Sema &S,
1151 const Expr *ArgExpr,
1152 SourceLocation CallSiteLoc) {
1153 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001154 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1155 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001156}
1157
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001158bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1159 FormatStringInfo FSI;
1160 if ((GetFormatStringType(Format) == FST_NSString) &&
1161 getFormatStringInfo(Format, false, &FSI)) {
1162 Idx = FSI.FormatIdx;
1163 return true;
1164 }
1165 return false;
1166}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001167/// \brief Diagnose use of %s directive in an NSString which is being passed
1168/// as formatting string to formatting method.
1169static void
1170DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1171 const NamedDecl *FDecl,
1172 Expr **Args,
1173 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001174 unsigned Idx = 0;
1175 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001176 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1177 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001178 Idx = 2;
1179 Format = true;
1180 }
1181 else
1182 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1183 if (S.GetFormatNSStringIdx(I, Idx)) {
1184 Format = true;
1185 break;
1186 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001187 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001188 if (!Format || NumArgs <= Idx)
1189 return;
1190 const Expr *FormatExpr = Args[Idx];
1191 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1192 FormatExpr = CSCE->getSubExpr();
1193 const StringLiteral *FormatString;
1194 if (const ObjCStringLiteral *OSL =
1195 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1196 FormatString = OSL->getString();
1197 else
1198 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1199 if (!FormatString)
1200 return;
1201 if (S.FormatStringHasSArg(FormatString)) {
1202 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1203 << "%s" << 1 << 1;
1204 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1205 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001206 }
1207}
1208
Douglas Gregorb4866e82015-06-19 18:13:19 +00001209/// Determine whether the given type has a non-null nullability annotation.
1210static bool isNonNullType(ASTContext &ctx, QualType type) {
1211 if (auto nullability = type->getNullability(ctx))
1212 return *nullability == NullabilityKind::NonNull;
1213
1214 return false;
1215}
1216
Ted Kremenek2bc73332014-01-17 06:24:43 +00001217static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001218 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001219 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001220 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001221 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001222 assert((FDecl || Proto) && "Need a function declaration or prototype");
1223
Ted Kremenek9aedc152014-01-17 06:24:56 +00001224 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001225 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001226 if (FDecl) {
1227 // Handle the nonnull attribute on the function/method declaration itself.
1228 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1229 if (!NonNull->args_size()) {
1230 // Easy case: all pointer arguments are nonnull.
1231 for (const auto *Arg : Args)
1232 if (S.isValidPointerAttrType(Arg->getType()))
1233 CheckNonNullArgument(S, Arg, CallSiteLoc);
1234 return;
1235 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001236
Douglas Gregorb4866e82015-06-19 18:13:19 +00001237 for (unsigned Val : NonNull->args()) {
1238 if (Val >= Args.size())
1239 continue;
1240 if (NonNullArgs.empty())
1241 NonNullArgs.resize(Args.size());
1242 NonNullArgs.set(Val);
1243 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001244 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001245 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001246
Douglas Gregorb4866e82015-06-19 18:13:19 +00001247 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1248 // Handle the nonnull attribute on the parameters of the
1249 // function/method.
1250 ArrayRef<ParmVarDecl*> parms;
1251 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1252 parms = FD->parameters();
1253 else
1254 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1255
1256 unsigned ParamIndex = 0;
1257 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1258 I != E; ++I, ++ParamIndex) {
1259 const ParmVarDecl *PVD = *I;
1260 if (PVD->hasAttr<NonNullAttr>() ||
1261 isNonNullType(S.Context, PVD->getType())) {
1262 if (NonNullArgs.empty())
1263 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001264
Douglas Gregorb4866e82015-06-19 18:13:19 +00001265 NonNullArgs.set(ParamIndex);
1266 }
1267 }
1268 } else {
1269 // If we have a non-function, non-method declaration but no
1270 // function prototype, try to dig out the function prototype.
1271 if (!Proto) {
1272 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1273 QualType type = VD->getType().getNonReferenceType();
1274 if (auto pointerType = type->getAs<PointerType>())
1275 type = pointerType->getPointeeType();
1276 else if (auto blockType = type->getAs<BlockPointerType>())
1277 type = blockType->getPointeeType();
1278 // FIXME: data member pointers?
1279
1280 // Dig out the function prototype, if there is one.
1281 Proto = type->getAs<FunctionProtoType>();
1282 }
1283 }
1284
1285 // Fill in non-null argument information from the nullability
1286 // information on the parameter types (if we have them).
1287 if (Proto) {
1288 unsigned Index = 0;
1289 for (auto paramType : Proto->getParamTypes()) {
1290 if (isNonNullType(S.Context, paramType)) {
1291 if (NonNullArgs.empty())
1292 NonNullArgs.resize(Args.size());
1293
1294 NonNullArgs.set(Index);
1295 }
1296
1297 ++Index;
1298 }
1299 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001300 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001301
Douglas Gregorb4866e82015-06-19 18:13:19 +00001302 // Check for non-null arguments.
1303 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1304 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001305 if (NonNullArgs[ArgIndex])
1306 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001307 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001308}
1309
Richard Smith55ce3522012-06-25 20:30:08 +00001310/// Handles the checks for format strings, non-POD arguments to vararg
1311/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001312void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1313 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001314 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001315 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001316 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001317 if (CurContext->isDependentContext())
1318 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001319
Ted Kremenekb8176da2010-09-09 04:33:05 +00001320 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001321 llvm::SmallBitVector CheckedVarArgs;
1322 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001323 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001324 // Only create vector if there are format attributes.
1325 CheckedVarArgs.resize(Args.size());
1326
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001327 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001328 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001329 }
Richard Smithd7293d72013-08-05 18:49:43 +00001330 }
Richard Smith55ce3522012-06-25 20:30:08 +00001331
1332 // Refuse POD arguments that weren't caught by the format string
1333 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001334 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001335 unsigned NumParams = Proto ? Proto->getNumParams()
1336 : FDecl && isa<FunctionDecl>(FDecl)
1337 ? cast<FunctionDecl>(FDecl)->getNumParams()
1338 : FDecl && isa<ObjCMethodDecl>(FDecl)
1339 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1340 : 0;
1341
Alp Toker9cacbab2014-01-20 20:26:09 +00001342 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001343 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001344 if (const Expr *Arg = Args[ArgIdx]) {
1345 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1346 checkVariadicArgument(Arg, CallType);
1347 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001348 }
Richard Smithd7293d72013-08-05 18:49:43 +00001349 }
Mike Stump11289f42009-09-09 15:08:12 +00001350
Douglas Gregorb4866e82015-06-19 18:13:19 +00001351 if (FDecl || Proto) {
1352 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001353
Richard Trieu41bc0992013-06-22 00:20:41 +00001354 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001355 if (FDecl) {
1356 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1357 CheckArgumentWithTypeTag(I, Args.data());
1358 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001359 }
Richard Smith55ce3522012-06-25 20:30:08 +00001360}
1361
1362/// CheckConstructorCall - Check a constructor call for correctness and safety
1363/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001364void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1365 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001366 const FunctionProtoType *Proto,
1367 SourceLocation Loc) {
1368 VariadicCallType CallType =
1369 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001370 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1371 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001372}
1373
1374/// CheckFunctionCall - Check a direct function call for various correctness
1375/// and safety properties not strictly enforced by the C type system.
1376bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1377 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001378 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1379 isa<CXXMethodDecl>(FDecl);
1380 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1381 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001382 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1383 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001384 Expr** Args = TheCall->getArgs();
1385 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001386 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001387 // If this is a call to a member operator, hide the first argument
1388 // from checkCall.
1389 // FIXME: Our choice of AST representation here is less than ideal.
1390 ++Args;
1391 --NumArgs;
1392 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001393 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001394 IsMemberFunction, TheCall->getRParenLoc(),
1395 TheCall->getCallee()->getSourceRange(), CallType);
1396
1397 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1398 // None of the checks below are needed for functions that don't have
1399 // simple names (e.g., C++ conversion functions).
1400 if (!FnInfo)
1401 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001402
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001403 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001404 if (getLangOpts().ObjC1)
1405 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001406
Anna Zaks22122702012-01-17 00:37:07 +00001407 unsigned CMId = FDecl->getMemoryFunctionKind();
1408 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001409 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001410
Anna Zaks201d4892012-01-13 21:52:01 +00001411 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001412 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001413 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001414 else if (CMId == Builtin::BIstrncat)
1415 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001416 else
Anna Zaks22122702012-01-17 00:37:07 +00001417 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001418
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001419 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001420}
1421
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001422bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001423 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001424 VariadicCallType CallType =
1425 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001426
Douglas Gregorb4866e82015-06-19 18:13:19 +00001427 checkCall(Method, nullptr, Args,
1428 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1429 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001430
1431 return false;
1432}
1433
Richard Trieu664c4c62013-06-20 21:03:13 +00001434bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1435 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001436 QualType Ty;
1437 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001438 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001439 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001440 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001441 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001442 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001443
Douglas Gregorb4866e82015-06-19 18:13:19 +00001444 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1445 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001446 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001447
Richard Trieu664c4c62013-06-20 21:03:13 +00001448 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001449 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001450 CallType = VariadicDoesNotApply;
1451 } else if (Ty->isBlockPointerType()) {
1452 CallType = VariadicBlock;
1453 } else { // Ty->isFunctionPointerType()
1454 CallType = VariadicFunction;
1455 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001456
Douglas Gregorb4866e82015-06-19 18:13:19 +00001457 checkCall(NDecl, Proto,
1458 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1459 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001460 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001461
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001462 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001463}
1464
Richard Trieu41bc0992013-06-22 00:20:41 +00001465/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1466/// such as function pointers returned from functions.
1467bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001468 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001469 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001470 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001471 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001472 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001473 TheCall->getCallee()->getSourceRange(), CallType);
1474
1475 return false;
1476}
1477
Tim Northovere94a34c2014-03-11 10:49:14 +00001478static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1479 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1480 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1481 return false;
1482
1483 switch (Op) {
1484 case AtomicExpr::AO__c11_atomic_init:
1485 llvm_unreachable("There is no ordering argument for an init");
1486
1487 case AtomicExpr::AO__c11_atomic_load:
1488 case AtomicExpr::AO__atomic_load_n:
1489 case AtomicExpr::AO__atomic_load:
1490 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1491 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1492
1493 case AtomicExpr::AO__c11_atomic_store:
1494 case AtomicExpr::AO__atomic_store:
1495 case AtomicExpr::AO__atomic_store_n:
1496 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1497 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1498 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1499
1500 default:
1501 return true;
1502 }
1503}
1504
Richard Smithfeea8832012-04-12 05:08:17 +00001505ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1506 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001507 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1508 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001509
Richard Smithfeea8832012-04-12 05:08:17 +00001510 // All these operations take one of the following forms:
1511 enum {
1512 // C __c11_atomic_init(A *, C)
1513 Init,
1514 // C __c11_atomic_load(A *, int)
1515 Load,
1516 // void __atomic_load(A *, CP, int)
1517 Copy,
1518 // C __c11_atomic_add(A *, M, int)
1519 Arithmetic,
1520 // C __atomic_exchange_n(A *, CP, int)
1521 Xchg,
1522 // void __atomic_exchange(A *, C *, CP, int)
1523 GNUXchg,
1524 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1525 C11CmpXchg,
1526 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1527 GNUCmpXchg
1528 } Form = Init;
1529 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1530 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1531 // where:
1532 // C is an appropriate type,
1533 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1534 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1535 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1536 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001537
Gabor Horvath98bd0982015-03-16 09:59:54 +00001538 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1539 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1540 AtomicExpr::AO__atomic_load,
1541 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001542 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1543 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1544 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1545 Op == AtomicExpr::AO__atomic_store_n ||
1546 Op == AtomicExpr::AO__atomic_exchange_n ||
1547 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1548 bool IsAddSub = false;
1549
1550 switch (Op) {
1551 case AtomicExpr::AO__c11_atomic_init:
1552 Form = Init;
1553 break;
1554
1555 case AtomicExpr::AO__c11_atomic_load:
1556 case AtomicExpr::AO__atomic_load_n:
1557 Form = Load;
1558 break;
1559
1560 case AtomicExpr::AO__c11_atomic_store:
1561 case AtomicExpr::AO__atomic_load:
1562 case AtomicExpr::AO__atomic_store:
1563 case AtomicExpr::AO__atomic_store_n:
1564 Form = Copy;
1565 break;
1566
1567 case AtomicExpr::AO__c11_atomic_fetch_add:
1568 case AtomicExpr::AO__c11_atomic_fetch_sub:
1569 case AtomicExpr::AO__atomic_fetch_add:
1570 case AtomicExpr::AO__atomic_fetch_sub:
1571 case AtomicExpr::AO__atomic_add_fetch:
1572 case AtomicExpr::AO__atomic_sub_fetch:
1573 IsAddSub = true;
1574 // Fall through.
1575 case AtomicExpr::AO__c11_atomic_fetch_and:
1576 case AtomicExpr::AO__c11_atomic_fetch_or:
1577 case AtomicExpr::AO__c11_atomic_fetch_xor:
1578 case AtomicExpr::AO__atomic_fetch_and:
1579 case AtomicExpr::AO__atomic_fetch_or:
1580 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001581 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001582 case AtomicExpr::AO__atomic_and_fetch:
1583 case AtomicExpr::AO__atomic_or_fetch:
1584 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001585 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001586 Form = Arithmetic;
1587 break;
1588
1589 case AtomicExpr::AO__c11_atomic_exchange:
1590 case AtomicExpr::AO__atomic_exchange_n:
1591 Form = Xchg;
1592 break;
1593
1594 case AtomicExpr::AO__atomic_exchange:
1595 Form = GNUXchg;
1596 break;
1597
1598 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1599 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1600 Form = C11CmpXchg;
1601 break;
1602
1603 case AtomicExpr::AO__atomic_compare_exchange:
1604 case AtomicExpr::AO__atomic_compare_exchange_n:
1605 Form = GNUCmpXchg;
1606 break;
1607 }
1608
1609 // Check we have the right number of arguments.
1610 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001611 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001612 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001613 << TheCall->getCallee()->getSourceRange();
1614 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001615 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1616 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001617 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001618 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001619 << TheCall->getCallee()->getSourceRange();
1620 return ExprError();
1621 }
1622
Richard Smithfeea8832012-04-12 05:08:17 +00001623 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001624 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001625 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1626 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1627 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001628 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001629 << Ptr->getType() << Ptr->getSourceRange();
1630 return ExprError();
1631 }
1632
Richard Smithfeea8832012-04-12 05:08:17 +00001633 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1634 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1635 QualType ValType = AtomTy; // 'C'
1636 if (IsC11) {
1637 if (!AtomTy->isAtomicType()) {
1638 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1639 << Ptr->getType() << Ptr->getSourceRange();
1640 return ExprError();
1641 }
Richard Smithe00921a2012-09-15 06:09:58 +00001642 if (AtomTy.isConstQualified()) {
1643 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1644 << Ptr->getType() << Ptr->getSourceRange();
1645 return ExprError();
1646 }
Richard Smithfeea8832012-04-12 05:08:17 +00001647 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001648 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1649 if (ValType.isConstQualified()) {
1650 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1651 << Ptr->getType() << Ptr->getSourceRange();
1652 return ExprError();
1653 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001654 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001655
Richard Smithfeea8832012-04-12 05:08:17 +00001656 // For an arithmetic operation, the implied arithmetic must be well-formed.
1657 if (Form == Arithmetic) {
1658 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1659 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1660 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1661 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1662 return ExprError();
1663 }
1664 if (!IsAddSub && !ValType->isIntegerType()) {
1665 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1666 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1667 return ExprError();
1668 }
David Majnemere85cff82015-01-28 05:48:06 +00001669 if (IsC11 && ValType->isPointerType() &&
1670 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1671 diag::err_incomplete_type)) {
1672 return ExprError();
1673 }
Richard Smithfeea8832012-04-12 05:08:17 +00001674 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1675 // For __atomic_*_n operations, the value type must be a scalar integral or
1676 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001677 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001678 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1679 return ExprError();
1680 }
1681
Eli Friedmanaa769812013-09-11 03:49:34 +00001682 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1683 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001684 // For GNU atomics, require a trivially-copyable type. This is not part of
1685 // the GNU atomics specification, but we enforce it for sanity.
1686 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001687 << Ptr->getType() << Ptr->getSourceRange();
1688 return ExprError();
1689 }
1690
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001691 switch (ValType.getObjCLifetime()) {
1692 case Qualifiers::OCL_None:
1693 case Qualifiers::OCL_ExplicitNone:
1694 // okay
1695 break;
1696
1697 case Qualifiers::OCL_Weak:
1698 case Qualifiers::OCL_Strong:
1699 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001700 // FIXME: Can this happen? By this point, ValType should be known
1701 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001702 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1703 << ValType << Ptr->getSourceRange();
1704 return ExprError();
1705 }
1706
David Majnemerc6eb6502015-06-03 00:26:35 +00001707 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1708 // volatile-ness of the pointee-type inject itself into the result or the
1709 // other operands.
1710 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001711 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001712 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001713 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001714 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001715 ResultType = Context.BoolTy;
1716
Richard Smithfeea8832012-04-12 05:08:17 +00001717 // The type of a parameter passed 'by value'. In the GNU atomics, such
1718 // arguments are actually passed as pointers.
1719 QualType ByValType = ValType; // 'CP'
1720 if (!IsC11 && !IsN)
1721 ByValType = Ptr->getType();
1722
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001723 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1724 // but not the second argument. We need to manually remove possible const
1725 // qualifiers.
1726
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001727 // The first argument --- the pointer --- has a fixed type; we
1728 // deduce the types of the rest of the arguments accordingly. Walk
1729 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001730 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001731 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001732 if (i < NumVals[Form] + 1) {
1733 switch (i) {
1734 case 1:
1735 // The second argument is the non-atomic operand. For arithmetic, this
1736 // is always passed by value, and for a compare_exchange it is always
1737 // passed by address. For the rest, GNU uses by-address and C11 uses
1738 // by-value.
1739 assert(Form != Load);
1740 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1741 Ty = ValType;
1742 else if (Form == Copy || Form == Xchg)
1743 Ty = ByValType;
1744 else if (Form == Arithmetic)
1745 Ty = Context.getPointerDiffType();
1746 else
1747 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1748 break;
1749 case 2:
1750 // The third argument to compare_exchange / GNU exchange is a
1751 // (pointer to a) desired value.
1752 Ty = ByValType;
1753 break;
1754 case 3:
1755 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1756 Ty = Context.BoolTy;
1757 break;
1758 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001759 } else {
1760 // The order(s) are always converted to int.
1761 Ty = Context.IntTy;
1762 }
Richard Smithfeea8832012-04-12 05:08:17 +00001763
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001764 InitializedEntity Entity =
1765 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001766 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001767 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1768 if (Arg.isInvalid())
1769 return true;
1770 TheCall->setArg(i, Arg.get());
1771 }
1772
Richard Smithfeea8832012-04-12 05:08:17 +00001773 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001774 SmallVector<Expr*, 5> SubExprs;
1775 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001776 switch (Form) {
1777 case Init:
1778 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001779 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001780 break;
1781 case Load:
1782 SubExprs.push_back(TheCall->getArg(1)); // Order
1783 break;
1784 case Copy:
1785 case Arithmetic:
1786 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001787 SubExprs.push_back(TheCall->getArg(2)); // Order
1788 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001789 break;
1790 case GNUXchg:
1791 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1792 SubExprs.push_back(TheCall->getArg(3)); // Order
1793 SubExprs.push_back(TheCall->getArg(1)); // Val1
1794 SubExprs.push_back(TheCall->getArg(2)); // Val2
1795 break;
1796 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001797 SubExprs.push_back(TheCall->getArg(3)); // Order
1798 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001799 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001800 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001801 break;
1802 case GNUCmpXchg:
1803 SubExprs.push_back(TheCall->getArg(4)); // Order
1804 SubExprs.push_back(TheCall->getArg(1)); // Val1
1805 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1806 SubExprs.push_back(TheCall->getArg(2)); // Val2
1807 SubExprs.push_back(TheCall->getArg(3)); // Weak
1808 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001809 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001810
1811 if (SubExprs.size() >= 2 && Form != Init) {
1812 llvm::APSInt Result(32);
1813 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1814 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001815 Diag(SubExprs[1]->getLocStart(),
1816 diag::warn_atomic_op_has_invalid_memory_order)
1817 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001818 }
1819
Fariborz Jahanian615de762013-05-28 17:37:39 +00001820 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1821 SubExprs, ResultType, Op,
1822 TheCall->getRParenLoc());
1823
1824 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1825 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1826 Context.AtomicUsesUnsupportedLibcall(AE))
1827 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1828 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001829
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001830 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001831}
1832
1833
John McCall29ad95b2011-08-27 01:09:30 +00001834/// checkBuiltinArgument - Given a call to a builtin function, perform
1835/// normal type-checking on the given argument, updating the call in
1836/// place. This is useful when a builtin function requires custom
1837/// type-checking for some of its arguments but not necessarily all of
1838/// them.
1839///
1840/// Returns true on error.
1841static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1842 FunctionDecl *Fn = E->getDirectCallee();
1843 assert(Fn && "builtin call without direct callee!");
1844
1845 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1846 InitializedEntity Entity =
1847 InitializedEntity::InitializeParameter(S.Context, Param);
1848
1849 ExprResult Arg = E->getArg(0);
1850 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1851 if (Arg.isInvalid())
1852 return true;
1853
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001854 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001855 return false;
1856}
1857
Chris Lattnerdc046542009-05-08 06:58:22 +00001858/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1859/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1860/// type of its first argument. The main ActOnCallExpr routines have already
1861/// promoted the types of arguments because all of these calls are prototyped as
1862/// void(...).
1863///
1864/// This function goes through and does final semantic checking for these
1865/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001866ExprResult
1867Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001868 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001869 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1870 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1871
1872 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001873 if (TheCall->getNumArgs() < 1) {
1874 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1875 << 0 << 1 << TheCall->getNumArgs()
1876 << TheCall->getCallee()->getSourceRange();
1877 return ExprError();
1878 }
Mike Stump11289f42009-09-09 15:08:12 +00001879
Chris Lattnerdc046542009-05-08 06:58:22 +00001880 // Inspect the first argument of the atomic builtin. This should always be
1881 // a pointer type, whose element is an integral scalar or pointer type.
1882 // Because it is a pointer type, we don't have to worry about any implicit
1883 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001884 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001885 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001886 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1887 if (FirstArgResult.isInvalid())
1888 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001889 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001890 TheCall->setArg(0, FirstArg);
1891
John McCall31168b02011-06-15 23:02:42 +00001892 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1893 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001894 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1895 << FirstArg->getType() << FirstArg->getSourceRange();
1896 return ExprError();
1897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
John McCall31168b02011-06-15 23:02:42 +00001899 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001900 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001901 !ValType->isBlockPointerType()) {
1902 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1903 << FirstArg->getType() << FirstArg->getSourceRange();
1904 return ExprError();
1905 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001906
John McCall31168b02011-06-15 23:02:42 +00001907 switch (ValType.getObjCLifetime()) {
1908 case Qualifiers::OCL_None:
1909 case Qualifiers::OCL_ExplicitNone:
1910 // okay
1911 break;
1912
1913 case Qualifiers::OCL_Weak:
1914 case Qualifiers::OCL_Strong:
1915 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001916 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001917 << ValType << FirstArg->getSourceRange();
1918 return ExprError();
1919 }
1920
John McCallb50451a2011-10-05 07:41:44 +00001921 // Strip any qualifiers off ValType.
1922 ValType = ValType.getUnqualifiedType();
1923
Chandler Carruth3973af72010-07-18 20:54:12 +00001924 // The majority of builtins return a value, but a few have special return
1925 // types, so allow them to override appropriately below.
1926 QualType ResultType = ValType;
1927
Chris Lattnerdc046542009-05-08 06:58:22 +00001928 // We need to figure out which concrete builtin this maps onto. For example,
1929 // __sync_fetch_and_add with a 2 byte object turns into
1930 // __sync_fetch_and_add_2.
1931#define BUILTIN_ROW(x) \
1932 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1933 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001934
Chris Lattnerdc046542009-05-08 06:58:22 +00001935 static const unsigned BuiltinIndices[][5] = {
1936 BUILTIN_ROW(__sync_fetch_and_add),
1937 BUILTIN_ROW(__sync_fetch_and_sub),
1938 BUILTIN_ROW(__sync_fetch_and_or),
1939 BUILTIN_ROW(__sync_fetch_and_and),
1940 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001941 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001942
Chris Lattnerdc046542009-05-08 06:58:22 +00001943 BUILTIN_ROW(__sync_add_and_fetch),
1944 BUILTIN_ROW(__sync_sub_and_fetch),
1945 BUILTIN_ROW(__sync_and_and_fetch),
1946 BUILTIN_ROW(__sync_or_and_fetch),
1947 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001948 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001949
Chris Lattnerdc046542009-05-08 06:58:22 +00001950 BUILTIN_ROW(__sync_val_compare_and_swap),
1951 BUILTIN_ROW(__sync_bool_compare_and_swap),
1952 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001953 BUILTIN_ROW(__sync_lock_release),
1954 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001955 };
Mike Stump11289f42009-09-09 15:08:12 +00001956#undef BUILTIN_ROW
1957
Chris Lattnerdc046542009-05-08 06:58:22 +00001958 // Determine the index of the size.
1959 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001960 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001961 case 1: SizeIndex = 0; break;
1962 case 2: SizeIndex = 1; break;
1963 case 4: SizeIndex = 2; break;
1964 case 8: SizeIndex = 3; break;
1965 case 16: SizeIndex = 4; break;
1966 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001967 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1968 << FirstArg->getType() << FirstArg->getSourceRange();
1969 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001970 }
Mike Stump11289f42009-09-09 15:08:12 +00001971
Chris Lattnerdc046542009-05-08 06:58:22 +00001972 // Each of these builtins has one pointer argument, followed by some number of
1973 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1974 // that we ignore. Find out which row of BuiltinIndices to read from as well
1975 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001976 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001977 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001978 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001979 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001980 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001981 case Builtin::BI__sync_fetch_and_add:
1982 case Builtin::BI__sync_fetch_and_add_1:
1983 case Builtin::BI__sync_fetch_and_add_2:
1984 case Builtin::BI__sync_fetch_and_add_4:
1985 case Builtin::BI__sync_fetch_and_add_8:
1986 case Builtin::BI__sync_fetch_and_add_16:
1987 BuiltinIndex = 0;
1988 break;
1989
1990 case Builtin::BI__sync_fetch_and_sub:
1991 case Builtin::BI__sync_fetch_and_sub_1:
1992 case Builtin::BI__sync_fetch_and_sub_2:
1993 case Builtin::BI__sync_fetch_and_sub_4:
1994 case Builtin::BI__sync_fetch_and_sub_8:
1995 case Builtin::BI__sync_fetch_and_sub_16:
1996 BuiltinIndex = 1;
1997 break;
1998
1999 case Builtin::BI__sync_fetch_and_or:
2000 case Builtin::BI__sync_fetch_and_or_1:
2001 case Builtin::BI__sync_fetch_and_or_2:
2002 case Builtin::BI__sync_fetch_and_or_4:
2003 case Builtin::BI__sync_fetch_and_or_8:
2004 case Builtin::BI__sync_fetch_and_or_16:
2005 BuiltinIndex = 2;
2006 break;
2007
2008 case Builtin::BI__sync_fetch_and_and:
2009 case Builtin::BI__sync_fetch_and_and_1:
2010 case Builtin::BI__sync_fetch_and_and_2:
2011 case Builtin::BI__sync_fetch_and_and_4:
2012 case Builtin::BI__sync_fetch_and_and_8:
2013 case Builtin::BI__sync_fetch_and_and_16:
2014 BuiltinIndex = 3;
2015 break;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Douglas Gregor73722482011-11-28 16:30:08 +00002017 case Builtin::BI__sync_fetch_and_xor:
2018 case Builtin::BI__sync_fetch_and_xor_1:
2019 case Builtin::BI__sync_fetch_and_xor_2:
2020 case Builtin::BI__sync_fetch_and_xor_4:
2021 case Builtin::BI__sync_fetch_and_xor_8:
2022 case Builtin::BI__sync_fetch_and_xor_16:
2023 BuiltinIndex = 4;
2024 break;
2025
Hal Finkeld2208b52014-10-02 20:53:50 +00002026 case Builtin::BI__sync_fetch_and_nand:
2027 case Builtin::BI__sync_fetch_and_nand_1:
2028 case Builtin::BI__sync_fetch_and_nand_2:
2029 case Builtin::BI__sync_fetch_and_nand_4:
2030 case Builtin::BI__sync_fetch_and_nand_8:
2031 case Builtin::BI__sync_fetch_and_nand_16:
2032 BuiltinIndex = 5;
2033 WarnAboutSemanticsChange = true;
2034 break;
2035
Douglas Gregor73722482011-11-28 16:30:08 +00002036 case Builtin::BI__sync_add_and_fetch:
2037 case Builtin::BI__sync_add_and_fetch_1:
2038 case Builtin::BI__sync_add_and_fetch_2:
2039 case Builtin::BI__sync_add_and_fetch_4:
2040 case Builtin::BI__sync_add_and_fetch_8:
2041 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002042 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002043 break;
2044
2045 case Builtin::BI__sync_sub_and_fetch:
2046 case Builtin::BI__sync_sub_and_fetch_1:
2047 case Builtin::BI__sync_sub_and_fetch_2:
2048 case Builtin::BI__sync_sub_and_fetch_4:
2049 case Builtin::BI__sync_sub_and_fetch_8:
2050 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002051 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002052 break;
2053
2054 case Builtin::BI__sync_and_and_fetch:
2055 case Builtin::BI__sync_and_and_fetch_1:
2056 case Builtin::BI__sync_and_and_fetch_2:
2057 case Builtin::BI__sync_and_and_fetch_4:
2058 case Builtin::BI__sync_and_and_fetch_8:
2059 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002060 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002061 break;
2062
2063 case Builtin::BI__sync_or_and_fetch:
2064 case Builtin::BI__sync_or_and_fetch_1:
2065 case Builtin::BI__sync_or_and_fetch_2:
2066 case Builtin::BI__sync_or_and_fetch_4:
2067 case Builtin::BI__sync_or_and_fetch_8:
2068 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002069 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002070 break;
2071
2072 case Builtin::BI__sync_xor_and_fetch:
2073 case Builtin::BI__sync_xor_and_fetch_1:
2074 case Builtin::BI__sync_xor_and_fetch_2:
2075 case Builtin::BI__sync_xor_and_fetch_4:
2076 case Builtin::BI__sync_xor_and_fetch_8:
2077 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002078 BuiltinIndex = 10;
2079 break;
2080
2081 case Builtin::BI__sync_nand_and_fetch:
2082 case Builtin::BI__sync_nand_and_fetch_1:
2083 case Builtin::BI__sync_nand_and_fetch_2:
2084 case Builtin::BI__sync_nand_and_fetch_4:
2085 case Builtin::BI__sync_nand_and_fetch_8:
2086 case Builtin::BI__sync_nand_and_fetch_16:
2087 BuiltinIndex = 11;
2088 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002089 break;
Mike Stump11289f42009-09-09 15:08:12 +00002090
Chris Lattnerdc046542009-05-08 06:58:22 +00002091 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002092 case Builtin::BI__sync_val_compare_and_swap_1:
2093 case Builtin::BI__sync_val_compare_and_swap_2:
2094 case Builtin::BI__sync_val_compare_and_swap_4:
2095 case Builtin::BI__sync_val_compare_and_swap_8:
2096 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002097 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002098 NumFixed = 2;
2099 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002100
Chris Lattnerdc046542009-05-08 06:58:22 +00002101 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002102 case Builtin::BI__sync_bool_compare_and_swap_1:
2103 case Builtin::BI__sync_bool_compare_and_swap_2:
2104 case Builtin::BI__sync_bool_compare_and_swap_4:
2105 case Builtin::BI__sync_bool_compare_and_swap_8:
2106 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002107 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002108 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002109 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002110 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002111
2112 case Builtin::BI__sync_lock_test_and_set:
2113 case Builtin::BI__sync_lock_test_and_set_1:
2114 case Builtin::BI__sync_lock_test_and_set_2:
2115 case Builtin::BI__sync_lock_test_and_set_4:
2116 case Builtin::BI__sync_lock_test_and_set_8:
2117 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002118 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002119 break;
2120
Chris Lattnerdc046542009-05-08 06:58:22 +00002121 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002122 case Builtin::BI__sync_lock_release_1:
2123 case Builtin::BI__sync_lock_release_2:
2124 case Builtin::BI__sync_lock_release_4:
2125 case Builtin::BI__sync_lock_release_8:
2126 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002127 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002128 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002129 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002130 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002131
2132 case Builtin::BI__sync_swap:
2133 case Builtin::BI__sync_swap_1:
2134 case Builtin::BI__sync_swap_2:
2135 case Builtin::BI__sync_swap_4:
2136 case Builtin::BI__sync_swap_8:
2137 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002138 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002139 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002140 }
Mike Stump11289f42009-09-09 15:08:12 +00002141
Chris Lattnerdc046542009-05-08 06:58:22 +00002142 // Now that we know how many fixed arguments we expect, first check that we
2143 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002144 if (TheCall->getNumArgs() < 1+NumFixed) {
2145 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2146 << 0 << 1+NumFixed << TheCall->getNumArgs()
2147 << TheCall->getCallee()->getSourceRange();
2148 return ExprError();
2149 }
Mike Stump11289f42009-09-09 15:08:12 +00002150
Hal Finkeld2208b52014-10-02 20:53:50 +00002151 if (WarnAboutSemanticsChange) {
2152 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2153 << TheCall->getCallee()->getSourceRange();
2154 }
2155
Chris Lattner5b9241b2009-05-08 15:36:58 +00002156 // Get the decl for the concrete builtin from this, we can tell what the
2157 // concrete integer type we should convert to is.
2158 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002159 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002160 FunctionDecl *NewBuiltinDecl;
2161 if (NewBuiltinID == BuiltinID)
2162 NewBuiltinDecl = FDecl;
2163 else {
2164 // Perform builtin lookup to avoid redeclaring it.
2165 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2166 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2167 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2168 assert(Res.getFoundDecl());
2169 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002170 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002171 return ExprError();
2172 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002173
John McCallcf142162010-08-07 06:22:56 +00002174 // The first argument --- the pointer --- has a fixed type; we
2175 // deduce the types of the rest of the arguments accordingly. Walk
2176 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002177 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002178 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002179
Chris Lattnerdc046542009-05-08 06:58:22 +00002180 // GCC does an implicit conversion to the pointer or integer ValType. This
2181 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002182 // Initialize the argument.
2183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2184 ValType, /*consume*/ false);
2185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002186 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002187 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattnerdc046542009-05-08 06:58:22 +00002189 // Okay, we have something that *can* be converted to the right type. Check
2190 // to see if there is a potentially weird extension going on here. This can
2191 // happen when you do an atomic operation on something like an char* and
2192 // pass in 42. The 42 gets converted to char. This is even more strange
2193 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002194 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002195 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002198 ASTContext& Context = this->getASTContext();
2199
2200 // Create a new DeclRefExpr to refer to the new decl.
2201 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2202 Context,
2203 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002204 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002205 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002206 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002207 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002208 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002209 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerdc046542009-05-08 06:58:22 +00002211 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002212 // FIXME: This loses syntactic information.
2213 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2214 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2215 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002216 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002217
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002218 // Change the result type of the call to match the original value type. This
2219 // is arbitrary, but the codegen for these builtins ins design to handle it
2220 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002221 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002222
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002223 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002224}
2225
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002226/// SemaBuiltinNontemporalOverloaded - We have a call to
2227/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2228/// overloaded function based on the pointer type of its last argument.
2229///
2230/// This function goes through and does final semantic checking for these
2231/// builtins.
2232ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2233 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2234 DeclRefExpr *DRE =
2235 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2236 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2237 unsigned BuiltinID = FDecl->getBuiltinID();
2238 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2239 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2240 "Unexpected nontemporal load/store builtin!");
2241 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2242 unsigned numArgs = isStore ? 2 : 1;
2243
2244 // Ensure that we have the proper number of arguments.
2245 if (checkArgCount(*this, TheCall, numArgs))
2246 return ExprError();
2247
2248 // Inspect the last argument of the nontemporal builtin. This should always
2249 // be a pointer type, from which we imply the type of the memory access.
2250 // Because it is a pointer type, we don't have to worry about any implicit
2251 // casts here.
2252 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2253 ExprResult PointerArgResult =
2254 DefaultFunctionArrayLvalueConversion(PointerArg);
2255
2256 if (PointerArgResult.isInvalid())
2257 return ExprError();
2258 PointerArg = PointerArgResult.get();
2259 TheCall->setArg(numArgs - 1, PointerArg);
2260
2261 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2262 if (!pointerType) {
2263 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2264 << PointerArg->getType() << PointerArg->getSourceRange();
2265 return ExprError();
2266 }
2267
2268 QualType ValType = pointerType->getPointeeType();
2269
2270 // Strip any qualifiers off ValType.
2271 ValType = ValType.getUnqualifiedType();
2272 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2273 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2274 !ValType->isVectorType()) {
2275 Diag(DRE->getLocStart(),
2276 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2277 << PointerArg->getType() << PointerArg->getSourceRange();
2278 return ExprError();
2279 }
2280
2281 if (!isStore) {
2282 TheCall->setType(ValType);
2283 return TheCallResult;
2284 }
2285
2286 ExprResult ValArg = TheCall->getArg(0);
2287 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2288 Context, ValType, /*consume*/ false);
2289 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2290 if (ValArg.isInvalid())
2291 return ExprError();
2292
2293 TheCall->setArg(0, ValArg.get());
2294 TheCall->setType(Context.VoidTy);
2295 return TheCallResult;
2296}
2297
Chris Lattner6436fb62009-02-18 06:01:06 +00002298/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002299/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002300/// Note: It might also make sense to do the UTF-16 conversion here (would
2301/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002302bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002303 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002304 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2305
Douglas Gregorfb65e592011-07-27 05:40:30 +00002306 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002307 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2308 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002309 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002310 }
Mike Stump11289f42009-09-09 15:08:12 +00002311
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002312 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002313 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002314 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002315 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002316 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002317 UTF16 *ToPtr = &ToBuf[0];
2318
2319 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2320 &ToPtr, ToPtr + NumBytes,
2321 strictConversion);
2322 // Check for conversion failure.
2323 if (Result != conversionOK)
2324 Diag(Arg->getLocStart(),
2325 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2326 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002327 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002328}
2329
Charles Davisc7d5c942015-09-17 20:55:33 +00002330/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2331/// for validity. Emit an error and return true on failure; return false
2332/// on success.
2333bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002334 Expr *Fn = TheCall->getCallee();
2335 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002336 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002337 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002338 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2339 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002340 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002341 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002342 return true;
2343 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002344
2345 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002346 return Diag(TheCall->getLocEnd(),
2347 diag::err_typecheck_call_too_few_args_at_least)
2348 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002349 }
2350
John McCall29ad95b2011-08-27 01:09:30 +00002351 // Type-check the first argument normally.
2352 if (checkBuiltinArgument(*this, TheCall, 0))
2353 return true;
2354
Chris Lattnere202e6a2007-12-20 00:05:45 +00002355 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002356 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002357 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002358 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002359 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002360 else if (FunctionDecl *FD = getCurFunctionDecl())
2361 isVariadic = FD->isVariadic();
2362 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002363 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002364
Chris Lattnere202e6a2007-12-20 00:05:45 +00002365 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002366 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2367 return true;
2368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Chris Lattner43be2e62007-12-19 23:59:04 +00002370 // Verify that the second argument to the builtin is the last argument of the
2371 // current function or method.
2372 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002373 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002374
Nico Weber9eea7642013-05-24 23:31:57 +00002375 // These are valid if SecondArgIsLastNamedArgument is false after the next
2376 // block.
2377 QualType Type;
2378 SourceLocation ParamLoc;
2379
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002380 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2381 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002382 // FIXME: This isn't correct for methods (results in bogus warning).
2383 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002384 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002385 if (CurBlock)
2386 LastArg = *(CurBlock->TheDecl->param_end()-1);
2387 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002388 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002389 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002390 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002391 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002392
2393 Type = PV->getType();
2394 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002395 }
2396 }
Mike Stump11289f42009-09-09 15:08:12 +00002397
Chris Lattner43be2e62007-12-19 23:59:04 +00002398 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002399 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002400 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002401 else if (Type->isReferenceType()) {
2402 Diag(Arg->getLocStart(),
2403 diag::warn_va_start_of_reference_type_is_undefined);
2404 Diag(ParamLoc, diag::note_parameter_type) << Type;
2405 }
2406
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002407 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002408 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002409}
Chris Lattner43be2e62007-12-19 23:59:04 +00002410
Charles Davisc7d5c942015-09-17 20:55:33 +00002411/// Check the arguments to '__builtin_va_start' for validity, and that
2412/// it was called from a function of the native ABI.
2413/// Emit an error and return true on failure; return false on success.
2414bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2415 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2416 // On x64 Windows, don't allow this in System V ABI functions.
2417 // (Yes, that means there's no corresponding way to support variadic
2418 // System V ABI functions on Windows.)
2419 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2420 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2421 clang::CallingConv CC = CC_C;
2422 if (const FunctionDecl *FD = getCurFunctionDecl())
2423 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2424 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2425 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2426 return Diag(TheCall->getCallee()->getLocStart(),
2427 diag::err_va_start_used_in_wrong_abi_function)
2428 << (OS != llvm::Triple::Win32);
2429 }
2430 return SemaBuiltinVAStartImpl(TheCall);
2431}
2432
2433/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2434/// it was called from a Win64 ABI function.
2435/// Emit an error and return true on failure; return false on success.
2436bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2437 // This only makes sense for x86-64.
2438 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2439 Expr *Callee = TheCall->getCallee();
2440 if (TT.getArch() != llvm::Triple::x86_64)
2441 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2442 // Don't allow this in System V ABI functions.
2443 clang::CallingConv CC = CC_C;
2444 if (const FunctionDecl *FD = getCurFunctionDecl())
2445 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2446 if (CC == CC_X86_64SysV ||
2447 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2448 return Diag(Callee->getLocStart(),
2449 diag::err_ms_va_start_used_in_sysv_function);
2450 return SemaBuiltinVAStartImpl(TheCall);
2451}
2452
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002453bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2454 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2455 // const char *named_addr);
2456
2457 Expr *Func = Call->getCallee();
2458
2459 if (Call->getNumArgs() < 3)
2460 return Diag(Call->getLocEnd(),
2461 diag::err_typecheck_call_too_few_args_at_least)
2462 << 0 /*function call*/ << 3 << Call->getNumArgs();
2463
2464 // Determine whether the current function is variadic or not.
2465 bool IsVariadic;
2466 if (BlockScopeInfo *CurBlock = getCurBlock())
2467 IsVariadic = CurBlock->TheDecl->isVariadic();
2468 else if (FunctionDecl *FD = getCurFunctionDecl())
2469 IsVariadic = FD->isVariadic();
2470 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2471 IsVariadic = MD->isVariadic();
2472 else
2473 llvm_unreachable("unexpected statement type");
2474
2475 if (!IsVariadic) {
2476 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2477 return true;
2478 }
2479
2480 // Type-check the first argument normally.
2481 if (checkBuiltinArgument(*this, Call, 0))
2482 return true;
2483
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002484 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002485 unsigned ArgNo;
2486 QualType Type;
2487 } ArgumentTypes[] = {
2488 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2489 { 2, Context.getSizeType() },
2490 };
2491
2492 for (const auto &AT : ArgumentTypes) {
2493 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2494 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2495 continue;
2496 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2497 << Arg->getType() << AT.Type << 1 /* different class */
2498 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2499 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2500 }
2501
2502 return false;
2503}
2504
Chris Lattner2da14fb2007-12-20 00:26:33 +00002505/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2506/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002507bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2508 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002509 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002510 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002511 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002512 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002513 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002514 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002515 << SourceRange(TheCall->getArg(2)->getLocStart(),
2516 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002517
John Wiegley01296292011-04-08 18:41:53 +00002518 ExprResult OrigArg0 = TheCall->getArg(0);
2519 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002520
Chris Lattner2da14fb2007-12-20 00:26:33 +00002521 // Do standard promotions between the two arguments, returning their common
2522 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002523 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002524 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2525 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002526
2527 // Make sure any conversions are pushed back into the call; this is
2528 // type safe since unordered compare builtins are declared as "_Bool
2529 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002530 TheCall->setArg(0, OrigArg0.get());
2531 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002532
John Wiegley01296292011-04-08 18:41:53 +00002533 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002534 return false;
2535
Chris Lattner2da14fb2007-12-20 00:26:33 +00002536 // If the common type isn't a real floating type, then the arguments were
2537 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002538 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002539 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002540 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002541 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2542 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002543
Chris Lattner2da14fb2007-12-20 00:26:33 +00002544 return false;
2545}
2546
Benjamin Kramer634fc102010-02-15 22:42:31 +00002547/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2548/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002549/// to check everything. We expect the last argument to be a floating point
2550/// value.
2551bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2552 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002553 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002554 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002555 if (TheCall->getNumArgs() > NumArgs)
2556 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002557 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002558 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002559 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002560 (*(TheCall->arg_end()-1))->getLocEnd());
2561
Benjamin Kramer64aae502010-02-16 10:07:31 +00002562 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002563
Eli Friedman7e4faac2009-08-31 20:06:00 +00002564 if (OrigArg->isTypeDependent())
2565 return false;
2566
Chris Lattner68784ef2010-05-06 05:50:07 +00002567 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002568 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002569 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002570 diag::err_typecheck_call_invalid_unary_fp)
2571 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002572
Chris Lattner68784ef2010-05-06 05:50:07 +00002573 // If this is an implicit conversion from float -> double, remove it.
2574 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2575 Expr *CastArg = Cast->getSubExpr();
2576 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2577 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2578 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002579 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002580 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002581 }
2582 }
2583
Eli Friedman7e4faac2009-08-31 20:06:00 +00002584 return false;
2585}
2586
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002587/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2588// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002589ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002590 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002591 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002592 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002593 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2594 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002595
Nate Begemana0110022010-06-08 00:16:34 +00002596 // Determine which of the following types of shufflevector we're checking:
2597 // 1) unary, vector mask: (lhs, mask)
2598 // 2) binary, vector mask: (lhs, rhs, mask)
2599 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2600 QualType resType = TheCall->getArg(0)->getType();
2601 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002602
Douglas Gregorc25f7662009-05-19 22:10:17 +00002603 if (!TheCall->getArg(0)->isTypeDependent() &&
2604 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002605 QualType LHSType = TheCall->getArg(0)->getType();
2606 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002607
Craig Topperbaca3892013-07-29 06:47:04 +00002608 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2609 return ExprError(Diag(TheCall->getLocStart(),
2610 diag::err_shufflevector_non_vector)
2611 << SourceRange(TheCall->getArg(0)->getLocStart(),
2612 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002613
Nate Begemana0110022010-06-08 00:16:34 +00002614 numElements = LHSType->getAs<VectorType>()->getNumElements();
2615 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002616
Nate Begemana0110022010-06-08 00:16:34 +00002617 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2618 // with mask. If so, verify that RHS is an integer vector type with the
2619 // same number of elts as lhs.
2620 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002621 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002622 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002623 return ExprError(Diag(TheCall->getLocStart(),
2624 diag::err_shufflevector_incompatible_vector)
2625 << SourceRange(TheCall->getArg(1)->getLocStart(),
2626 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002627 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002628 return ExprError(Diag(TheCall->getLocStart(),
2629 diag::err_shufflevector_incompatible_vector)
2630 << SourceRange(TheCall->getArg(0)->getLocStart(),
2631 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002632 } else if (numElements != numResElements) {
2633 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002634 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002635 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002636 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002637 }
2638
2639 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002640 if (TheCall->getArg(i)->isTypeDependent() ||
2641 TheCall->getArg(i)->isValueDependent())
2642 continue;
2643
Nate Begemana0110022010-06-08 00:16:34 +00002644 llvm::APSInt Result(32);
2645 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2646 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002647 diag::err_shufflevector_nonconstant_argument)
2648 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002649
Craig Topper50ad5b72013-08-03 17:40:38 +00002650 // Allow -1 which will be translated to undef in the IR.
2651 if (Result.isSigned() && Result.isAllOnesValue())
2652 continue;
2653
Chris Lattner7ab824e2008-08-10 02:05:13 +00002654 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002655 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002656 diag::err_shufflevector_argument_too_large)
2657 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002658 }
2659
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002660 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002661
Chris Lattner7ab824e2008-08-10 02:05:13 +00002662 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002663 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002664 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002665 }
2666
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002667 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2668 TheCall->getCallee()->getLocStart(),
2669 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002670}
Chris Lattner43be2e62007-12-19 23:59:04 +00002671
Hal Finkelc4d7c822013-09-18 03:29:45 +00002672/// SemaConvertVectorExpr - Handle __builtin_convertvector
2673ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2674 SourceLocation BuiltinLoc,
2675 SourceLocation RParenLoc) {
2676 ExprValueKind VK = VK_RValue;
2677 ExprObjectKind OK = OK_Ordinary;
2678 QualType DstTy = TInfo->getType();
2679 QualType SrcTy = E->getType();
2680
2681 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2682 return ExprError(Diag(BuiltinLoc,
2683 diag::err_convertvector_non_vector)
2684 << E->getSourceRange());
2685 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2686 return ExprError(Diag(BuiltinLoc,
2687 diag::err_convertvector_non_vector_type));
2688
2689 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2690 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2691 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2692 if (SrcElts != DstElts)
2693 return ExprError(Diag(BuiltinLoc,
2694 diag::err_convertvector_incompatible_vector)
2695 << E->getSourceRange());
2696 }
2697
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002698 return new (Context)
2699 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002700}
2701
Daniel Dunbarb7257262008-07-21 22:59:13 +00002702/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2703// This is declared to take (const void*, ...) and can take two
2704// optional constant int args.
2705bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002706 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002707
Chris Lattner3b054132008-11-19 05:08:23 +00002708 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002709 return Diag(TheCall->getLocEnd(),
2710 diag::err_typecheck_call_too_many_args_at_most)
2711 << 0 /*function call*/ << 3 << NumArgs
2712 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002713
2714 // Argument 0 is checked for us and the remaining arguments must be
2715 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002716 for (unsigned i = 1; i != NumArgs; ++i)
2717 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002718 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002719
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002720 return false;
2721}
2722
Hal Finkelf0417332014-07-17 14:25:55 +00002723/// SemaBuiltinAssume - Handle __assume (MS Extension).
2724// __assume does not evaluate its arguments, and should warn if its argument
2725// has side effects.
2726bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2727 Expr *Arg = TheCall->getArg(0);
2728 if (Arg->isInstantiationDependent()) return false;
2729
2730 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002731 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002732 << Arg->getSourceRange()
2733 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2734
2735 return false;
2736}
2737
2738/// Handle __builtin_assume_aligned. This is declared
2739/// as (const void*, size_t, ...) and can take one optional constant int arg.
2740bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2741 unsigned NumArgs = TheCall->getNumArgs();
2742
2743 if (NumArgs > 3)
2744 return Diag(TheCall->getLocEnd(),
2745 diag::err_typecheck_call_too_many_args_at_most)
2746 << 0 /*function call*/ << 3 << NumArgs
2747 << TheCall->getSourceRange();
2748
2749 // The alignment must be a constant integer.
2750 Expr *Arg = TheCall->getArg(1);
2751
2752 // We can't check the value of a dependent argument.
2753 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2754 llvm::APSInt Result;
2755 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2756 return true;
2757
2758 if (!Result.isPowerOf2())
2759 return Diag(TheCall->getLocStart(),
2760 diag::err_alignment_not_power_of_two)
2761 << Arg->getSourceRange();
2762 }
2763
2764 if (NumArgs > 2) {
2765 ExprResult Arg(TheCall->getArg(2));
2766 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2767 Context.getSizeType(), false);
2768 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2769 if (Arg.isInvalid()) return true;
2770 TheCall->setArg(2, Arg.get());
2771 }
Hal Finkelf0417332014-07-17 14:25:55 +00002772
2773 return false;
2774}
2775
Eric Christopher8d0c6212010-04-17 02:26:23 +00002776/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2777/// TheCall is a constant expression.
2778bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2779 llvm::APSInt &Result) {
2780 Expr *Arg = TheCall->getArg(ArgNum);
2781 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2782 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2783
2784 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2785
2786 if (!Arg->isIntegerConstantExpr(Result, Context))
2787 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002788 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002789
Chris Lattnerd545ad12009-09-23 06:06:36 +00002790 return false;
2791}
2792
Richard Sandiford28940af2014-04-16 08:47:51 +00002793/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2794/// TheCall is a constant expression in the range [Low, High].
2795bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2796 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002797 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002798
2799 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002800 Expr *Arg = TheCall->getArg(ArgNum);
2801 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002802 return false;
2803
Eric Christopher8d0c6212010-04-17 02:26:23 +00002804 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002805 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002806 return true;
2807
Richard Sandiford28940af2014-04-16 08:47:51 +00002808 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002809 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002810 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002811
2812 return false;
2813}
2814
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002815/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2816/// TheCall is an ARM/AArch64 special register string literal.
2817bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2818 int ArgNum, unsigned ExpectedFieldNum,
2819 bool AllowName) {
2820 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2821 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2822 BuiltinID == ARM::BI__builtin_arm_rsr ||
2823 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2824 BuiltinID == ARM::BI__builtin_arm_wsr ||
2825 BuiltinID == ARM::BI__builtin_arm_wsrp;
2826 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2827 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2828 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2829 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2830 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2831 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2832 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2833
2834 // We can't check the value of a dependent argument.
2835 Expr *Arg = TheCall->getArg(ArgNum);
2836 if (Arg->isTypeDependent() || Arg->isValueDependent())
2837 return false;
2838
2839 // Check if the argument is a string literal.
2840 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2841 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2842 << Arg->getSourceRange();
2843
2844 // Check the type of special register given.
2845 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2846 SmallVector<StringRef, 6> Fields;
2847 Reg.split(Fields, ":");
2848
2849 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2850 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2851 << Arg->getSourceRange();
2852
2853 // If the string is the name of a register then we cannot check that it is
2854 // valid here but if the string is of one the forms described in ACLE then we
2855 // can check that the supplied fields are integers and within the valid
2856 // ranges.
2857 if (Fields.size() > 1) {
2858 bool FiveFields = Fields.size() == 5;
2859
2860 bool ValidString = true;
2861 if (IsARMBuiltin) {
2862 ValidString &= Fields[0].startswith_lower("cp") ||
2863 Fields[0].startswith_lower("p");
2864 if (ValidString)
2865 Fields[0] =
2866 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2867
2868 ValidString &= Fields[2].startswith_lower("c");
2869 if (ValidString)
2870 Fields[2] = Fields[2].drop_front(1);
2871
2872 if (FiveFields) {
2873 ValidString &= Fields[3].startswith_lower("c");
2874 if (ValidString)
2875 Fields[3] = Fields[3].drop_front(1);
2876 }
2877 }
2878
2879 SmallVector<int, 5> Ranges;
2880 if (FiveFields)
2881 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2882 else
2883 Ranges.append({15, 7, 15});
2884
2885 for (unsigned i=0; i<Fields.size(); ++i) {
2886 int IntField;
2887 ValidString &= !Fields[i].getAsInteger(10, IntField);
2888 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2889 }
2890
2891 if (!ValidString)
2892 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2893 << Arg->getSourceRange();
2894
2895 } else if (IsAArch64Builtin && Fields.size() == 1) {
2896 // If the register name is one of those that appear in the condition below
2897 // and the special register builtin being used is one of the write builtins,
2898 // then we require that the argument provided for writing to the register
2899 // is an integer constant expression. This is because it will be lowered to
2900 // an MSR (immediate) instruction, so we need to know the immediate at
2901 // compile time.
2902 if (TheCall->getNumArgs() != 2)
2903 return false;
2904
2905 std::string RegLower = Reg.lower();
2906 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2907 RegLower != "pan" && RegLower != "uao")
2908 return false;
2909
2910 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2911 }
2912
2913 return false;
2914}
2915
Eric Christopherd9832702015-06-29 21:00:05 +00002916/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2917/// This checks that the target supports __builtin_cpu_supports and
2918/// that the string argument is constant and valid.
2919bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2920 Expr *Arg = TheCall->getArg(0);
2921
2922 // Check if the argument is a string literal.
2923 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2924 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2925 << Arg->getSourceRange();
2926
2927 // Check the contents of the string.
2928 StringRef Feature =
2929 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2930 if (!Context.getTargetInfo().validateCpuSupports(Feature))
2931 return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2932 << Arg->getSourceRange();
2933 return false;
2934}
2935
Eli Friedmanc97d0142009-05-03 06:04:26 +00002936/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002937/// This checks that the target supports __builtin_longjmp and
2938/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002939bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002940 if (!Context.getTargetInfo().hasSjLjLowering())
2941 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2942 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2943
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002944 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002945 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002946
Eric Christopher8d0c6212010-04-17 02:26:23 +00002947 // TODO: This is less than ideal. Overload this to take a value.
2948 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2949 return true;
2950
2951 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002952 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2953 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2954
2955 return false;
2956}
2957
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002958
2959/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2960/// This checks that the target supports __builtin_setjmp.
2961bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2962 if (!Context.getTargetInfo().hasSjLjLowering())
2963 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2964 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2965 return false;
2966}
2967
Richard Smithd7293d72013-08-05 18:49:43 +00002968namespace {
2969enum StringLiteralCheckType {
2970 SLCT_NotALiteral,
2971 SLCT_UncheckedLiteral,
2972 SLCT_CheckedLiteral
2973};
2974}
2975
Richard Smith55ce3522012-06-25 20:30:08 +00002976// Determine if an expression is a string literal or constant string.
2977// If this function returns false on the arguments to a function expecting a
2978// format string, we will usually need to emit a warning.
2979// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002980static StringLiteralCheckType
2981checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2982 bool HasVAListArg, unsigned format_idx,
2983 unsigned firstDataArg, Sema::FormatStringType Type,
2984 Sema::VariadicCallType CallType, bool InFunctionCall,
2985 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002986 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002987 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002988 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002989
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002990 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002991
Richard Smithd7293d72013-08-05 18:49:43 +00002992 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002993 // Technically -Wformat-nonliteral does not warn about this case.
2994 // The behavior of printf and friends in this case is implementation
2995 // dependent. Ideally if the format string cannot be null then
2996 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002997 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002998
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002999 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003000 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003001 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003002 // The expression is a literal if both sub-expressions were, and it was
3003 // completely checked only if both sub-expressions were checked.
3004 const AbstractConditionalOperator *C =
3005 cast<AbstractConditionalOperator>(E);
3006 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003007 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003008 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003009 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003010 if (Left == SLCT_NotALiteral)
3011 return SLCT_NotALiteral;
3012 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003013 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003014 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003015 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003016 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003017 }
3018
3019 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003020 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3021 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003022 }
3023
John McCallc07a0c72011-02-17 10:25:35 +00003024 case Stmt::OpaqueValueExprClass:
3025 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3026 E = src;
3027 goto tryAgain;
3028 }
Richard Smith55ce3522012-06-25 20:30:08 +00003029 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003030
Ted Kremeneka8890832011-02-24 23:03:04 +00003031 case Stmt::PredefinedExprClass:
3032 // While __func__, etc., are technically not string literals, they
3033 // cannot contain format specifiers and thus are not a security
3034 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003035 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003036
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003037 case Stmt::DeclRefExprClass: {
3038 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003039
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003040 // As an exception, do not flag errors for variables binding to
3041 // const string literals.
3042 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3043 bool isConstant = false;
3044 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003045
Richard Smithd7293d72013-08-05 18:49:43 +00003046 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3047 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003048 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003049 isConstant = T.isConstant(S.Context) &&
3050 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003051 } else if (T->isObjCObjectPointerType()) {
3052 // In ObjC, there is usually no "const ObjectPointer" type,
3053 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003054 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003055 }
Mike Stump11289f42009-09-09 15:08:12 +00003056
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003057 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003058 if (const Expr *Init = VD->getAnyInitializer()) {
3059 // Look through initializers like const char c[] = { "foo" }
3060 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3061 if (InitList->isStringLiteralInit())
3062 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3063 }
Richard Smithd7293d72013-08-05 18:49:43 +00003064 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003065 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003066 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003067 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003068 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003069 }
Mike Stump11289f42009-09-09 15:08:12 +00003070
Anders Carlssonb012ca92009-06-28 19:55:58 +00003071 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3072 // special check to see if the format string is a function parameter
3073 // of the function calling the printf function. If the function
3074 // has an attribute indicating it is a printf-like function, then we
3075 // should suppress warnings concerning non-literals being used in a call
3076 // to a vprintf function. For example:
3077 //
3078 // void
3079 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3080 // va_list ap;
3081 // va_start(ap, fmt);
3082 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3083 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003084 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003085 if (HasVAListArg) {
3086 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3087 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3088 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003089 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003090 // adjust for implicit parameter
3091 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3092 if (MD->isInstance())
3093 ++PVIndex;
3094 // We also check if the formats are compatible.
3095 // We can't pass a 'scanf' string to a 'printf' function.
3096 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003097 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003098 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003099 }
3100 }
3101 }
3102 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003103 }
Mike Stump11289f42009-09-09 15:08:12 +00003104
Richard Smith55ce3522012-06-25 20:30:08 +00003105 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003106 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003107
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003108 case Stmt::CallExprClass:
3109 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003110 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003111 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3112 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3113 unsigned ArgIndex = FA->getFormatIdx();
3114 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3115 if (MD->isInstance())
3116 --ArgIndex;
3117 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003118
Richard Smithd7293d72013-08-05 18:49:43 +00003119 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003120 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003121 Type, CallType, InFunctionCall,
3122 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003123 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3124 unsigned BuiltinID = FD->getBuiltinID();
3125 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3126 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3127 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003128 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003129 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003130 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003131 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003132 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003133 }
3134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
Richard Smith55ce3522012-06-25 20:30:08 +00003136 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003137 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003138 case Stmt::ObjCStringLiteralClass:
3139 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003140 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003142 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003143 StrE = ObjCFExpr->getString();
3144 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003145 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003146
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003147 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003148 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3149 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003150 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003151 }
Mike Stump11289f42009-09-09 15:08:12 +00003152
Richard Smith55ce3522012-06-25 20:30:08 +00003153 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003154 }
Mike Stump11289f42009-09-09 15:08:12 +00003155
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003156 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003157 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003158 }
3159}
3160
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003161Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003162 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003163 .Case("scanf", FST_Scanf)
3164 .Cases("printf", "printf0", FST_Printf)
3165 .Cases("NSString", "CFString", FST_NSString)
3166 .Case("strftime", FST_Strftime)
3167 .Case("strfmon", FST_Strfmon)
3168 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003169 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003170 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003171 .Default(FST_Unknown);
3172}
3173
Jordan Rose3e0ec582012-07-19 18:10:23 +00003174/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003175/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003176/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003177bool Sema::CheckFormatArguments(const FormatAttr *Format,
3178 ArrayRef<const Expr *> Args,
3179 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003180 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003181 SourceLocation Loc, SourceRange Range,
3182 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003183 FormatStringInfo FSI;
3184 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003185 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003186 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003187 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003188 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003189}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003190
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003191bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003192 bool HasVAListArg, unsigned format_idx,
3193 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003194 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003195 SourceLocation Loc, SourceRange Range,
3196 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003197 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003198 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003199 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003200 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003201 }
Mike Stump11289f42009-09-09 15:08:12 +00003202
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003203 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003204
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003205 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003206 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003207 // Dynamically generated format strings are difficult to
3208 // automatically vet at compile time. Requiring that format strings
3209 // are string literals: (1) permits the checking of format strings by
3210 // the compiler and thereby (2) can practically remove the source of
3211 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003212
Mike Stump11289f42009-09-09 15:08:12 +00003213 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003214 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003215 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003216 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003217 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003218 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3219 format_idx, firstDataArg, Type, CallType,
3220 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003221 if (CT != SLCT_NotALiteral)
3222 // Literal format string found, check done!
3223 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003224
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003225 // Strftime is particular as it always uses a single 'time' argument,
3226 // so it is safe to pass a non-literal string.
3227 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003228 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003229
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003230 // Do not emit diag when the string param is a macro expansion and the
3231 // format is either NSString or CFString. This is a hack to prevent
3232 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3233 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003234 if (Type == FST_NSString &&
3235 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003236 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003237
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003238 // If there are no arguments specified, warn with -Wformat-security, otherwise
3239 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003240 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003241 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003242 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003243 << OrigFormatExpr->getSourceRange();
3244 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003245 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003246 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003247 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003248 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003249}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003250
Ted Kremenekab278de2010-01-28 23:39:18 +00003251namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003252class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3253protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003254 Sema &S;
3255 const StringLiteral *FExpr;
3256 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003257 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003258 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003259 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003260 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003261 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003262 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003263 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003264 bool usesPositionalArgs;
3265 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003266 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003267 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003268 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003269public:
Ted Kremenek02087932010-07-16 02:11:22 +00003270 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003271 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003272 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003273 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003274 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003275 Sema::VariadicCallType callType,
3276 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003277 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003278 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3279 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003280 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003281 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003282 inFunctionCall(inFunctionCall), CallType(callType),
3283 CheckedVarArgs(CheckedVarArgs) {
3284 CoveredArgs.resize(numDataArgs);
3285 CoveredArgs.reset();
3286 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003287
Ted Kremenek019d2242010-01-29 01:50:07 +00003288 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003289
Ted Kremenek02087932010-07-16 02:11:22 +00003290 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003291 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003292
Jordan Rose92303592012-09-08 04:00:03 +00003293 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003294 const analyze_format_string::FormatSpecifier &FS,
3295 const analyze_format_string::ConversionSpecifier &CS,
3296 const char *startSpecifier, unsigned specifierLen,
3297 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003298
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003299 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003300 const analyze_format_string::FormatSpecifier &FS,
3301 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003302
3303 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003304 const analyze_format_string::ConversionSpecifier &CS,
3305 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003306
Craig Toppere14c0f82014-03-12 04:55:44 +00003307 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003308
Craig Toppere14c0f82014-03-12 04:55:44 +00003309 void HandleInvalidPosition(const char *startSpecifier,
3310 unsigned specifierLen,
3311 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003312
Craig Toppere14c0f82014-03-12 04:55:44 +00003313 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003314
Craig Toppere14c0f82014-03-12 04:55:44 +00003315 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003316
Richard Trieu03cf7b72011-10-28 00:41:25 +00003317 template <typename Range>
3318 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3319 const Expr *ArgumentExpr,
3320 PartialDiagnostic PDiag,
3321 SourceLocation StringLoc,
3322 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003323 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003324
Ted Kremenek02087932010-07-16 02:11:22 +00003325protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003326 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3327 const char *startSpec,
3328 unsigned specifierLen,
3329 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003330
3331 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3332 const char *startSpec,
3333 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003334
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003335 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003336 CharSourceRange getSpecifierRange(const char *startSpecifier,
3337 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003338 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003339
Ted Kremenek5739de72010-01-29 01:06:55 +00003340 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003341
3342 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3343 const analyze_format_string::ConversionSpecifier &CS,
3344 const char *startSpecifier, unsigned specifierLen,
3345 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003346
3347 template <typename Range>
3348 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3349 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003350 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003351};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003352}
Ted Kremenekab278de2010-01-28 23:39:18 +00003353
Ted Kremenek02087932010-07-16 02:11:22 +00003354SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003355 return OrigFormatExpr->getSourceRange();
3356}
3357
Ted Kremenek02087932010-07-16 02:11:22 +00003358CharSourceRange CheckFormatHandler::
3359getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003360 SourceLocation Start = getLocationOfByte(startSpecifier);
3361 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3362
3363 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003364 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003365
3366 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003367}
3368
Ted Kremenek02087932010-07-16 02:11:22 +00003369SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003370 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003371}
3372
Ted Kremenek02087932010-07-16 02:11:22 +00003373void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3374 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003375 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3376 getLocationOfByte(startSpecifier),
3377 /*IsStringLocation*/true,
3378 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003379}
3380
Jordan Rose92303592012-09-08 04:00:03 +00003381void CheckFormatHandler::HandleInvalidLengthModifier(
3382 const analyze_format_string::FormatSpecifier &FS,
3383 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003384 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003385 using namespace analyze_format_string;
3386
3387 const LengthModifier &LM = FS.getLengthModifier();
3388 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3389
3390 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003391 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003392 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003393 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003394 getLocationOfByte(LM.getStart()),
3395 /*IsStringLocation*/true,
3396 getSpecifierRange(startSpecifier, specifierLen));
3397
3398 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3399 << FixedLM->toString()
3400 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3401
3402 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003403 FixItHint Hint;
3404 if (DiagID == diag::warn_format_nonsensical_length)
3405 Hint = FixItHint::CreateRemoval(LMRange);
3406
3407 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003408 getLocationOfByte(LM.getStart()),
3409 /*IsStringLocation*/true,
3410 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003411 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003412 }
3413}
3414
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003415void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003416 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003417 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003418 using namespace analyze_format_string;
3419
3420 const LengthModifier &LM = FS.getLengthModifier();
3421 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3422
3423 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003424 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003425 if (FixedLM) {
3426 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3427 << LM.toString() << 0,
3428 getLocationOfByte(LM.getStart()),
3429 /*IsStringLocation*/true,
3430 getSpecifierRange(startSpecifier, specifierLen));
3431
3432 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3433 << FixedLM->toString()
3434 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3435
3436 } else {
3437 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3438 << LM.toString() << 0,
3439 getLocationOfByte(LM.getStart()),
3440 /*IsStringLocation*/true,
3441 getSpecifierRange(startSpecifier, specifierLen));
3442 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003443}
3444
3445void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3446 const analyze_format_string::ConversionSpecifier &CS,
3447 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003448 using namespace analyze_format_string;
3449
3450 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003451 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003452 if (FixedCS) {
3453 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3454 << CS.toString() << /*conversion specifier*/1,
3455 getLocationOfByte(CS.getStart()),
3456 /*IsStringLocation*/true,
3457 getSpecifierRange(startSpecifier, specifierLen));
3458
3459 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3460 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3461 << FixedCS->toString()
3462 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3463 } else {
3464 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3465 << CS.toString() << /*conversion specifier*/1,
3466 getLocationOfByte(CS.getStart()),
3467 /*IsStringLocation*/true,
3468 getSpecifierRange(startSpecifier, specifierLen));
3469 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003470}
3471
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003472void CheckFormatHandler::HandlePosition(const char *startPos,
3473 unsigned posLen) {
3474 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3475 getLocationOfByte(startPos),
3476 /*IsStringLocation*/true,
3477 getSpecifierRange(startPos, posLen));
3478}
3479
Ted Kremenekd1668192010-02-27 01:41:03 +00003480void
Ted Kremenek02087932010-07-16 02:11:22 +00003481CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3482 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003483 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3484 << (unsigned) p,
3485 getLocationOfByte(startPos), /*IsStringLocation*/true,
3486 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003487}
3488
Ted Kremenek02087932010-07-16 02:11:22 +00003489void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003490 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003491 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3492 getLocationOfByte(startPos),
3493 /*IsStringLocation*/true,
3494 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003495}
3496
Ted Kremenek02087932010-07-16 02:11:22 +00003497void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003498 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003499 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003500 EmitFormatDiagnostic(
3501 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3502 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3503 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003504 }
Ted Kremenek02087932010-07-16 02:11:22 +00003505}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003506
Jordan Rose58bbe422012-07-19 18:10:08 +00003507// Note that this may return NULL if there was an error parsing or building
3508// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003509const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003510 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003511}
3512
3513void CheckFormatHandler::DoneProcessing() {
3514 // Does the number of data arguments exceed the number of
3515 // format conversions in the format string?
3516 if (!HasVAListArg) {
3517 // Find any arguments that weren't covered.
3518 CoveredArgs.flip();
3519 signed notCoveredArg = CoveredArgs.find_first();
3520 if (notCoveredArg >= 0) {
3521 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003522 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3523 SourceLocation Loc = E->getLocStart();
3524 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3525 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3526 Loc, /*IsStringLocation*/false,
3527 getFormatStringRange());
3528 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003529 }
Ted Kremenek02087932010-07-16 02:11:22 +00003530 }
3531 }
3532}
3533
Ted Kremenekce815422010-07-19 21:25:57 +00003534bool
3535CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3536 SourceLocation Loc,
3537 const char *startSpec,
3538 unsigned specifierLen,
3539 const char *csStart,
3540 unsigned csLen) {
3541
3542 bool keepGoing = true;
3543 if (argIndex < NumDataArgs) {
3544 // Consider the argument coverered, even though the specifier doesn't
3545 // make sense.
3546 CoveredArgs.set(argIndex);
3547 }
3548 else {
3549 // If argIndex exceeds the number of data arguments we
3550 // don't issue a warning because that is just a cascade of warnings (and
3551 // they may have intended '%%' anyway). We don't want to continue processing
3552 // the format string after this point, however, as we will like just get
3553 // gibberish when trying to match arguments.
3554 keepGoing = false;
3555 }
3556
Richard Trieu03cf7b72011-10-28 00:41:25 +00003557 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3558 << StringRef(csStart, csLen),
3559 Loc, /*IsStringLocation*/true,
3560 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003561
3562 return keepGoing;
3563}
3564
Richard Trieu03cf7b72011-10-28 00:41:25 +00003565void
3566CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3567 const char *startSpec,
3568 unsigned specifierLen) {
3569 EmitFormatDiagnostic(
3570 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3571 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3572}
3573
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003574bool
3575CheckFormatHandler::CheckNumArgs(
3576 const analyze_format_string::FormatSpecifier &FS,
3577 const analyze_format_string::ConversionSpecifier &CS,
3578 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3579
3580 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003581 PartialDiagnostic PDiag = FS.usesPositionalArg()
3582 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3583 << (argIndex+1) << NumDataArgs)
3584 : S.PDiag(diag::warn_printf_insufficient_data_args);
3585 EmitFormatDiagnostic(
3586 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3587 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003588 return false;
3589 }
3590 return true;
3591}
3592
Richard Trieu03cf7b72011-10-28 00:41:25 +00003593template<typename Range>
3594void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3595 SourceLocation Loc,
3596 bool IsStringLocation,
3597 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003598 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003599 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003600 Loc, IsStringLocation, StringRange, FixIt);
3601}
3602
3603/// \brief If the format string is not within the funcion call, emit a note
3604/// so that the function call and string are in diagnostic messages.
3605///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003606/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003607/// call and only one diagnostic message will be produced. Otherwise, an
3608/// extra note will be emitted pointing to location of the format string.
3609///
3610/// \param ArgumentExpr the expression that is passed as the format string
3611/// argument in the function call. Used for getting locations when two
3612/// diagnostics are emitted.
3613///
3614/// \param PDiag the callee should already have provided any strings for the
3615/// diagnostic message. This function only adds locations and fixits
3616/// to diagnostics.
3617///
3618/// \param Loc primary location for diagnostic. If two diagnostics are
3619/// required, one will be at Loc and a new SourceLocation will be created for
3620/// the other one.
3621///
3622/// \param IsStringLocation if true, Loc points to the format string should be
3623/// used for the note. Otherwise, Loc points to the argument list and will
3624/// be used with PDiag.
3625///
3626/// \param StringRange some or all of the string to highlight. This is
3627/// templated so it can accept either a CharSourceRange or a SourceRange.
3628///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003629/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003630template<typename Range>
3631void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3632 const Expr *ArgumentExpr,
3633 PartialDiagnostic PDiag,
3634 SourceLocation Loc,
3635 bool IsStringLocation,
3636 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003637 ArrayRef<FixItHint> FixIt) {
3638 if (InFunctionCall) {
3639 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3640 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003641 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003642 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003643 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3644 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003645
3646 const Sema::SemaDiagnosticBuilder &Note =
3647 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3648 diag::note_format_string_defined);
3649
3650 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003651 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003652 }
3653}
3654
Ted Kremenek02087932010-07-16 02:11:22 +00003655//===--- CHECK: Printf format string checking ------------------------------===//
3656
3657namespace {
3658class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003659 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003660public:
3661 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3662 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003663 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003664 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003665 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003666 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003667 Sema::VariadicCallType CallType,
3668 llvm::SmallBitVector &CheckedVarArgs)
3669 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3670 numDataArgs, beg, hasVAListArg, Args,
3671 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3672 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003673 {}
3674
Craig Toppere14c0f82014-03-12 04:55:44 +00003675
Ted Kremenek02087932010-07-16 02:11:22 +00003676 bool HandleInvalidPrintfConversionSpecifier(
3677 const analyze_printf::PrintfSpecifier &FS,
3678 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003679 unsigned specifierLen) override;
3680
Ted Kremenek02087932010-07-16 02:11:22 +00003681 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3682 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003683 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003684 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3685 const char *StartSpecifier,
3686 unsigned SpecifierLen,
3687 const Expr *E);
3688
Ted Kremenek02087932010-07-16 02:11:22 +00003689 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3690 const char *startSpecifier, unsigned specifierLen);
3691 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3692 const analyze_printf::OptionalAmount &Amt,
3693 unsigned type,
3694 const char *startSpecifier, unsigned specifierLen);
3695 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3696 const analyze_printf::OptionalFlag &flag,
3697 const char *startSpecifier, unsigned specifierLen);
3698 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3699 const analyze_printf::OptionalFlag &ignoredFlag,
3700 const analyze_printf::OptionalFlag &flag,
3701 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003702 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003703 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003704
3705 void HandleEmptyObjCModifierFlag(const char *startFlag,
3706 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003707
Ted Kremenek2b417712015-07-02 05:39:16 +00003708 void HandleInvalidObjCModifierFlag(const char *startFlag,
3709 unsigned flagLen) override;
3710
3711 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3712 const char *flagsEnd,
3713 const char *conversionPosition)
3714 override;
3715};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003716}
Ted Kremenek02087932010-07-16 02:11:22 +00003717
3718bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3719 const analyze_printf::PrintfSpecifier &FS,
3720 const char *startSpecifier,
3721 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003722 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003723 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003724
Ted Kremenekce815422010-07-19 21:25:57 +00003725 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3726 getLocationOfByte(CS.getStart()),
3727 startSpecifier, specifierLen,
3728 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003729}
3730
Ted Kremenek02087932010-07-16 02:11:22 +00003731bool CheckPrintfHandler::HandleAmount(
3732 const analyze_format_string::OptionalAmount &Amt,
3733 unsigned k, const char *startSpecifier,
3734 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003735
3736 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003737 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003738 unsigned argIndex = Amt.getArgIndex();
3739 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003740 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3741 << k,
3742 getLocationOfByte(Amt.getStart()),
3743 /*IsStringLocation*/true,
3744 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003745 // Don't do any more checking. We will just emit
3746 // spurious errors.
3747 return false;
3748 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003749
Ted Kremenek5739de72010-01-29 01:06:55 +00003750 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003751 // Although not in conformance with C99, we also allow the argument to be
3752 // an 'unsigned int' as that is a reasonably safe case. GCC also
3753 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003754 CoveredArgs.set(argIndex);
3755 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003756 if (!Arg)
3757 return false;
3758
Ted Kremenek5739de72010-01-29 01:06:55 +00003759 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003760
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003761 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3762 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003763
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003764 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003765 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003766 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003767 << T << Arg->getSourceRange(),
3768 getLocationOfByte(Amt.getStart()),
3769 /*IsStringLocation*/true,
3770 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003771 // Don't do any more checking. We will just emit
3772 // spurious errors.
3773 return false;
3774 }
3775 }
3776 }
3777 return true;
3778}
Ted Kremenek5739de72010-01-29 01:06:55 +00003779
Tom Careb49ec692010-06-17 19:00:27 +00003780void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003781 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003782 const analyze_printf::OptionalAmount &Amt,
3783 unsigned type,
3784 const char *startSpecifier,
3785 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003786 const analyze_printf::PrintfConversionSpecifier &CS =
3787 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003788
Richard Trieu03cf7b72011-10-28 00:41:25 +00003789 FixItHint fixit =
3790 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3791 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3792 Amt.getConstantLength()))
3793 : FixItHint();
3794
3795 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3796 << type << CS.toString(),
3797 getLocationOfByte(Amt.getStart()),
3798 /*IsStringLocation*/true,
3799 getSpecifierRange(startSpecifier, specifierLen),
3800 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003801}
3802
Ted Kremenek02087932010-07-16 02:11:22 +00003803void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003804 const analyze_printf::OptionalFlag &flag,
3805 const char *startSpecifier,
3806 unsigned specifierLen) {
3807 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003808 const analyze_printf::PrintfConversionSpecifier &CS =
3809 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003810 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3811 << flag.toString() << CS.toString(),
3812 getLocationOfByte(flag.getPosition()),
3813 /*IsStringLocation*/true,
3814 getSpecifierRange(startSpecifier, specifierLen),
3815 FixItHint::CreateRemoval(
3816 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003817}
3818
3819void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003820 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003821 const analyze_printf::OptionalFlag &ignoredFlag,
3822 const analyze_printf::OptionalFlag &flag,
3823 const char *startSpecifier,
3824 unsigned specifierLen) {
3825 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003826 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3827 << ignoredFlag.toString() << flag.toString(),
3828 getLocationOfByte(ignoredFlag.getPosition()),
3829 /*IsStringLocation*/true,
3830 getSpecifierRange(startSpecifier, specifierLen),
3831 FixItHint::CreateRemoval(
3832 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003833}
3834
Ted Kremenek2b417712015-07-02 05:39:16 +00003835// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3836// bool IsStringLocation, Range StringRange,
3837// ArrayRef<FixItHint> Fixit = None);
3838
3839void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3840 unsigned flagLen) {
3841 // Warn about an empty flag.
3842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3843 getLocationOfByte(startFlag),
3844 /*IsStringLocation*/true,
3845 getSpecifierRange(startFlag, flagLen));
3846}
3847
3848void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3849 unsigned flagLen) {
3850 // Warn about an invalid flag.
3851 auto Range = getSpecifierRange(startFlag, flagLen);
3852 StringRef flag(startFlag, flagLen);
3853 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3854 getLocationOfByte(startFlag),
3855 /*IsStringLocation*/true,
3856 Range, FixItHint::CreateRemoval(Range));
3857}
3858
3859void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3860 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3861 // Warn about using '[...]' without a '@' conversion.
3862 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3863 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3864 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3865 getLocationOfByte(conversionPosition),
3866 /*IsStringLocation*/true,
3867 Range, FixItHint::CreateRemoval(Range));
3868}
3869
Richard Smith55ce3522012-06-25 20:30:08 +00003870// Determines if the specified is a C++ class or struct containing
3871// a member with the specified name and kind (e.g. a CXXMethodDecl named
3872// "c_str()").
3873template<typename MemberKind>
3874static llvm::SmallPtrSet<MemberKind*, 1>
3875CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3876 const RecordType *RT = Ty->getAs<RecordType>();
3877 llvm::SmallPtrSet<MemberKind*, 1> Results;
3878
3879 if (!RT)
3880 return Results;
3881 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003882 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003883 return Results;
3884
Alp Tokerb6cc5922014-05-03 03:45:55 +00003885 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003886 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003887 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003888
3889 // We just need to include all members of the right kind turned up by the
3890 // filter, at this point.
3891 if (S.LookupQualifiedName(R, RT->getDecl()))
3892 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3893 NamedDecl *decl = (*I)->getUnderlyingDecl();
3894 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3895 Results.insert(FK);
3896 }
3897 return Results;
3898}
3899
Richard Smith2868a732014-02-28 01:36:39 +00003900/// Check if we could call '.c_str()' on an object.
3901///
3902/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3903/// allow the call, or if it would be ambiguous).
3904bool Sema::hasCStrMethod(const Expr *E) {
3905 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3906 MethodSet Results =
3907 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3908 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3909 MI != ME; ++MI)
3910 if ((*MI)->getMinRequiredArguments() == 0)
3911 return true;
3912 return false;
3913}
3914
Richard Smith55ce3522012-06-25 20:30:08 +00003915// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003916// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003917// Returns true when a c_str() conversion method is found.
3918bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003919 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003920 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3921
3922 MethodSet Results =
3923 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3924
3925 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3926 MI != ME; ++MI) {
3927 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003928 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003929 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003930 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003931 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003932 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3933 << "c_str()"
3934 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3935 return true;
3936 }
3937 }
3938
3939 return false;
3940}
3941
Ted Kremenekab278de2010-01-28 23:39:18 +00003942bool
Ted Kremenek02087932010-07-16 02:11:22 +00003943CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003944 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003945 const char *startSpecifier,
3946 unsigned specifierLen) {
3947
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003948 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003949 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003950 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003951
Ted Kremenek6cd69422010-07-19 22:01:06 +00003952 if (FS.consumesDataArgument()) {
3953 if (atFirstArg) {
3954 atFirstArg = false;
3955 usesPositionalArgs = FS.usesPositionalArg();
3956 }
3957 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003958 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3959 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003960 return false;
3961 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003962 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003963
Ted Kremenekd1668192010-02-27 01:41:03 +00003964 // First check if the field width, precision, and conversion specifier
3965 // have matching data arguments.
3966 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3967 startSpecifier, specifierLen)) {
3968 return false;
3969 }
3970
3971 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3972 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003973 return false;
3974 }
3975
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003976 if (!CS.consumesDataArgument()) {
3977 // FIXME: Technically specifying a precision or field width here
3978 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003979 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003980 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003981
Ted Kremenek4a49d982010-02-26 19:18:41 +00003982 // Consume the argument.
3983 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003984 if (argIndex < NumDataArgs) {
3985 // The check to see if the argIndex is valid will come later.
3986 // We set the bit here because we may exit early from this
3987 // function if we encounter some other error.
3988 CoveredArgs.set(argIndex);
3989 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003990
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003991 // FreeBSD kernel extensions.
3992 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3993 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3994 // We need at least two arguments.
3995 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3996 return false;
3997
3998 // Claim the second argument.
3999 CoveredArgs.set(argIndex + 1);
4000
4001 // Type check the first argument (int for %b, pointer for %D)
4002 const Expr *Ex = getDataArg(argIndex);
4003 const analyze_printf::ArgType &AT =
4004 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4005 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4006 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4007 EmitFormatDiagnostic(
4008 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4009 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4010 << false << Ex->getSourceRange(),
4011 Ex->getLocStart(), /*IsStringLocation*/false,
4012 getSpecifierRange(startSpecifier, specifierLen));
4013
4014 // Type check the second argument (char * for both %b and %D)
4015 Ex = getDataArg(argIndex + 1);
4016 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4017 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4018 EmitFormatDiagnostic(
4019 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4020 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4021 << false << Ex->getSourceRange(),
4022 Ex->getLocStart(), /*IsStringLocation*/false,
4023 getSpecifierRange(startSpecifier, specifierLen));
4024
4025 return true;
4026 }
4027
Ted Kremenek4a49d982010-02-26 19:18:41 +00004028 // Check for using an Objective-C specific conversion specifier
4029 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004030 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004031 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4032 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004033 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004034
Tom Careb49ec692010-06-17 19:00:27 +00004035 // Check for invalid use of field width
4036 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004037 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004038 startSpecifier, specifierLen);
4039 }
4040
4041 // Check for invalid use of precision
4042 if (!FS.hasValidPrecision()) {
4043 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4044 startSpecifier, specifierLen);
4045 }
4046
4047 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004048 if (!FS.hasValidThousandsGroupingPrefix())
4049 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004050 if (!FS.hasValidLeadingZeros())
4051 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4052 if (!FS.hasValidPlusPrefix())
4053 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004054 if (!FS.hasValidSpacePrefix())
4055 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004056 if (!FS.hasValidAlternativeForm())
4057 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4058 if (!FS.hasValidLeftJustified())
4059 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4060
4061 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004062 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4063 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4064 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004065 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4066 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4067 startSpecifier, specifierLen);
4068
4069 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004070 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004071 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4072 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004073 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004074 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004075 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004076 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4077 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004078
Jordan Rose92303592012-09-08 04:00:03 +00004079 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4080 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4081
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004082 // The remaining checks depend on the data arguments.
4083 if (HasVAListArg)
4084 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004085
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004086 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004087 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004088
Jordan Rose58bbe422012-07-19 18:10:08 +00004089 const Expr *Arg = getDataArg(argIndex);
4090 if (!Arg)
4091 return true;
4092
4093 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004094}
4095
Jordan Roseaee34382012-09-05 22:56:26 +00004096static bool requiresParensToAddCast(const Expr *E) {
4097 // FIXME: We should have a general way to reason about operator
4098 // precedence and whether parens are actually needed here.
4099 // Take care of a few common cases where they aren't.
4100 const Expr *Inside = E->IgnoreImpCasts();
4101 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4102 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4103
4104 switch (Inside->getStmtClass()) {
4105 case Stmt::ArraySubscriptExprClass:
4106 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004107 case Stmt::CharacterLiteralClass:
4108 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004109 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004110 case Stmt::FloatingLiteralClass:
4111 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004112 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004113 case Stmt::ObjCArrayLiteralClass:
4114 case Stmt::ObjCBoolLiteralExprClass:
4115 case Stmt::ObjCBoxedExprClass:
4116 case Stmt::ObjCDictionaryLiteralClass:
4117 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004118 case Stmt::ObjCIvarRefExprClass:
4119 case Stmt::ObjCMessageExprClass:
4120 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004121 case Stmt::ObjCStringLiteralClass:
4122 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004123 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004124 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004125 case Stmt::UnaryOperatorClass:
4126 return false;
4127 default:
4128 return true;
4129 }
4130}
4131
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004132static std::pair<QualType, StringRef>
4133shouldNotPrintDirectly(const ASTContext &Context,
4134 QualType IntendedTy,
4135 const Expr *E) {
4136 // Use a 'while' to peel off layers of typedefs.
4137 QualType TyTy = IntendedTy;
4138 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4139 StringRef Name = UserTy->getDecl()->getName();
4140 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4141 .Case("NSInteger", Context.LongTy)
4142 .Case("NSUInteger", Context.UnsignedLongTy)
4143 .Case("SInt32", Context.IntTy)
4144 .Case("UInt32", Context.UnsignedIntTy)
4145 .Default(QualType());
4146
4147 if (!CastTy.isNull())
4148 return std::make_pair(CastTy, Name);
4149
4150 TyTy = UserTy->desugar();
4151 }
4152
4153 // Strip parens if necessary.
4154 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4155 return shouldNotPrintDirectly(Context,
4156 PE->getSubExpr()->getType(),
4157 PE->getSubExpr());
4158
4159 // If this is a conditional expression, then its result type is constructed
4160 // via usual arithmetic conversions and thus there might be no necessary
4161 // typedef sugar there. Recurse to operands to check for NSInteger &
4162 // Co. usage condition.
4163 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4164 QualType TrueTy, FalseTy;
4165 StringRef TrueName, FalseName;
4166
4167 std::tie(TrueTy, TrueName) =
4168 shouldNotPrintDirectly(Context,
4169 CO->getTrueExpr()->getType(),
4170 CO->getTrueExpr());
4171 std::tie(FalseTy, FalseName) =
4172 shouldNotPrintDirectly(Context,
4173 CO->getFalseExpr()->getType(),
4174 CO->getFalseExpr());
4175
4176 if (TrueTy == FalseTy)
4177 return std::make_pair(TrueTy, TrueName);
4178 else if (TrueTy.isNull())
4179 return std::make_pair(FalseTy, FalseName);
4180 else if (FalseTy.isNull())
4181 return std::make_pair(TrueTy, TrueName);
4182 }
4183
4184 return std::make_pair(QualType(), StringRef());
4185}
4186
Richard Smith55ce3522012-06-25 20:30:08 +00004187bool
4188CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4189 const char *StartSpecifier,
4190 unsigned SpecifierLen,
4191 const Expr *E) {
4192 using namespace analyze_format_string;
4193 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004194 // Now type check the data expression that matches the
4195 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004196 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4197 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004198 if (!AT.isValid())
4199 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004200
Jordan Rose598ec092012-12-05 18:44:40 +00004201 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004202 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4203 ExprTy = TET->getUnderlyingExpr()->getType();
4204 }
4205
Seth Cantrellb4802962015-03-04 03:12:10 +00004206 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4207
4208 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004209 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004210 }
Jordan Rose98709982012-06-04 22:48:57 +00004211
Jordan Rose22b74712012-09-05 22:56:19 +00004212 // Look through argument promotions for our error message's reported type.
4213 // This includes the integral and floating promotions, but excludes array
4214 // and function pointer decay; seeing that an argument intended to be a
4215 // string has type 'char [6]' is probably more confusing than 'char *'.
4216 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4217 if (ICE->getCastKind() == CK_IntegralCast ||
4218 ICE->getCastKind() == CK_FloatingCast) {
4219 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004220 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004221
4222 // Check if we didn't match because of an implicit cast from a 'char'
4223 // or 'short' to an 'int'. This is done because printf is a varargs
4224 // function.
4225 if (ICE->getType() == S.Context.IntTy ||
4226 ICE->getType() == S.Context.UnsignedIntTy) {
4227 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004228 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004229 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004230 }
Jordan Rose98709982012-06-04 22:48:57 +00004231 }
Jordan Rose598ec092012-12-05 18:44:40 +00004232 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4233 // Special case for 'a', which has type 'int' in C.
4234 // Note, however, that we do /not/ want to treat multibyte constants like
4235 // 'MooV' as characters! This form is deprecated but still exists.
4236 if (ExprTy == S.Context.IntTy)
4237 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4238 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004239 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004240
Jordan Rosebc53ed12014-05-31 04:12:14 +00004241 // Look through enums to their underlying type.
4242 bool IsEnum = false;
4243 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4244 ExprTy = EnumTy->getDecl()->getIntegerType();
4245 IsEnum = true;
4246 }
4247
Jordan Rose0e5badd2012-12-05 18:44:49 +00004248 // %C in an Objective-C context prints a unichar, not a wchar_t.
4249 // If the argument is an integer of some kind, believe the %C and suggest
4250 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004251 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004252 if (ObjCContext &&
4253 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4254 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4255 !ExprTy->isCharType()) {
4256 // 'unichar' is defined as a typedef of unsigned short, but we should
4257 // prefer using the typedef if it is visible.
4258 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004259
4260 // While we are here, check if the value is an IntegerLiteral that happens
4261 // to be within the valid range.
4262 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4263 const llvm::APInt &V = IL->getValue();
4264 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4265 return true;
4266 }
4267
Jordan Rose0e5badd2012-12-05 18:44:49 +00004268 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4269 Sema::LookupOrdinaryName);
4270 if (S.LookupName(Result, S.getCurScope())) {
4271 NamedDecl *ND = Result.getFoundDecl();
4272 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4273 if (TD->getUnderlyingType() == IntendedTy)
4274 IntendedTy = S.Context.getTypedefType(TD);
4275 }
4276 }
4277 }
4278
4279 // Special-case some of Darwin's platform-independence types by suggesting
4280 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004281 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004282 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004283 QualType CastTy;
4284 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4285 if (!CastTy.isNull()) {
4286 IntendedTy = CastTy;
4287 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004288 }
4289 }
4290
Jordan Rose22b74712012-09-05 22:56:19 +00004291 // We may be able to offer a FixItHint if it is a supported type.
4292 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004293 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004294 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004295
Jordan Rose22b74712012-09-05 22:56:19 +00004296 if (success) {
4297 // Get the fix string from the fixed format specifier
4298 SmallString<16> buf;
4299 llvm::raw_svector_ostream os(buf);
4300 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004301
Jordan Roseaee34382012-09-05 22:56:26 +00004302 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4303
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004304 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004305 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4306 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4307 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4308 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004309 // In this case, the specifier is wrong and should be changed to match
4310 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004311 EmitFormatDiagnostic(S.PDiag(diag)
4312 << AT.getRepresentativeTypeName(S.Context)
4313 << IntendedTy << IsEnum << E->getSourceRange(),
4314 E->getLocStart(),
4315 /*IsStringLocation*/ false, SpecRange,
4316 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004317
4318 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004319 // The canonical type for formatting this value is different from the
4320 // actual type of the expression. (This occurs, for example, with Darwin's
4321 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4322 // should be printed as 'long' for 64-bit compatibility.)
4323 // Rather than emitting a normal format/argument mismatch, we want to
4324 // add a cast to the recommended type (and correct the format string
4325 // if necessary).
4326 SmallString<16> CastBuf;
4327 llvm::raw_svector_ostream CastFix(CastBuf);
4328 CastFix << "(";
4329 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4330 CastFix << ")";
4331
4332 SmallVector<FixItHint,4> Hints;
4333 if (!AT.matchesType(S.Context, IntendedTy))
4334 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4335
4336 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4337 // If there's already a cast present, just replace it.
4338 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4339 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4340
4341 } else if (!requiresParensToAddCast(E)) {
4342 // If the expression has high enough precedence,
4343 // just write the C-style cast.
4344 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4345 CastFix.str()));
4346 } else {
4347 // Otherwise, add parens around the expression as well as the cast.
4348 CastFix << "(";
4349 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4350 CastFix.str()));
4351
Alp Tokerb6cc5922014-05-03 03:45:55 +00004352 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004353 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4354 }
4355
Jordan Rose0e5badd2012-12-05 18:44:49 +00004356 if (ShouldNotPrintDirectly) {
4357 // The expression has a type that should not be printed directly.
4358 // We extract the name from the typedef because we don't want to show
4359 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004360 StringRef Name;
4361 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4362 Name = TypedefTy->getDecl()->getName();
4363 else
4364 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004366 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004367 << E->getSourceRange(),
4368 E->getLocStart(), /*IsStringLocation=*/false,
4369 SpecRange, Hints);
4370 } else {
4371 // In this case, the expression could be printed using a different
4372 // specifier, but we've decided that the specifier is probably correct
4373 // and we should cast instead. Just use the normal warning message.
4374 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004375 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4376 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004377 << E->getSourceRange(),
4378 E->getLocStart(), /*IsStringLocation*/false,
4379 SpecRange, Hints);
4380 }
Jordan Roseaee34382012-09-05 22:56:26 +00004381 }
Jordan Rose22b74712012-09-05 22:56:19 +00004382 } else {
4383 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4384 SpecifierLen);
4385 // Since the warning for passing non-POD types to variadic functions
4386 // was deferred until now, we emit a warning for non-POD
4387 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004388 switch (S.isValidVarArgType(ExprTy)) {
4389 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004390 case Sema::VAK_ValidInCXX11: {
4391 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4392 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4393 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4394 }
Richard Smithd7293d72013-08-05 18:49:43 +00004395
Seth Cantrellb4802962015-03-04 03:12:10 +00004396 EmitFormatDiagnostic(
4397 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4398 << IsEnum << CSR << E->getSourceRange(),
4399 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4400 break;
4401 }
Richard Smithd7293d72013-08-05 18:49:43 +00004402 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004403 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004404 EmitFormatDiagnostic(
4405 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004406 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004407 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004408 << CallType
4409 << AT.getRepresentativeTypeName(S.Context)
4410 << CSR
4411 << E->getSourceRange(),
4412 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004413 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004414 break;
4415
4416 case Sema::VAK_Invalid:
4417 if (ExprTy->isObjCObjectType())
4418 EmitFormatDiagnostic(
4419 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4420 << S.getLangOpts().CPlusPlus11
4421 << ExprTy
4422 << CallType
4423 << AT.getRepresentativeTypeName(S.Context)
4424 << CSR
4425 << E->getSourceRange(),
4426 E->getLocStart(), /*IsStringLocation*/false, CSR);
4427 else
4428 // FIXME: If this is an initializer list, suggest removing the braces
4429 // or inserting a cast to the target type.
4430 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4431 << isa<InitListExpr>(E) << ExprTy << CallType
4432 << AT.getRepresentativeTypeName(S.Context)
4433 << E->getSourceRange();
4434 break;
4435 }
4436
4437 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4438 "format string specifier index out of range");
4439 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004440 }
4441
Ted Kremenekab278de2010-01-28 23:39:18 +00004442 return true;
4443}
4444
Ted Kremenek02087932010-07-16 02:11:22 +00004445//===--- CHECK: Scanf format string checking ------------------------------===//
4446
4447namespace {
4448class CheckScanfHandler : public CheckFormatHandler {
4449public:
4450 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4451 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004452 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004453 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004454 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004455 Sema::VariadicCallType CallType,
4456 llvm::SmallBitVector &CheckedVarArgs)
4457 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4458 numDataArgs, beg, hasVAListArg,
4459 Args, formatIdx, inFunctionCall, CallType,
4460 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004461 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004462
4463 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4464 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004465 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004466
4467 bool HandleInvalidScanfConversionSpecifier(
4468 const analyze_scanf::ScanfSpecifier &FS,
4469 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004470 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004471
Craig Toppere14c0f82014-03-12 04:55:44 +00004472 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004473};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004474}
Ted Kremenekab278de2010-01-28 23:39:18 +00004475
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004476void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4477 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004478 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4479 getLocationOfByte(end), /*IsStringLocation*/true,
4480 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004481}
4482
Ted Kremenekce815422010-07-19 21:25:57 +00004483bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4484 const analyze_scanf::ScanfSpecifier &FS,
4485 const char *startSpecifier,
4486 unsigned specifierLen) {
4487
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004488 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004489 FS.getConversionSpecifier();
4490
4491 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4492 getLocationOfByte(CS.getStart()),
4493 startSpecifier, specifierLen,
4494 CS.getStart(), CS.getLength());
4495}
4496
Ted Kremenek02087932010-07-16 02:11:22 +00004497bool CheckScanfHandler::HandleScanfSpecifier(
4498 const analyze_scanf::ScanfSpecifier &FS,
4499 const char *startSpecifier,
4500 unsigned specifierLen) {
4501
4502 using namespace analyze_scanf;
4503 using namespace analyze_format_string;
4504
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004505 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004506
Ted Kremenek6cd69422010-07-19 22:01:06 +00004507 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4508 // be used to decide if we are using positional arguments consistently.
4509 if (FS.consumesDataArgument()) {
4510 if (atFirstArg) {
4511 atFirstArg = false;
4512 usesPositionalArgs = FS.usesPositionalArg();
4513 }
4514 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004515 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4516 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004517 return false;
4518 }
Ted Kremenek02087932010-07-16 02:11:22 +00004519 }
4520
4521 // Check if the field with is non-zero.
4522 const OptionalAmount &Amt = FS.getFieldWidth();
4523 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4524 if (Amt.getConstantAmount() == 0) {
4525 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4526 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004527 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4528 getLocationOfByte(Amt.getStart()),
4529 /*IsStringLocation*/true, R,
4530 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004531 }
4532 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004533
Ted Kremenek02087932010-07-16 02:11:22 +00004534 if (!FS.consumesDataArgument()) {
4535 // FIXME: Technically specifying a precision or field width here
4536 // makes no sense. Worth issuing a warning at some point.
4537 return true;
4538 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004539
Ted Kremenek02087932010-07-16 02:11:22 +00004540 // Consume the argument.
4541 unsigned argIndex = FS.getArgIndex();
4542 if (argIndex < NumDataArgs) {
4543 // The check to see if the argIndex is valid will come later.
4544 // We set the bit here because we may exit early from this
4545 // function if we encounter some other error.
4546 CoveredArgs.set(argIndex);
4547 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004548
Ted Kremenek4407ea42010-07-20 20:04:47 +00004549 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004550 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004551 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4552 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004553 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004554 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004555 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004556 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4557 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004558
Jordan Rose92303592012-09-08 04:00:03 +00004559 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4560 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4561
Ted Kremenek02087932010-07-16 02:11:22 +00004562 // The remaining checks depend on the data arguments.
4563 if (HasVAListArg)
4564 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004565
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004566 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004567 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004568
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004569 // Check that the argument type matches the format specifier.
4570 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004571 if (!Ex)
4572 return true;
4573
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004574 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004575
4576 if (!AT.isValid()) {
4577 return true;
4578 }
4579
Seth Cantrellb4802962015-03-04 03:12:10 +00004580 analyze_format_string::ArgType::MatchKind match =
4581 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004582 if (match == analyze_format_string::ArgType::Match) {
4583 return true;
4584 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004585
Seth Cantrell79340072015-03-04 05:58:08 +00004586 ScanfSpecifier fixedFS = FS;
4587 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4588 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004589
Seth Cantrell79340072015-03-04 05:58:08 +00004590 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4591 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4592 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4593 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004594
Seth Cantrell79340072015-03-04 05:58:08 +00004595 if (success) {
4596 // Get the fix string from the fixed format specifier.
4597 SmallString<128> buf;
4598 llvm::raw_svector_ostream os(buf);
4599 fixedFS.toString(os);
4600
4601 EmitFormatDiagnostic(
4602 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4603 << Ex->getType() << false << Ex->getSourceRange(),
4604 Ex->getLocStart(),
4605 /*IsStringLocation*/ false,
4606 getSpecifierRange(startSpecifier, specifierLen),
4607 FixItHint::CreateReplacement(
4608 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4609 } else {
4610 EmitFormatDiagnostic(S.PDiag(diag)
4611 << AT.getRepresentativeTypeName(S.Context)
4612 << Ex->getType() << false << Ex->getSourceRange(),
4613 Ex->getLocStart(),
4614 /*IsStringLocation*/ false,
4615 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004616 }
4617
Ted Kremenek02087932010-07-16 02:11:22 +00004618 return true;
4619}
4620
4621void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004622 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004623 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004624 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004625 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004626 bool inFunctionCall, VariadicCallType CallType,
4627 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004628
Ted Kremenekab278de2010-01-28 23:39:18 +00004629 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004630 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004631 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004632 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004633 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4634 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004635 return;
4636 }
Ted Kremenek02087932010-07-16 02:11:22 +00004637
Ted Kremenekab278de2010-01-28 23:39:18 +00004638 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004639 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004640 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004641 // Account for cases where the string literal is truncated in a declaration.
4642 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4643 assert(T && "String literal not of constant array type!");
4644 size_t TypeSize = T->getSize().getZExtValue();
4645 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004646 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004647
4648 // Emit a warning if the string literal is truncated and does not contain an
4649 // embedded null character.
4650 if (TypeSize <= StrRef.size() &&
4651 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4652 CheckFormatHandler::EmitFormatDiagnostic(
4653 *this, inFunctionCall, Args[format_idx],
4654 PDiag(diag::warn_printf_format_string_not_null_terminated),
4655 FExpr->getLocStart(),
4656 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4657 return;
4658 }
4659
Ted Kremenekab278de2010-01-28 23:39:18 +00004660 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004661 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004662 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004663 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004664 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4665 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004666 return;
4667 }
Ted Kremenek02087932010-07-16 02:11:22 +00004668
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004669 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004670 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004671 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004672 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004673 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004674 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004675
Hans Wennborg23926bd2011-12-15 10:25:47 +00004676 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004677 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004678 Context.getTargetInfo(),
4679 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004680 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004681 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004682 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004683 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004684 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004685
Hans Wennborg23926bd2011-12-15 10:25:47 +00004686 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004687 getLangOpts(),
4688 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004689 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004690 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004691}
4692
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004693bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4694 // Str - The format string. NOTE: this is NOT null-terminated!
4695 StringRef StrRef = FExpr->getString();
4696 const char *Str = StrRef.data();
4697 // Account for cases where the string literal is truncated in a declaration.
4698 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4699 assert(T && "String literal not of constant array type!");
4700 size_t TypeSize = T->getSize().getZExtValue();
4701 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4702 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4703 getLangOpts(),
4704 Context.getTargetInfo());
4705}
4706
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004707//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4708
4709// Returns the related absolute value function that is larger, of 0 if one
4710// does not exist.
4711static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4712 switch (AbsFunction) {
4713 default:
4714 return 0;
4715
4716 case Builtin::BI__builtin_abs:
4717 return Builtin::BI__builtin_labs;
4718 case Builtin::BI__builtin_labs:
4719 return Builtin::BI__builtin_llabs;
4720 case Builtin::BI__builtin_llabs:
4721 return 0;
4722
4723 case Builtin::BI__builtin_fabsf:
4724 return Builtin::BI__builtin_fabs;
4725 case Builtin::BI__builtin_fabs:
4726 return Builtin::BI__builtin_fabsl;
4727 case Builtin::BI__builtin_fabsl:
4728 return 0;
4729
4730 case Builtin::BI__builtin_cabsf:
4731 return Builtin::BI__builtin_cabs;
4732 case Builtin::BI__builtin_cabs:
4733 return Builtin::BI__builtin_cabsl;
4734 case Builtin::BI__builtin_cabsl:
4735 return 0;
4736
4737 case Builtin::BIabs:
4738 return Builtin::BIlabs;
4739 case Builtin::BIlabs:
4740 return Builtin::BIllabs;
4741 case Builtin::BIllabs:
4742 return 0;
4743
4744 case Builtin::BIfabsf:
4745 return Builtin::BIfabs;
4746 case Builtin::BIfabs:
4747 return Builtin::BIfabsl;
4748 case Builtin::BIfabsl:
4749 return 0;
4750
4751 case Builtin::BIcabsf:
4752 return Builtin::BIcabs;
4753 case Builtin::BIcabs:
4754 return Builtin::BIcabsl;
4755 case Builtin::BIcabsl:
4756 return 0;
4757 }
4758}
4759
4760// Returns the argument type of the absolute value function.
4761static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4762 unsigned AbsType) {
4763 if (AbsType == 0)
4764 return QualType();
4765
4766 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4767 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4768 if (Error != ASTContext::GE_None)
4769 return QualType();
4770
4771 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4772 if (!FT)
4773 return QualType();
4774
4775 if (FT->getNumParams() != 1)
4776 return QualType();
4777
4778 return FT->getParamType(0);
4779}
4780
4781// Returns the best absolute value function, or zero, based on type and
4782// current absolute value function.
4783static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4784 unsigned AbsFunctionKind) {
4785 unsigned BestKind = 0;
4786 uint64_t ArgSize = Context.getTypeSize(ArgType);
4787 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4788 Kind = getLargerAbsoluteValueFunction(Kind)) {
4789 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4790 if (Context.getTypeSize(ParamType) >= ArgSize) {
4791 if (BestKind == 0)
4792 BestKind = Kind;
4793 else if (Context.hasSameType(ParamType, ArgType)) {
4794 BestKind = Kind;
4795 break;
4796 }
4797 }
4798 }
4799 return BestKind;
4800}
4801
4802enum AbsoluteValueKind {
4803 AVK_Integer,
4804 AVK_Floating,
4805 AVK_Complex
4806};
4807
4808static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4809 if (T->isIntegralOrEnumerationType())
4810 return AVK_Integer;
4811 if (T->isRealFloatingType())
4812 return AVK_Floating;
4813 if (T->isAnyComplexType())
4814 return AVK_Complex;
4815
4816 llvm_unreachable("Type not integer, floating, or complex");
4817}
4818
4819// Changes the absolute value function to a different type. Preserves whether
4820// the function is a builtin.
4821static unsigned changeAbsFunction(unsigned AbsKind,
4822 AbsoluteValueKind ValueKind) {
4823 switch (ValueKind) {
4824 case AVK_Integer:
4825 switch (AbsKind) {
4826 default:
4827 return 0;
4828 case Builtin::BI__builtin_fabsf:
4829 case Builtin::BI__builtin_fabs:
4830 case Builtin::BI__builtin_fabsl:
4831 case Builtin::BI__builtin_cabsf:
4832 case Builtin::BI__builtin_cabs:
4833 case Builtin::BI__builtin_cabsl:
4834 return Builtin::BI__builtin_abs;
4835 case Builtin::BIfabsf:
4836 case Builtin::BIfabs:
4837 case Builtin::BIfabsl:
4838 case Builtin::BIcabsf:
4839 case Builtin::BIcabs:
4840 case Builtin::BIcabsl:
4841 return Builtin::BIabs;
4842 }
4843 case AVK_Floating:
4844 switch (AbsKind) {
4845 default:
4846 return 0;
4847 case Builtin::BI__builtin_abs:
4848 case Builtin::BI__builtin_labs:
4849 case Builtin::BI__builtin_llabs:
4850 case Builtin::BI__builtin_cabsf:
4851 case Builtin::BI__builtin_cabs:
4852 case Builtin::BI__builtin_cabsl:
4853 return Builtin::BI__builtin_fabsf;
4854 case Builtin::BIabs:
4855 case Builtin::BIlabs:
4856 case Builtin::BIllabs:
4857 case Builtin::BIcabsf:
4858 case Builtin::BIcabs:
4859 case Builtin::BIcabsl:
4860 return Builtin::BIfabsf;
4861 }
4862 case AVK_Complex:
4863 switch (AbsKind) {
4864 default:
4865 return 0;
4866 case Builtin::BI__builtin_abs:
4867 case Builtin::BI__builtin_labs:
4868 case Builtin::BI__builtin_llabs:
4869 case Builtin::BI__builtin_fabsf:
4870 case Builtin::BI__builtin_fabs:
4871 case Builtin::BI__builtin_fabsl:
4872 return Builtin::BI__builtin_cabsf;
4873 case Builtin::BIabs:
4874 case Builtin::BIlabs:
4875 case Builtin::BIllabs:
4876 case Builtin::BIfabsf:
4877 case Builtin::BIfabs:
4878 case Builtin::BIfabsl:
4879 return Builtin::BIcabsf;
4880 }
4881 }
4882 llvm_unreachable("Unable to convert function");
4883}
4884
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004885static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004886 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4887 if (!FnInfo)
4888 return 0;
4889
4890 switch (FDecl->getBuiltinID()) {
4891 default:
4892 return 0;
4893 case Builtin::BI__builtin_abs:
4894 case Builtin::BI__builtin_fabs:
4895 case Builtin::BI__builtin_fabsf:
4896 case Builtin::BI__builtin_fabsl:
4897 case Builtin::BI__builtin_labs:
4898 case Builtin::BI__builtin_llabs:
4899 case Builtin::BI__builtin_cabs:
4900 case Builtin::BI__builtin_cabsf:
4901 case Builtin::BI__builtin_cabsl:
4902 case Builtin::BIabs:
4903 case Builtin::BIlabs:
4904 case Builtin::BIllabs:
4905 case Builtin::BIfabs:
4906 case Builtin::BIfabsf:
4907 case Builtin::BIfabsl:
4908 case Builtin::BIcabs:
4909 case Builtin::BIcabsf:
4910 case Builtin::BIcabsl:
4911 return FDecl->getBuiltinID();
4912 }
4913 llvm_unreachable("Unknown Builtin type");
4914}
4915
4916// If the replacement is valid, emit a note with replacement function.
4917// Additionally, suggest including the proper header if not already included.
4918static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004919 unsigned AbsKind, QualType ArgType) {
4920 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004921 const char *HeaderName = nullptr;
4922 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004923 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4924 FunctionName = "std::abs";
4925 if (ArgType->isIntegralOrEnumerationType()) {
4926 HeaderName = "cstdlib";
4927 } else if (ArgType->isRealFloatingType()) {
4928 HeaderName = "cmath";
4929 } else {
4930 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004931 }
Richard Trieubeffb832014-04-15 23:47:53 +00004932
4933 // Lookup all std::abs
4934 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004935 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004936 R.suppressDiagnostics();
4937 S.LookupQualifiedName(R, Std);
4938
4939 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004940 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004941 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4942 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4943 } else {
4944 FDecl = dyn_cast<FunctionDecl>(I);
4945 }
4946 if (!FDecl)
4947 continue;
4948
4949 // Found std::abs(), check that they are the right ones.
4950 if (FDecl->getNumParams() != 1)
4951 continue;
4952
4953 // Check that the parameter type can handle the argument.
4954 QualType ParamType = FDecl->getParamDecl(0)->getType();
4955 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4956 S.Context.getTypeSize(ArgType) <=
4957 S.Context.getTypeSize(ParamType)) {
4958 // Found a function, don't need the header hint.
4959 EmitHeaderHint = false;
4960 break;
4961 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004962 }
Richard Trieubeffb832014-04-15 23:47:53 +00004963 }
4964 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00004965 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00004966 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4967
4968 if (HeaderName) {
4969 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4970 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4971 R.suppressDiagnostics();
4972 S.LookupName(R, S.getCurScope());
4973
4974 if (R.isSingleResult()) {
4975 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4976 if (FD && FD->getBuiltinID() == AbsKind) {
4977 EmitHeaderHint = false;
4978 } else {
4979 return;
4980 }
4981 } else if (!R.empty()) {
4982 return;
4983 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004984 }
4985 }
4986
4987 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004988 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004989
Richard Trieubeffb832014-04-15 23:47:53 +00004990 if (!HeaderName)
4991 return;
4992
4993 if (!EmitHeaderHint)
4994 return;
4995
Alp Toker5d96e0a2014-07-11 20:53:51 +00004996 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4997 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004998}
4999
5000static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5001 if (!FDecl)
5002 return false;
5003
5004 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5005 return false;
5006
5007 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5008
5009 while (ND && ND->isInlineNamespace()) {
5010 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005011 }
Richard Trieubeffb832014-04-15 23:47:53 +00005012
5013 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5014 return false;
5015
5016 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5017 return false;
5018
5019 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005020}
5021
5022// Warn when using the wrong abs() function.
5023void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5024 const FunctionDecl *FDecl,
5025 IdentifierInfo *FnInfo) {
5026 if (Call->getNumArgs() != 1)
5027 return;
5028
5029 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005030 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5031 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005032 return;
5033
5034 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5035 QualType ParamType = Call->getArg(0)->getType();
5036
Alp Toker5d96e0a2014-07-11 20:53:51 +00005037 // Unsigned types cannot be negative. Suggest removing the absolute value
5038 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005039 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005040 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005041 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005042 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5043 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005044 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005045 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5046 return;
5047 }
5048
Richard Trieubeffb832014-04-15 23:47:53 +00005049 // std::abs has overloads which prevent most of the absolute value problems
5050 // from occurring.
5051 if (IsStdAbs)
5052 return;
5053
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005054 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5055 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5056
5057 // The argument and parameter are the same kind. Check if they are the right
5058 // size.
5059 if (ArgValueKind == ParamValueKind) {
5060 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5061 return;
5062
5063 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5064 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5065 << FDecl << ArgType << ParamType;
5066
5067 if (NewAbsKind == 0)
5068 return;
5069
5070 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005071 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005072 return;
5073 }
5074
5075 // ArgValueKind != ParamValueKind
5076 // The wrong type of absolute value function was used. Attempt to find the
5077 // proper one.
5078 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5079 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5080 if (NewAbsKind == 0)
5081 return;
5082
5083 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5084 << FDecl << ParamValueKind << ArgValueKind;
5085
5086 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005087 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005088 return;
5089}
5090
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005091//===--- CHECK: Standard memory functions ---------------------------------===//
5092
Nico Weber0e6daef2013-12-26 23:38:39 +00005093/// \brief Takes the expression passed to the size_t parameter of functions
5094/// such as memcmp, strncat, etc and warns if it's a comparison.
5095///
5096/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5097static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5098 IdentifierInfo *FnName,
5099 SourceLocation FnLoc,
5100 SourceLocation RParenLoc) {
5101 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5102 if (!Size)
5103 return false;
5104
5105 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5106 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5107 return false;
5108
Nico Weber0e6daef2013-12-26 23:38:39 +00005109 SourceRange SizeRange = Size->getSourceRange();
5110 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5111 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005112 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005113 << FnName << FixItHint::CreateInsertion(
5114 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005115 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005116 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005117 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005118 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5119 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005120
5121 return true;
5122}
5123
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005124/// \brief Determine whether the given type is or contains a dynamic class type
5125/// (e.g., whether it has a vtable).
5126static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5127 bool &IsContained) {
5128 // Look through array types while ignoring qualifiers.
5129 const Type *Ty = T->getBaseElementTypeUnsafe();
5130 IsContained = false;
5131
5132 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5133 RD = RD ? RD->getDefinition() : nullptr;
5134 if (!RD)
5135 return nullptr;
5136
5137 if (RD->isDynamicClass())
5138 return RD;
5139
5140 // Check all the fields. If any bases were dynamic, the class is dynamic.
5141 // It's impossible for a class to transitively contain itself by value, so
5142 // infinite recursion is impossible.
5143 for (auto *FD : RD->fields()) {
5144 bool SubContained;
5145 if (const CXXRecordDecl *ContainedRD =
5146 getContainedDynamicClass(FD->getType(), SubContained)) {
5147 IsContained = true;
5148 return ContainedRD;
5149 }
5150 }
5151
5152 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005153}
5154
Chandler Carruth889ed862011-06-21 23:04:20 +00005155/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005156/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005157static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005158 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005159 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5160 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5161 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005162
Craig Topperc3ec1492014-05-26 06:22:03 +00005163 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005164}
5165
Chandler Carruth889ed862011-06-21 23:04:20 +00005166/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005167static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005168 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5169 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5170 if (SizeOf->getKind() == clang::UETT_SizeOf)
5171 return SizeOf->getTypeOfArgument();
5172
5173 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005174}
5175
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005176/// \brief Check for dangerous or invalid arguments to memset().
5177///
Chandler Carruthac687262011-06-03 06:23:57 +00005178/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005179/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5180/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005181///
5182/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005183void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005184 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005185 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005186 assert(BId != 0);
5187
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005188 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005189 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005190 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005191 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005192 return;
5193
Anna Zaks22122702012-01-17 00:37:07 +00005194 unsigned LastArg = (BId == Builtin::BImemset ||
5195 BId == Builtin::BIstrndup ? 1 : 2);
5196 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005197 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005198
Nico Weber0e6daef2013-12-26 23:38:39 +00005199 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5200 Call->getLocStart(), Call->getRParenLoc()))
5201 return;
5202
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005203 // We have special checking when the length is a sizeof expression.
5204 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5205 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5206 llvm::FoldingSetNodeID SizeOfArgID;
5207
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005208 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5209 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005210 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005211
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005212 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005213 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005214 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005215 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005216
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005217 // Never warn about void type pointers. This can be used to suppress
5218 // false positives.
5219 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005220 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005221
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005222 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5223 // actually comparing the expressions for equality. Because computing the
5224 // expression IDs can be expensive, we only do this if the diagnostic is
5225 // enabled.
5226 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005227 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5228 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005229 // We only compute IDs for expressions if the warning is enabled, and
5230 // cache the sizeof arg's ID.
5231 if (SizeOfArgID == llvm::FoldingSetNodeID())
5232 SizeOfArg->Profile(SizeOfArgID, Context, true);
5233 llvm::FoldingSetNodeID DestID;
5234 Dest->Profile(DestID, Context, true);
5235 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005236 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5237 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005238 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005239 StringRef ReadableName = FnName->getName();
5240
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005241 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005242 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005243 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005244 if (!PointeeTy->isIncompleteType() &&
5245 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005246 ActionIdx = 2; // If the pointee's size is sizeof(char),
5247 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005248
5249 // If the function is defined as a builtin macro, do not show macro
5250 // expansion.
5251 SourceLocation SL = SizeOfArg->getExprLoc();
5252 SourceRange DSR = Dest->getSourceRange();
5253 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005254 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005255
5256 if (SM.isMacroArgExpansion(SL)) {
5257 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5258 SL = SM.getSpellingLoc(SL);
5259 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5260 SM.getSpellingLoc(DSR.getEnd()));
5261 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5262 SM.getSpellingLoc(SSR.getEnd()));
5263 }
5264
Anna Zaksd08d9152012-05-30 23:14:52 +00005265 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005266 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005267 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005268 << PointeeTy
5269 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005270 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005271 << SSR);
5272 DiagRuntimeBehavior(SL, SizeOfArg,
5273 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5274 << ActionIdx
5275 << SSR);
5276
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005277 break;
5278 }
5279 }
5280
5281 // Also check for cases where the sizeof argument is the exact same
5282 // type as the memory argument, and where it points to a user-defined
5283 // record type.
5284 if (SizeOfArgTy != QualType()) {
5285 if (PointeeTy->isRecordType() &&
5286 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5287 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5288 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5289 << FnName << SizeOfArgTy << ArgIdx
5290 << PointeeTy << Dest->getSourceRange()
5291 << LenExpr->getSourceRange());
5292 break;
5293 }
Nico Weberc5e73862011-06-14 16:14:58 +00005294 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005295 } else if (DestTy->isArrayType()) {
5296 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005297 }
Nico Weberc5e73862011-06-14 16:14:58 +00005298
Nico Weberc44b35e2015-03-21 17:37:46 +00005299 if (PointeeTy == QualType())
5300 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005301
Nico Weberc44b35e2015-03-21 17:37:46 +00005302 // Always complain about dynamic classes.
5303 bool IsContained;
5304 if (const CXXRecordDecl *ContainedRD =
5305 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005306
Nico Weberc44b35e2015-03-21 17:37:46 +00005307 unsigned OperationType = 0;
5308 // "overwritten" if we're warning about the destination for any call
5309 // but memcmp; otherwise a verb appropriate to the call.
5310 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5311 if (BId == Builtin::BImemcpy)
5312 OperationType = 1;
5313 else if(BId == Builtin::BImemmove)
5314 OperationType = 2;
5315 else if (BId == Builtin::BImemcmp)
5316 OperationType = 3;
5317 }
5318
John McCall31168b02011-06-15 23:02:42 +00005319 DiagRuntimeBehavior(
5320 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005321 PDiag(diag::warn_dyn_class_memaccess)
5322 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5323 << FnName << IsContained << ContainedRD << OperationType
5324 << Call->getCallee()->getSourceRange());
5325 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5326 BId != Builtin::BImemset)
5327 DiagRuntimeBehavior(
5328 Dest->getExprLoc(), Dest,
5329 PDiag(diag::warn_arc_object_memaccess)
5330 << ArgIdx << FnName << PointeeTy
5331 << Call->getCallee()->getSourceRange());
5332 else
5333 continue;
5334
5335 DiagRuntimeBehavior(
5336 Dest->getExprLoc(), Dest,
5337 PDiag(diag::note_bad_memaccess_silence)
5338 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5339 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005340 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005341
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005342}
5343
Ted Kremenek6865f772011-08-18 20:55:45 +00005344// A little helper routine: ignore addition and subtraction of integer literals.
5345// This intentionally does not ignore all integer constant expressions because
5346// we don't want to remove sizeof().
5347static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5348 Ex = Ex->IgnoreParenCasts();
5349
5350 for (;;) {
5351 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5352 if (!BO || !BO->isAdditiveOp())
5353 break;
5354
5355 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5356 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5357
5358 if (isa<IntegerLiteral>(RHS))
5359 Ex = LHS;
5360 else if (isa<IntegerLiteral>(LHS))
5361 Ex = RHS;
5362 else
5363 break;
5364 }
5365
5366 return Ex;
5367}
5368
Anna Zaks13b08572012-08-08 21:42:23 +00005369static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5370 ASTContext &Context) {
5371 // Only handle constant-sized or VLAs, but not flexible members.
5372 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5373 // Only issue the FIXIT for arrays of size > 1.
5374 if (CAT->getSize().getSExtValue() <= 1)
5375 return false;
5376 } else if (!Ty->isVariableArrayType()) {
5377 return false;
5378 }
5379 return true;
5380}
5381
Ted Kremenek6865f772011-08-18 20:55:45 +00005382// Warn if the user has made the 'size' argument to strlcpy or strlcat
5383// be the size of the source, instead of the destination.
5384void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5385 IdentifierInfo *FnName) {
5386
5387 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005388 unsigned NumArgs = Call->getNumArgs();
5389 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005390 return;
5391
5392 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5393 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005394 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005395
5396 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5397 Call->getLocStart(), Call->getRParenLoc()))
5398 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005399
5400 // Look for 'strlcpy(dst, x, sizeof(x))'
5401 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5402 CompareWithSrc = Ex;
5403 else {
5404 // Look for 'strlcpy(dst, x, strlen(x))'
5405 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005406 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5407 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005408 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5409 }
5410 }
5411
5412 if (!CompareWithSrc)
5413 return;
5414
5415 // Determine if the argument to sizeof/strlen is equal to the source
5416 // argument. In principle there's all kinds of things you could do
5417 // here, for instance creating an == expression and evaluating it with
5418 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5419 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5420 if (!SrcArgDRE)
5421 return;
5422
5423 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5424 if (!CompareWithSrcDRE ||
5425 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5426 return;
5427
5428 const Expr *OriginalSizeArg = Call->getArg(2);
5429 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5430 << OriginalSizeArg->getSourceRange() << FnName;
5431
5432 // Output a FIXIT hint if the destination is an array (rather than a
5433 // pointer to an array). This could be enhanced to handle some
5434 // pointers if we know the actual size, like if DstArg is 'array+2'
5435 // we could say 'sizeof(array)-2'.
5436 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005437 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005438 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005439
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005440 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005441 llvm::raw_svector_ostream OS(sizeString);
5442 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005443 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005444 OS << ")";
5445
5446 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5447 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5448 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005449}
5450
Anna Zaks314cd092012-02-01 19:08:57 +00005451/// Check if two expressions refer to the same declaration.
5452static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5453 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5454 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5455 return D1->getDecl() == D2->getDecl();
5456 return false;
5457}
5458
5459static const Expr *getStrlenExprArg(const Expr *E) {
5460 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5461 const FunctionDecl *FD = CE->getDirectCallee();
5462 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005463 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005464 return CE->getArg(0)->IgnoreParenCasts();
5465 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005466 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005467}
5468
5469// Warn on anti-patterns as the 'size' argument to strncat.
5470// The correct size argument should look like following:
5471// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5472void Sema::CheckStrncatArguments(const CallExpr *CE,
5473 IdentifierInfo *FnName) {
5474 // Don't crash if the user has the wrong number of arguments.
5475 if (CE->getNumArgs() < 3)
5476 return;
5477 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5478 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5479 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5480
Nico Weber0e6daef2013-12-26 23:38:39 +00005481 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5482 CE->getRParenLoc()))
5483 return;
5484
Anna Zaks314cd092012-02-01 19:08:57 +00005485 // Identify common expressions, which are wrongly used as the size argument
5486 // to strncat and may lead to buffer overflows.
5487 unsigned PatternType = 0;
5488 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5489 // - sizeof(dst)
5490 if (referToTheSameDecl(SizeOfArg, DstArg))
5491 PatternType = 1;
5492 // - sizeof(src)
5493 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5494 PatternType = 2;
5495 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5496 if (BE->getOpcode() == BO_Sub) {
5497 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5498 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5499 // - sizeof(dst) - strlen(dst)
5500 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5501 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5502 PatternType = 1;
5503 // - sizeof(src) - (anything)
5504 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5505 PatternType = 2;
5506 }
5507 }
5508
5509 if (PatternType == 0)
5510 return;
5511
Anna Zaks5069aa32012-02-03 01:27:37 +00005512 // Generate the diagnostic.
5513 SourceLocation SL = LenArg->getLocStart();
5514 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005515 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005516
5517 // If the function is defined as a builtin macro, do not show macro expansion.
5518 if (SM.isMacroArgExpansion(SL)) {
5519 SL = SM.getSpellingLoc(SL);
5520 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5521 SM.getSpellingLoc(SR.getEnd()));
5522 }
5523
Anna Zaks13b08572012-08-08 21:42:23 +00005524 // Check if the destination is an array (rather than a pointer to an array).
5525 QualType DstTy = DstArg->getType();
5526 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5527 Context);
5528 if (!isKnownSizeArray) {
5529 if (PatternType == 1)
5530 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5531 else
5532 Diag(SL, diag::warn_strncat_src_size) << SR;
5533 return;
5534 }
5535
Anna Zaks314cd092012-02-01 19:08:57 +00005536 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005537 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005538 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005539 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005540
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005541 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005542 llvm::raw_svector_ostream OS(sizeString);
5543 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005544 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005545 OS << ") - ";
5546 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005547 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005548 OS << ") - 1";
5549
Anna Zaks5069aa32012-02-03 01:27:37 +00005550 Diag(SL, diag::note_strncat_wrong_size)
5551 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005552}
5553
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005554//===--- CHECK: Return Address of Stack Variable --------------------------===//
5555
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005556static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5557 Decl *ParentDecl);
5558static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5559 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005560
5561/// CheckReturnStackAddr - Check if a return statement returns the address
5562/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005563static void
5564CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5565 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005566
Craig Topperc3ec1492014-05-26 06:22:03 +00005567 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005568 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005569
5570 // Perform checking for returned stack addresses, local blocks,
5571 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005572 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005573 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005574 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005575 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005576 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005577 }
5578
Craig Topperc3ec1492014-05-26 06:22:03 +00005579 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005580 return; // Nothing suspicious was found.
5581
5582 SourceLocation diagLoc;
5583 SourceRange diagRange;
5584 if (refVars.empty()) {
5585 diagLoc = stackE->getLocStart();
5586 diagRange = stackE->getSourceRange();
5587 } else {
5588 // We followed through a reference variable. 'stackE' contains the
5589 // problematic expression but we will warn at the return statement pointing
5590 // at the reference variable. We will later display the "trail" of
5591 // reference variables using notes.
5592 diagLoc = refVars[0]->getLocStart();
5593 diagRange = refVars[0]->getSourceRange();
5594 }
5595
5596 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005597 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005598 : diag::warn_ret_stack_addr)
5599 << DR->getDecl()->getDeclName() << diagRange;
5600 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005601 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005602 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005603 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005604 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005605 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5606 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005607 << diagRange;
5608 }
5609
5610 // Display the "trail" of reference variables that we followed until we
5611 // found the problematic expression using notes.
5612 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5613 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5614 // If this var binds to another reference var, show the range of the next
5615 // var, otherwise the var binds to the problematic expression, in which case
5616 // show the range of the expression.
5617 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5618 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005619 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5620 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005621 }
5622}
5623
5624/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5625/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005626/// to a location on the stack, a local block, an address of a label, or a
5627/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005628/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005629/// encounter a subexpression that (1) clearly does not lead to one of the
5630/// above problematic expressions (2) is something we cannot determine leads to
5631/// a problematic expression based on such local checking.
5632///
5633/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5634/// the expression that they point to. Such variables are added to the
5635/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005636///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005637/// EvalAddr processes expressions that are pointers that are used as
5638/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005639/// At the base case of the recursion is a check for the above problematic
5640/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005641///
5642/// This implementation handles:
5643///
5644/// * pointer-to-pointer casts
5645/// * implicit conversions from array references to pointers
5646/// * taking the address of fields
5647/// * arbitrary interplay between "&" and "*" operators
5648/// * pointer arithmetic from an address of a stack variable
5649/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005650static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5651 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005652 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005653 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005654
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005655 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005656 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005657 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005658 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005659 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005660
Peter Collingbourne91147592011-04-15 00:35:48 +00005661 E = E->IgnoreParens();
5662
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005663 // Our "symbolic interpreter" is just a dispatch off the currently
5664 // viewed AST node. We then recursively traverse the AST by calling
5665 // EvalAddr and EvalVal appropriately.
5666 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005667 case Stmt::DeclRefExprClass: {
5668 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5669
Richard Smith40f08eb2014-01-30 22:05:38 +00005670 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005671 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005672 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005673
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005674 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5675 // If this is a reference variable, follow through to the expression that
5676 // it points to.
5677 if (V->hasLocalStorage() &&
5678 V->getType()->isReferenceType() && V->hasInit()) {
5679 // Add the reference variable to the "trail".
5680 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005681 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005682 }
5683
Craig Topperc3ec1492014-05-26 06:22:03 +00005684 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005685 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005686
Chris Lattner934edb22007-12-28 05:31:15 +00005687 case Stmt::UnaryOperatorClass: {
5688 // The only unary operator that make sense to handle here
5689 // is AddrOf. All others don't make sense as pointers.
5690 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005691
John McCalle3027922010-08-25 11:45:40 +00005692 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005693 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005694 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005695 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005696 }
Mike Stump11289f42009-09-09 15:08:12 +00005697
Chris Lattner934edb22007-12-28 05:31:15 +00005698 case Stmt::BinaryOperatorClass: {
5699 // Handle pointer arithmetic. All other binary operators are not valid
5700 // in this context.
5701 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005702 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005703
John McCalle3027922010-08-25 11:45:40 +00005704 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005705 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005706
Chris Lattner934edb22007-12-28 05:31:15 +00005707 Expr *Base = B->getLHS();
5708
5709 // Determine which argument is the real pointer base. It could be
5710 // the RHS argument instead of the LHS.
5711 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005712
Chris Lattner934edb22007-12-28 05:31:15 +00005713 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005714 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005715 }
Steve Naroff2752a172008-09-10 19:17:48 +00005716
Chris Lattner934edb22007-12-28 05:31:15 +00005717 // For conditional operators we need to see if either the LHS or RHS are
5718 // valid DeclRefExpr*s. If one of them is valid, we return it.
5719 case Stmt::ConditionalOperatorClass: {
5720 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005721
Chris Lattner934edb22007-12-28 05:31:15 +00005722 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005723 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5724 if (Expr *LHSExpr = C->getLHS()) {
5725 // In C++, we can have a throw-expression, which has 'void' type.
5726 if (!LHSExpr->getType()->isVoidType())
5727 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005728 return LHS;
5729 }
Chris Lattner934edb22007-12-28 05:31:15 +00005730
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005731 // In C++, we can have a throw-expression, which has 'void' type.
5732 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005733 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005734
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005735 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005736 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005737
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005738 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005739 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005740 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005741 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005742
5743 case Stmt::AddrLabelExprClass:
5744 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005745
John McCall28fc7092011-11-10 05:35:25 +00005746 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005747 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5748 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005749
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005750 // For casts, we need to handle conversions from arrays to
5751 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005752 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005753 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005754 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005755 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005756 case Stmt::CXXStaticCastExprClass:
5757 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005758 case Stmt::CXXConstCastExprClass:
5759 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005760 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5761 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005762 case CK_LValueToRValue:
5763 case CK_NoOp:
5764 case CK_BaseToDerived:
5765 case CK_DerivedToBase:
5766 case CK_UncheckedDerivedToBase:
5767 case CK_Dynamic:
5768 case CK_CPointerToObjCPointerCast:
5769 case CK_BlockPointerToObjCPointerCast:
5770 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005771 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005772
5773 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005774 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005775
Richard Trieudadefde2014-07-02 04:39:38 +00005776 case CK_BitCast:
5777 if (SubExpr->getType()->isAnyPointerType() ||
5778 SubExpr->getType()->isBlockPointerType() ||
5779 SubExpr->getType()->isObjCQualifiedIdType())
5780 return EvalAddr(SubExpr, refVars, ParentDecl);
5781 else
5782 return nullptr;
5783
Eli Friedman8195ad72012-02-23 23:04:32 +00005784 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005785 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005786 }
Chris Lattner934edb22007-12-28 05:31:15 +00005787 }
Mike Stump11289f42009-09-09 15:08:12 +00005788
Douglas Gregorfe314812011-06-21 17:03:29 +00005789 case Stmt::MaterializeTemporaryExprClass:
5790 if (Expr *Result = EvalAddr(
5791 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005792 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005793 return Result;
5794
5795 return E;
5796
Chris Lattner934edb22007-12-28 05:31:15 +00005797 // Everything else: we simply don't reason about them.
5798 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005799 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005800 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005801}
Mike Stump11289f42009-09-09 15:08:12 +00005802
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005803
5804/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5805/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005806static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5807 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005808do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005809 // We should only be called for evaluating non-pointer expressions, or
5810 // expressions with a pointer type that are not used as references but instead
5811 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005812
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005813 // Our "symbolic interpreter" is just a dispatch off the currently
5814 // viewed AST node. We then recursively traverse the AST by calling
5815 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005816
5817 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005818 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005819 case Stmt::ImplicitCastExprClass: {
5820 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005821 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005822 E = IE->getSubExpr();
5823 continue;
5824 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005825 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005826 }
5827
John McCall28fc7092011-11-10 05:35:25 +00005828 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005829 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005830
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005831 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005832 // When we hit a DeclRefExpr we are looking at code that refers to a
5833 // variable's name. If it's not a reference variable we check if it has
5834 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005835 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005836
Richard Smith40f08eb2014-01-30 22:05:38 +00005837 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005838 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005839 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005840
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005841 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5842 // Check if it refers to itself, e.g. "int& i = i;".
5843 if (V == ParentDecl)
5844 return DR;
5845
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005846 if (V->hasLocalStorage()) {
5847 if (!V->getType()->isReferenceType())
5848 return DR;
5849
5850 // Reference variable, follow through to the expression that
5851 // it points to.
5852 if (V->hasInit()) {
5853 // Add the reference variable to the "trail".
5854 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005855 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005856 }
5857 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005858 }
Mike Stump11289f42009-09-09 15:08:12 +00005859
Craig Topperc3ec1492014-05-26 06:22:03 +00005860 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005861 }
Mike Stump11289f42009-09-09 15:08:12 +00005862
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005863 case Stmt::UnaryOperatorClass: {
5864 // The only unary operator that make sense to handle here
5865 // is Deref. All others don't resolve to a "name." This includes
5866 // handling all sorts of rvalues passed to a unary operator.
5867 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005868
John McCalle3027922010-08-25 11:45:40 +00005869 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005870 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005871
Craig Topperc3ec1492014-05-26 06:22:03 +00005872 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005873 }
Mike Stump11289f42009-09-09 15:08:12 +00005874
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005875 case Stmt::ArraySubscriptExprClass: {
5876 // Array subscripts are potential references to data on the stack. We
5877 // retrieve the DeclRefExpr* for the array variable if it indeed
5878 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005879 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005880 }
Mike Stump11289f42009-09-09 15:08:12 +00005881
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005882 case Stmt::OMPArraySectionExprClass: {
5883 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5884 ParentDecl);
5885 }
5886
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005887 case Stmt::ConditionalOperatorClass: {
5888 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005889 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005890 ConditionalOperator *C = cast<ConditionalOperator>(E);
5891
Anders Carlsson801c5c72007-11-30 19:04:31 +00005892 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005893 if (Expr *LHSExpr = C->getLHS()) {
5894 // In C++, we can have a throw-expression, which has 'void' type.
5895 if (!LHSExpr->getType()->isVoidType())
5896 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5897 return LHS;
5898 }
5899
5900 // In C++, we can have a throw-expression, which has 'void' type.
5901 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005902 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005903
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005904 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005905 }
Mike Stump11289f42009-09-09 15:08:12 +00005906
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005907 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005908 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005909 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005910
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005911 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005912 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005913 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005914
5915 // Check whether the member type is itself a reference, in which case
5916 // we're not going to refer to the member, but to what the member refers to.
5917 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005918 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005919
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005920 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005921 }
Mike Stump11289f42009-09-09 15:08:12 +00005922
Douglas Gregorfe314812011-06-21 17:03:29 +00005923 case Stmt::MaterializeTemporaryExprClass:
5924 if (Expr *Result = EvalVal(
5925 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005926 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005927 return Result;
5928
5929 return E;
5930
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005931 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005932 // Check that we don't return or take the address of a reference to a
5933 // temporary. This is only useful in C++.
5934 if (!E->isTypeDependent() && E->isRValue())
5935 return E;
5936
5937 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005938 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005939 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005940} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005941}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005942
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005943void
5944Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5945 SourceLocation ReturnLoc,
5946 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005947 const AttrVec *Attrs,
5948 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005949 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5950
5951 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005952 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5953 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005954 CheckNonNullExpr(*this, RetValExp))
5955 Diag(ReturnLoc, diag::warn_null_ret)
5956 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005957
5958 // C++11 [basic.stc.dynamic.allocation]p4:
5959 // If an allocation function declared with a non-throwing
5960 // exception-specification fails to allocate storage, it shall return
5961 // a null pointer. Any other allocation function that fails to allocate
5962 // storage shall indicate failure only by throwing an exception [...]
5963 if (FD) {
5964 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5965 if (Op == OO_New || Op == OO_Array_New) {
5966 const FunctionProtoType *Proto
5967 = FD->getType()->castAs<FunctionProtoType>();
5968 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5969 CheckNonNullExpr(*this, RetValExp))
5970 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5971 << FD << getLangOpts().CPlusPlus11;
5972 }
5973 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005974}
5975
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005976//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5977
5978/// Check for comparisons of floating point operands using != and ==.
5979/// Issue a warning if these are no self-comparisons, as they are not likely
5980/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005981void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005982 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5983 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005984
5985 // Special case: check for x == x (which is OK).
5986 // Do not emit warnings for such cases.
5987 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5988 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5989 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005990 return;
Mike Stump11289f42009-09-09 15:08:12 +00005991
5992
Ted Kremenekeda40e22007-11-29 00:59:04 +00005993 // Special case: check for comparisons against literals that can be exactly
5994 // represented by APFloat. In such cases, do not emit a warning. This
5995 // is a heuristic: often comparison against such literals are used to
5996 // detect if a value in a variable has not changed. This clearly can
5997 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005998 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5999 if (FLL->isExact())
6000 return;
6001 } else
6002 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6003 if (FLR->isExact())
6004 return;
Mike Stump11289f42009-09-09 15:08:12 +00006005
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006006 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006007 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006008 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006009 return;
Mike Stump11289f42009-09-09 15:08:12 +00006010
David Blaikie1f4ff152012-07-16 20:47:22 +00006011 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006012 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006013 return;
Mike Stump11289f42009-09-09 15:08:12 +00006014
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006015 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006016 Diag(Loc, diag::warn_floatingpoint_eq)
6017 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006018}
John McCallca01b222010-01-04 23:21:16 +00006019
John McCall70aa5392010-01-06 05:24:50 +00006020//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6021//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006022
John McCall70aa5392010-01-06 05:24:50 +00006023namespace {
John McCallca01b222010-01-04 23:21:16 +00006024
John McCall70aa5392010-01-06 05:24:50 +00006025/// Structure recording the 'active' range of an integer-valued
6026/// expression.
6027struct IntRange {
6028 /// The number of bits active in the int.
6029 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006030
John McCall70aa5392010-01-06 05:24:50 +00006031 /// True if the int is known not to have negative values.
6032 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006033
John McCall70aa5392010-01-06 05:24:50 +00006034 IntRange(unsigned Width, bool NonNegative)
6035 : Width(Width), NonNegative(NonNegative)
6036 {}
John McCallca01b222010-01-04 23:21:16 +00006037
John McCall817d4af2010-11-10 23:38:19 +00006038 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006039 static IntRange forBoolType() {
6040 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006041 }
6042
John McCall817d4af2010-11-10 23:38:19 +00006043 /// Returns the range of an opaque value of the given integral type.
6044 static IntRange forValueOfType(ASTContext &C, QualType T) {
6045 return forValueOfCanonicalType(C,
6046 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006047 }
6048
John McCall817d4af2010-11-10 23:38:19 +00006049 /// Returns the range of an opaque value of a canonical integral type.
6050 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006051 assert(T->isCanonicalUnqualified());
6052
6053 if (const VectorType *VT = dyn_cast<VectorType>(T))
6054 T = VT->getElementType().getTypePtr();
6055 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6056 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006057 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6058 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006059
David Majnemer6a426652013-06-07 22:07:20 +00006060 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006061 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006062 EnumDecl *Enum = ET->getDecl();
6063 if (!Enum->isCompleteDefinition())
6064 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006065
David Majnemer6a426652013-06-07 22:07:20 +00006066 unsigned NumPositive = Enum->getNumPositiveBits();
6067 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006068
David Majnemer6a426652013-06-07 22:07:20 +00006069 if (NumNegative == 0)
6070 return IntRange(NumPositive, true/*NonNegative*/);
6071 else
6072 return IntRange(std::max(NumPositive + 1, NumNegative),
6073 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006074 }
John McCall70aa5392010-01-06 05:24:50 +00006075
6076 const BuiltinType *BT = cast<BuiltinType>(T);
6077 assert(BT->isInteger());
6078
6079 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6080 }
6081
John McCall817d4af2010-11-10 23:38:19 +00006082 /// Returns the "target" range of a canonical integral type, i.e.
6083 /// the range of values expressible in the type.
6084 ///
6085 /// This matches forValueOfCanonicalType except that enums have the
6086 /// full range of their type, not the range of their enumerators.
6087 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6088 assert(T->isCanonicalUnqualified());
6089
6090 if (const VectorType *VT = dyn_cast<VectorType>(T))
6091 T = VT->getElementType().getTypePtr();
6092 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6093 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006094 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6095 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006096 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006097 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006098
6099 const BuiltinType *BT = cast<BuiltinType>(T);
6100 assert(BT->isInteger());
6101
6102 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6103 }
6104
6105 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006106 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006107 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006108 L.NonNegative && R.NonNegative);
6109 }
6110
John McCall817d4af2010-11-10 23:38:19 +00006111 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006112 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006113 return IntRange(std::min(L.Width, R.Width),
6114 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006115 }
6116};
6117
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006118static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6119 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006120 if (value.isSigned() && value.isNegative())
6121 return IntRange(value.getMinSignedBits(), false);
6122
6123 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006124 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006125
6126 // isNonNegative() just checks the sign bit without considering
6127 // signedness.
6128 return IntRange(value.getActiveBits(), true);
6129}
6130
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006131static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6132 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006133 if (result.isInt())
6134 return GetValueRange(C, result.getInt(), MaxWidth);
6135
6136 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006137 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6138 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6139 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6140 R = IntRange::join(R, El);
6141 }
John McCall70aa5392010-01-06 05:24:50 +00006142 return R;
6143 }
6144
6145 if (result.isComplexInt()) {
6146 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6147 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6148 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006149 }
6150
6151 // This can happen with lossless casts to intptr_t of "based" lvalues.
6152 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006153 // FIXME: The only reason we need to pass the type in here is to get
6154 // the sign right on this one case. It would be nice if APValue
6155 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006156 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006157 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006158}
John McCall70aa5392010-01-06 05:24:50 +00006159
Eli Friedmane6d33952013-07-08 20:20:06 +00006160static QualType GetExprType(Expr *E) {
6161 QualType Ty = E->getType();
6162 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6163 Ty = AtomicRHS->getValueType();
6164 return Ty;
6165}
6166
John McCall70aa5392010-01-06 05:24:50 +00006167/// Pseudo-evaluate the given integer expression, estimating the
6168/// range of values it might take.
6169///
6170/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006171static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006172 E = E->IgnoreParens();
6173
6174 // Try a full evaluation first.
6175 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006176 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006177 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006178
6179 // I think we only want to look through implicit casts here; if the
6180 // user has an explicit widening cast, we should treat the value as
6181 // being of the new, wider type.
6182 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006183 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006184 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6185
Eli Friedmane6d33952013-07-08 20:20:06 +00006186 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006187
John McCalle3027922010-08-25 11:45:40 +00006188 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006189
John McCall70aa5392010-01-06 05:24:50 +00006190 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006191 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006192 return OutputTypeRange;
6193
6194 IntRange SubRange
6195 = GetExprRange(C, CE->getSubExpr(),
6196 std::min(MaxWidth, OutputTypeRange.Width));
6197
6198 // Bail out if the subexpr's range is as wide as the cast type.
6199 if (SubRange.Width >= OutputTypeRange.Width)
6200 return OutputTypeRange;
6201
6202 // Otherwise, we take the smaller width, and we're non-negative if
6203 // either the output type or the subexpr is.
6204 return IntRange(SubRange.Width,
6205 SubRange.NonNegative || OutputTypeRange.NonNegative);
6206 }
6207
6208 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6209 // If we can fold the condition, just take that operand.
6210 bool CondResult;
6211 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6212 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6213 : CO->getFalseExpr(),
6214 MaxWidth);
6215
6216 // Otherwise, conservatively merge.
6217 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6218 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6219 return IntRange::join(L, R);
6220 }
6221
6222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6223 switch (BO->getOpcode()) {
6224
6225 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006226 case BO_LAnd:
6227 case BO_LOr:
6228 case BO_LT:
6229 case BO_GT:
6230 case BO_LE:
6231 case BO_GE:
6232 case BO_EQ:
6233 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006234 return IntRange::forBoolType();
6235
John McCallc3688382011-07-13 06:35:24 +00006236 // The type of the assignments is the type of the LHS, so the RHS
6237 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006238 case BO_MulAssign:
6239 case BO_DivAssign:
6240 case BO_RemAssign:
6241 case BO_AddAssign:
6242 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006243 case BO_XorAssign:
6244 case BO_OrAssign:
6245 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006246 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006247
John McCallc3688382011-07-13 06:35:24 +00006248 // Simple assignments just pass through the RHS, which will have
6249 // been coerced to the LHS type.
6250 case BO_Assign:
6251 // TODO: bitfields?
6252 return GetExprRange(C, BO->getRHS(), MaxWidth);
6253
John McCall70aa5392010-01-06 05:24:50 +00006254 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006255 case BO_PtrMemD:
6256 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006257 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006258
John McCall2ce81ad2010-01-06 22:07:33 +00006259 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006260 case BO_And:
6261 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006262 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6263 GetExprRange(C, BO->getRHS(), MaxWidth));
6264
John McCall70aa5392010-01-06 05:24:50 +00006265 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006266 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006267 // ...except that we want to treat '1 << (blah)' as logically
6268 // positive. It's an important idiom.
6269 if (IntegerLiteral *I
6270 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6271 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006272 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006273 return IntRange(R.Width, /*NonNegative*/ true);
6274 }
6275 }
6276 // fallthrough
6277
John McCalle3027922010-08-25 11:45:40 +00006278 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006279 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006280
John McCall2ce81ad2010-01-06 22:07:33 +00006281 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006282 case BO_Shr:
6283 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006284 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6285
6286 // If the shift amount is a positive constant, drop the width by
6287 // that much.
6288 llvm::APSInt shift;
6289 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6290 shift.isNonNegative()) {
6291 unsigned zext = shift.getZExtValue();
6292 if (zext >= L.Width)
6293 L.Width = (L.NonNegative ? 0 : 1);
6294 else
6295 L.Width -= zext;
6296 }
6297
6298 return L;
6299 }
6300
6301 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006302 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006303 return GetExprRange(C, BO->getRHS(), MaxWidth);
6304
John McCall2ce81ad2010-01-06 22:07:33 +00006305 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006306 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006307 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006308 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006309 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006310
John McCall51431812011-07-14 22:39:48 +00006311 // The width of a division result is mostly determined by the size
6312 // of the LHS.
6313 case BO_Div: {
6314 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006315 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006316 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6317
6318 // If the divisor is constant, use that.
6319 llvm::APSInt divisor;
6320 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6321 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6322 if (log2 >= L.Width)
6323 L.Width = (L.NonNegative ? 0 : 1);
6324 else
6325 L.Width = std::min(L.Width - log2, MaxWidth);
6326 return L;
6327 }
6328
6329 // Otherwise, just use the LHS's width.
6330 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6331 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6332 }
6333
6334 // The result of a remainder can't be larger than the result of
6335 // either side.
6336 case BO_Rem: {
6337 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006338 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006339 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6340 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6341
6342 IntRange meet = IntRange::meet(L, R);
6343 meet.Width = std::min(meet.Width, MaxWidth);
6344 return meet;
6345 }
6346
6347 // The default behavior is okay for these.
6348 case BO_Mul:
6349 case BO_Add:
6350 case BO_Xor:
6351 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006352 break;
6353 }
6354
John McCall51431812011-07-14 22:39:48 +00006355 // The default case is to treat the operation as if it were closed
6356 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006357 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6358 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6359 return IntRange::join(L, R);
6360 }
6361
6362 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6363 switch (UO->getOpcode()) {
6364 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006365 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006366 return IntRange::forBoolType();
6367
6368 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006369 case UO_Deref:
6370 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006371 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006372
6373 default:
6374 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6375 }
6376 }
6377
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006378 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6379 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6380
John McCalld25db7e2013-05-06 21:39:12 +00006381 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006382 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006383 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006384
Eli Friedmane6d33952013-07-08 20:20:06 +00006385 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006386}
John McCall263a48b2010-01-04 23:31:57 +00006387
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006388static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006389 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006390}
6391
John McCall263a48b2010-01-04 23:31:57 +00006392/// Checks whether the given value, which currently has the given
6393/// source semantics, has the same value when coerced through the
6394/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006395static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6396 const llvm::fltSemantics &Src,
6397 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006398 llvm::APFloat truncated = value;
6399
6400 bool ignored;
6401 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6402 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6403
6404 return truncated.bitwiseIsEqual(value);
6405}
6406
6407/// Checks whether the given value, which currently has the given
6408/// source semantics, has the same value when coerced through the
6409/// target semantics.
6410///
6411/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006412static bool IsSameFloatAfterCast(const APValue &value,
6413 const llvm::fltSemantics &Src,
6414 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006415 if (value.isFloat())
6416 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6417
6418 if (value.isVector()) {
6419 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6420 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6421 return false;
6422 return true;
6423 }
6424
6425 assert(value.isComplexFloat());
6426 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6427 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6428}
6429
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006430static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006431
Ted Kremenek6274be42010-09-23 21:43:44 +00006432static bool IsZero(Sema &S, Expr *E) {
6433 // Suppress cases where we are comparing against an enum constant.
6434 if (const DeclRefExpr *DR =
6435 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6436 if (isa<EnumConstantDecl>(DR->getDecl()))
6437 return false;
6438
6439 // Suppress cases where the '0' value is expanded from a macro.
6440 if (E->getLocStart().isMacroID())
6441 return false;
6442
John McCallcc7e5bf2010-05-06 08:58:33 +00006443 llvm::APSInt Value;
6444 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6445}
6446
John McCall2551c1b2010-10-06 00:25:24 +00006447static bool HasEnumType(Expr *E) {
6448 // Strip off implicit integral promotions.
6449 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006450 if (ICE->getCastKind() != CK_IntegralCast &&
6451 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006452 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006453 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006454 }
6455
6456 return E->getType()->isEnumeralType();
6457}
6458
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006459static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006460 // Disable warning in template instantiations.
6461 if (!S.ActiveTemplateInstantiations.empty())
6462 return;
6463
John McCalle3027922010-08-25 11:45:40 +00006464 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006465 if (E->isValueDependent())
6466 return;
6467
John McCalle3027922010-08-25 11:45:40 +00006468 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006469 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006470 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006471 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006472 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006473 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006474 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006475 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006476 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006477 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006478 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006479 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006480 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006481 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006482 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006483 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6484 }
6485}
6486
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006487static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006488 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006489 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006490 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006491 // Disable warning in template instantiations.
6492 if (!S.ActiveTemplateInstantiations.empty())
6493 return;
6494
Richard Trieu0f097742014-04-04 04:13:47 +00006495 // TODO: Investigate using GetExprRange() to get tighter bounds
6496 // on the bit ranges.
6497 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006498 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006499 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006500 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6501 unsigned OtherWidth = OtherRange.Width;
6502
6503 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6504
Richard Trieu560910c2012-11-14 22:50:24 +00006505 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006506 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006507 return;
6508
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006509 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006510 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006511
Richard Trieu0f097742014-04-04 04:13:47 +00006512 // Used for diagnostic printout.
6513 enum {
6514 LiteralConstant = 0,
6515 CXXBoolLiteralTrue,
6516 CXXBoolLiteralFalse
6517 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006518
Richard Trieu0f097742014-04-04 04:13:47 +00006519 if (!OtherIsBooleanType) {
6520 QualType ConstantT = Constant->getType();
6521 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006522
Richard Trieu0f097742014-04-04 04:13:47 +00006523 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6524 return;
6525 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6526 "comparison with non-integer type");
6527
6528 bool ConstantSigned = ConstantT->isSignedIntegerType();
6529 bool CommonSigned = CommonT->isSignedIntegerType();
6530
6531 bool EqualityOnly = false;
6532
6533 if (CommonSigned) {
6534 // The common type is signed, therefore no signed to unsigned conversion.
6535 if (!OtherRange.NonNegative) {
6536 // Check that the constant is representable in type OtherT.
6537 if (ConstantSigned) {
6538 if (OtherWidth >= Value.getMinSignedBits())
6539 return;
6540 } else { // !ConstantSigned
6541 if (OtherWidth >= Value.getActiveBits() + 1)
6542 return;
6543 }
6544 } else { // !OtherSigned
6545 // Check that the constant is representable in type OtherT.
6546 // Negative values are out of range.
6547 if (ConstantSigned) {
6548 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6549 return;
6550 } else { // !ConstantSigned
6551 if (OtherWidth >= Value.getActiveBits())
6552 return;
6553 }
Richard Trieu560910c2012-11-14 22:50:24 +00006554 }
Richard Trieu0f097742014-04-04 04:13:47 +00006555 } else { // !CommonSigned
6556 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006557 if (OtherWidth >= Value.getActiveBits())
6558 return;
Craig Toppercf360162014-06-18 05:13:11 +00006559 } else { // OtherSigned
6560 assert(!ConstantSigned &&
6561 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006562 // Check to see if the constant is representable in OtherT.
6563 if (OtherWidth > Value.getActiveBits())
6564 return;
6565 // Check to see if the constant is equivalent to a negative value
6566 // cast to CommonT.
6567 if (S.Context.getIntWidth(ConstantT) ==
6568 S.Context.getIntWidth(CommonT) &&
6569 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6570 return;
6571 // The constant value rests between values that OtherT can represent
6572 // after conversion. Relational comparison still works, but equality
6573 // comparisons will be tautological.
6574 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006575 }
6576 }
Richard Trieu0f097742014-04-04 04:13:47 +00006577
6578 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6579
6580 if (op == BO_EQ || op == BO_NE) {
6581 IsTrue = op == BO_NE;
6582 } else if (EqualityOnly) {
6583 return;
6584 } else if (RhsConstant) {
6585 if (op == BO_GT || op == BO_GE)
6586 IsTrue = !PositiveConstant;
6587 else // op == BO_LT || op == BO_LE
6588 IsTrue = PositiveConstant;
6589 } else {
6590 if (op == BO_LT || op == BO_LE)
6591 IsTrue = !PositiveConstant;
6592 else // op == BO_GT || op == BO_GE
6593 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006594 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006595 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006596 // Other isKnownToHaveBooleanValue
6597 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6598 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6599 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6600
6601 static const struct LinkedConditions {
6602 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6603 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6604 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6605 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6606 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6607 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6608
6609 } TruthTable = {
6610 // Constant on LHS. | Constant on RHS. |
6611 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6612 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6613 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6614 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6615 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6616 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6617 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6618 };
6619
6620 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6621
6622 enum ConstantValue ConstVal = Zero;
6623 if (Value.isUnsigned() || Value.isNonNegative()) {
6624 if (Value == 0) {
6625 LiteralOrBoolConstant =
6626 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6627 ConstVal = Zero;
6628 } else if (Value == 1) {
6629 LiteralOrBoolConstant =
6630 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6631 ConstVal = One;
6632 } else {
6633 LiteralOrBoolConstant = LiteralConstant;
6634 ConstVal = GT_One;
6635 }
6636 } else {
6637 ConstVal = LT_Zero;
6638 }
6639
6640 CompareBoolWithConstantResult CmpRes;
6641
6642 switch (op) {
6643 case BO_LT:
6644 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6645 break;
6646 case BO_GT:
6647 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6648 break;
6649 case BO_LE:
6650 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6651 break;
6652 case BO_GE:
6653 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6654 break;
6655 case BO_EQ:
6656 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6657 break;
6658 case BO_NE:
6659 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6660 break;
6661 default:
6662 CmpRes = Unkwn;
6663 break;
6664 }
6665
6666 if (CmpRes == AFals) {
6667 IsTrue = false;
6668 } else if (CmpRes == ATrue) {
6669 IsTrue = true;
6670 } else {
6671 return;
6672 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006673 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006674
6675 // If this is a comparison to an enum constant, include that
6676 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006677 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006678 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6679 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6680
6681 SmallString<64> PrettySourceValue;
6682 llvm::raw_svector_ostream OS(PrettySourceValue);
6683 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006684 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006685 else
6686 OS << Value;
6687
Richard Trieu0f097742014-04-04 04:13:47 +00006688 S.DiagRuntimeBehavior(
6689 E->getOperatorLoc(), E,
6690 S.PDiag(diag::warn_out_of_range_compare)
6691 << OS.str() << LiteralOrBoolConstant
6692 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6693 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006694}
6695
John McCallcc7e5bf2010-05-06 08:58:33 +00006696/// Analyze the operands of the given comparison. Implements the
6697/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006698static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006699 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6700 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006701}
John McCall263a48b2010-01-04 23:31:57 +00006702
John McCallca01b222010-01-04 23:21:16 +00006703/// \brief Implements -Wsign-compare.
6704///
Richard Trieu82402a02011-09-15 21:56:47 +00006705/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006706static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006707 // The type the comparison is being performed in.
6708 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006709
6710 // Only analyze comparison operators where both sides have been converted to
6711 // the same type.
6712 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6713 return AnalyzeImpConvsInComparison(S, E);
6714
6715 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006716 if (E->isValueDependent())
6717 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006718
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006719 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6720 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006721
6722 bool IsComparisonConstant = false;
6723
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006724 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006725 // of 'true' or 'false'.
6726 if (T->isIntegralType(S.Context)) {
6727 llvm::APSInt RHSValue;
6728 bool IsRHSIntegralLiteral =
6729 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6730 llvm::APSInt LHSValue;
6731 bool IsLHSIntegralLiteral =
6732 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6733 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6734 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6735 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6736 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6737 else
6738 IsComparisonConstant =
6739 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006740 } else if (!T->hasUnsignedIntegerRepresentation())
6741 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006742
John McCallcc7e5bf2010-05-06 08:58:33 +00006743 // We don't do anything special if this isn't an unsigned integral
6744 // comparison: we're only interested in integral comparisons, and
6745 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006746 //
6747 // We also don't care about value-dependent expressions or expressions
6748 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006749 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006750 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006751
John McCallcc7e5bf2010-05-06 08:58:33 +00006752 // Check to see if one of the (unmodified) operands is of different
6753 // signedness.
6754 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006755 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6756 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006757 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006758 signedOperand = LHS;
6759 unsignedOperand = RHS;
6760 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6761 signedOperand = RHS;
6762 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006763 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006764 CheckTrivialUnsignedComparison(S, E);
6765 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006766 }
6767
John McCallcc7e5bf2010-05-06 08:58:33 +00006768 // Otherwise, calculate the effective range of the signed operand.
6769 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006770
John McCallcc7e5bf2010-05-06 08:58:33 +00006771 // Go ahead and analyze implicit conversions in the operands. Note
6772 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006773 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6774 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006775
John McCallcc7e5bf2010-05-06 08:58:33 +00006776 // If the signed range is non-negative, -Wsign-compare won't fire,
6777 // but we should still check for comparisons which are always true
6778 // or false.
6779 if (signedRange.NonNegative)
6780 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006781
6782 // For (in)equality comparisons, if the unsigned operand is a
6783 // constant which cannot collide with a overflowed signed operand,
6784 // then reinterpreting the signed operand as unsigned will not
6785 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006786 if (E->isEqualityOp()) {
6787 unsigned comparisonWidth = S.Context.getIntWidth(T);
6788 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006789
John McCallcc7e5bf2010-05-06 08:58:33 +00006790 // We should never be unable to prove that the unsigned operand is
6791 // non-negative.
6792 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6793
6794 if (unsignedRange.Width < comparisonWidth)
6795 return;
6796 }
6797
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006798 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6799 S.PDiag(diag::warn_mixed_sign_comparison)
6800 << LHS->getType() << RHS->getType()
6801 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006802}
6803
John McCall1f425642010-11-11 03:21:53 +00006804/// Analyzes an attempt to assign the given value to a bitfield.
6805///
6806/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006807static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6808 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006809 assert(Bitfield->isBitField());
6810 if (Bitfield->isInvalidDecl())
6811 return false;
6812
John McCalldeebbcf2010-11-11 05:33:51 +00006813 // White-list bool bitfields.
6814 if (Bitfield->getType()->isBooleanType())
6815 return false;
6816
Douglas Gregor789adec2011-02-04 13:09:01 +00006817 // Ignore value- or type-dependent expressions.
6818 if (Bitfield->getBitWidth()->isValueDependent() ||
6819 Bitfield->getBitWidth()->isTypeDependent() ||
6820 Init->isValueDependent() ||
6821 Init->isTypeDependent())
6822 return false;
6823
John McCall1f425642010-11-11 03:21:53 +00006824 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6825
Richard Smith5fab0c92011-12-28 19:48:30 +00006826 llvm::APSInt Value;
6827 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006828 return false;
6829
John McCall1f425642010-11-11 03:21:53 +00006830 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006831 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006832
6833 if (OriginalWidth <= FieldWidth)
6834 return false;
6835
Eli Friedmanc267a322012-01-26 23:11:39 +00006836 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006837 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006838 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006839
Eli Friedmanc267a322012-01-26 23:11:39 +00006840 // Check whether the stored value is equal to the original value.
6841 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006842 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006843 return false;
6844
Eli Friedmanc267a322012-01-26 23:11:39 +00006845 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006846 // therefore don't strictly fit into a signed bitfield of width 1.
6847 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006848 return false;
6849
John McCall1f425642010-11-11 03:21:53 +00006850 std::string PrettyValue = Value.toString(10);
6851 std::string PrettyTrunc = TruncatedValue.toString(10);
6852
6853 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6854 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6855 << Init->getSourceRange();
6856
6857 return true;
6858}
6859
John McCalld2a53122010-11-09 23:24:47 +00006860/// Analyze the given simple or compound assignment for warning-worthy
6861/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006862static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006863 // Just recurse on the LHS.
6864 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6865
6866 // We want to recurse on the RHS as normal unless we're assigning to
6867 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006868 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006869 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006870 E->getOperatorLoc())) {
6871 // Recurse, ignoring any implicit conversions on the RHS.
6872 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6873 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006874 }
6875 }
6876
6877 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6878}
6879
John McCall263a48b2010-01-04 23:31:57 +00006880/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006881static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006882 SourceLocation CContext, unsigned diag,
6883 bool pruneControlFlow = false) {
6884 if (pruneControlFlow) {
6885 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6886 S.PDiag(diag)
6887 << SourceType << T << E->getSourceRange()
6888 << SourceRange(CContext));
6889 return;
6890 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006891 S.Diag(E->getExprLoc(), diag)
6892 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6893}
6894
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006895/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006896static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006897 SourceLocation CContext, unsigned diag,
6898 bool pruneControlFlow = false) {
6899 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006900}
6901
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006902/// Diagnose an implicit cast from a literal expression. Does not warn when the
6903/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006904void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6905 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006906 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006907 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006908 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006909 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6910 T->hasUnsignedIntegerRepresentation());
6911 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006912 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006913 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006914 return;
6915
Eli Friedman07185912013-08-29 23:44:43 +00006916 // FIXME: Force the precision of the source value down so we don't print
6917 // digits which are usually useless (we don't really care here if we
6918 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6919 // would automatically print the shortest representation, but it's a bit
6920 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006921 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006922 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6923 precision = (precision * 59 + 195) / 196;
6924 Value.toString(PrettySourceValue, precision);
6925
David Blaikie9b88cc02012-05-15 17:18:27 +00006926 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006927 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6928 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6929 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006930 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006931
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006932 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006933 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6934 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006935}
6936
John McCall18a2c2c2010-11-09 22:22:12 +00006937std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6938 if (!Range.Width) return "0";
6939
6940 llvm::APSInt ValueInRange = Value;
6941 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006942 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006943 return ValueInRange.toString(10);
6944}
6945
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006946static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6947 if (!isa<ImplicitCastExpr>(Ex))
6948 return false;
6949
6950 Expr *InnerE = Ex->IgnoreParenImpCasts();
6951 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6952 const Type *Source =
6953 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6954 if (Target->isDependentType())
6955 return false;
6956
6957 const BuiltinType *FloatCandidateBT =
6958 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6959 const Type *BoolCandidateType = ToBool ? Target : Source;
6960
6961 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6962 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6963}
6964
6965void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6966 SourceLocation CC) {
6967 unsigned NumArgs = TheCall->getNumArgs();
6968 for (unsigned i = 0; i < NumArgs; ++i) {
6969 Expr *CurrA = TheCall->getArg(i);
6970 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6971 continue;
6972
6973 bool IsSwapped = ((i > 0) &&
6974 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6975 IsSwapped |= ((i < (NumArgs - 1)) &&
6976 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6977 if (IsSwapped) {
6978 // Warn on this floating-point to bool conversion.
6979 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6980 CurrA->getType(), CC,
6981 diag::warn_impcast_floating_point_to_bool);
6982 }
6983 }
6984}
6985
Richard Trieu5b993502014-10-15 03:42:06 +00006986static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6987 SourceLocation CC) {
6988 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6989 E->getExprLoc()))
6990 return;
6991
6992 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6993 const Expr::NullPointerConstantKind NullKind =
6994 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6995 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6996 return;
6997
6998 // Return if target type is a safe conversion.
6999 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7000 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7001 return;
7002
7003 SourceLocation Loc = E->getSourceRange().getBegin();
7004
7005 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7006 if (NullKind == Expr::NPCK_GNUNull) {
7007 if (Loc.isMacroID())
7008 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7009 }
7010
7011 // Only warn if the null and context location are in the same macro expansion.
7012 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7013 return;
7014
7015 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7016 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7017 << FixItHint::CreateReplacement(Loc,
7018 S.getFixItZeroLiteralForType(T, Loc));
7019}
7020
Douglas Gregor5054cb02015-07-07 03:58:22 +00007021static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7022 ObjCArrayLiteral *ArrayLiteral);
7023static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7024 ObjCDictionaryLiteral *DictionaryLiteral);
7025
7026/// Check a single element within a collection literal against the
7027/// target element type.
7028static void checkObjCCollectionLiteralElement(Sema &S,
7029 QualType TargetElementType,
7030 Expr *Element,
7031 unsigned ElementKind) {
7032 // Skip a bitcast to 'id' or qualified 'id'.
7033 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7034 if (ICE->getCastKind() == CK_BitCast &&
7035 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7036 Element = ICE->getSubExpr();
7037 }
7038
7039 QualType ElementType = Element->getType();
7040 ExprResult ElementResult(Element);
7041 if (ElementType->getAs<ObjCObjectPointerType>() &&
7042 S.CheckSingleAssignmentConstraints(TargetElementType,
7043 ElementResult,
7044 false, false)
7045 != Sema::Compatible) {
7046 S.Diag(Element->getLocStart(),
7047 diag::warn_objc_collection_literal_element)
7048 << ElementType << ElementKind << TargetElementType
7049 << Element->getSourceRange();
7050 }
7051
7052 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7053 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7054 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7055 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7056}
7057
7058/// Check an Objective-C array literal being converted to the given
7059/// target type.
7060static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7061 ObjCArrayLiteral *ArrayLiteral) {
7062 if (!S.NSArrayDecl)
7063 return;
7064
7065 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7066 if (!TargetObjCPtr)
7067 return;
7068
7069 if (TargetObjCPtr->isUnspecialized() ||
7070 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7071 != S.NSArrayDecl->getCanonicalDecl())
7072 return;
7073
7074 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7075 if (TypeArgs.size() != 1)
7076 return;
7077
7078 QualType TargetElementType = TypeArgs[0];
7079 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7080 checkObjCCollectionLiteralElement(S, TargetElementType,
7081 ArrayLiteral->getElement(I),
7082 0);
7083 }
7084}
7085
7086/// Check an Objective-C dictionary literal being converted to the given
7087/// target type.
7088static void checkObjCDictionaryLiteral(
7089 Sema &S, QualType TargetType,
7090 ObjCDictionaryLiteral *DictionaryLiteral) {
7091 if (!S.NSDictionaryDecl)
7092 return;
7093
7094 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7095 if (!TargetObjCPtr)
7096 return;
7097
7098 if (TargetObjCPtr->isUnspecialized() ||
7099 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7100 != S.NSDictionaryDecl->getCanonicalDecl())
7101 return;
7102
7103 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7104 if (TypeArgs.size() != 2)
7105 return;
7106
7107 QualType TargetKeyType = TypeArgs[0];
7108 QualType TargetObjectType = TypeArgs[1];
7109 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7110 auto Element = DictionaryLiteral->getKeyValueElement(I);
7111 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7112 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7113 }
7114}
7115
John McCallcc7e5bf2010-05-06 08:58:33 +00007116void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007117 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007118 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007119
John McCallcc7e5bf2010-05-06 08:58:33 +00007120 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7121 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7122 if (Source == Target) return;
7123 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007124
Chandler Carruthc22845a2011-07-26 05:40:03 +00007125 // If the conversion context location is invalid don't complain. We also
7126 // don't want to emit a warning if the issue occurs from the expansion of
7127 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7128 // delay this check as long as possible. Once we detect we are in that
7129 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007130 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007131 return;
7132
Richard Trieu021baa32011-09-23 20:10:00 +00007133 // Diagnose implicit casts to bool.
7134 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7135 if (isa<StringLiteral>(E))
7136 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007137 // and expressions, for instance, assert(0 && "error here"), are
7138 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007139 return DiagnoseImpCast(S, E, T, CC,
7140 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007141 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7142 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7143 // This covers the literal expressions that evaluate to Objective-C
7144 // objects.
7145 return DiagnoseImpCast(S, E, T, CC,
7146 diag::warn_impcast_objective_c_literal_to_bool);
7147 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007148 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7149 // Warn on pointer to bool conversion that is always true.
7150 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7151 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007152 }
Richard Trieu021baa32011-09-23 20:10:00 +00007153 }
John McCall263a48b2010-01-04 23:31:57 +00007154
Douglas Gregor5054cb02015-07-07 03:58:22 +00007155 // Check implicit casts from Objective-C collection literals to specialized
7156 // collection types, e.g., NSArray<NSString *> *.
7157 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7158 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7159 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7160 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7161
John McCall263a48b2010-01-04 23:31:57 +00007162 // Strip vector types.
7163 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007164 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007165 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007166 return;
John McCallacf0ee52010-10-08 02:01:28 +00007167 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007168 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007169
7170 // If the vector cast is cast between two vectors of the same size, it is
7171 // a bitcast, not a conversion.
7172 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7173 return;
John McCall263a48b2010-01-04 23:31:57 +00007174
7175 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7176 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7177 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007178 if (auto VecTy = dyn_cast<VectorType>(Target))
7179 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007180
7181 // Strip complex types.
7182 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007183 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007184 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007185 return;
7186
John McCallacf0ee52010-10-08 02:01:28 +00007187 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007188 }
John McCall263a48b2010-01-04 23:31:57 +00007189
7190 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7191 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7192 }
7193
7194 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7195 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7196
7197 // If the source is floating point...
7198 if (SourceBT && SourceBT->isFloatingPoint()) {
7199 // ...and the target is floating point...
7200 if (TargetBT && TargetBT->isFloatingPoint()) {
7201 // ...then warn if we're dropping FP rank.
7202
7203 // Builtin FP kinds are ordered by increasing FP rank.
7204 if (SourceBT->getKind() > TargetBT->getKind()) {
7205 // Don't warn about float constants that are precisely
7206 // representable in the target type.
7207 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007208 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007209 // Value might be a float, a float vector, or a float complex.
7210 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007211 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7212 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007213 return;
7214 }
7215
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007216 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007217 return;
7218
John McCallacf0ee52010-10-08 02:01:28 +00007219 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007220
7221 }
7222 // ... or possibly if we're increasing rank, too
7223 else if (TargetBT->getKind() > SourceBT->getKind()) {
7224 if (S.SourceMgr.isInSystemMacro(CC))
7225 return;
7226
7227 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007228 }
7229 return;
7230 }
7231
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007232 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007233 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007234 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007235 return;
7236
Chandler Carruth22c7a792011-02-17 11:05:49 +00007237 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007238 // We also want to warn on, e.g., "int i = -1.234"
7239 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7240 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7241 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7242
Chandler Carruth016ef402011-04-10 08:36:24 +00007243 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7244 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007245 } else {
7246 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7247 }
7248 }
John McCall263a48b2010-01-04 23:31:57 +00007249
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007250 // If the target is bool, warn if expr is a function or method call.
7251 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7252 isa<CallExpr>(E)) {
7253 // Check last argument of function call to see if it is an
7254 // implicit cast from a type matching the type the result
7255 // is being cast to.
7256 CallExpr *CEx = cast<CallExpr>(E);
7257 unsigned NumArgs = CEx->getNumArgs();
7258 if (NumArgs > 0) {
7259 Expr *LastA = CEx->getArg(NumArgs - 1);
7260 Expr *InnerE = LastA->IgnoreParenImpCasts();
7261 const Type *InnerType =
7262 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7263 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7264 // Warn on this floating-point to bool conversion
7265 DiagnoseImpCast(S, E, T, CC,
7266 diag::warn_impcast_floating_point_to_bool);
7267 }
7268 }
7269 }
John McCall263a48b2010-01-04 23:31:57 +00007270 return;
7271 }
7272
Richard Trieu5b993502014-10-15 03:42:06 +00007273 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007274
David Blaikie9366d2b2012-06-19 21:19:06 +00007275 if (!Source->isIntegerType() || !Target->isIntegerType())
7276 return;
7277
David Blaikie7555b6a2012-05-15 16:56:36 +00007278 // TODO: remove this early return once the false positives for constant->bool
7279 // in templates, macros, etc, are reduced or removed.
7280 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7281 return;
7282
John McCallcc7e5bf2010-05-06 08:58:33 +00007283 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007284 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007285
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007286 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007287 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007288 // TODO: this should happen for bitfield stores, too.
7289 llvm::APSInt Value(32);
7290 if (E->isIntegerConstantExpr(Value, S.Context)) {
7291 if (S.SourceMgr.isInSystemMacro(CC))
7292 return;
7293
John McCall18a2c2c2010-11-09 22:22:12 +00007294 std::string PrettySourceValue = Value.toString(10);
7295 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007296
Ted Kremenek33ba9952011-10-22 02:37:33 +00007297 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7298 S.PDiag(diag::warn_impcast_integer_precision_constant)
7299 << PrettySourceValue << PrettyTargetValue
7300 << E->getType() << T << E->getSourceRange()
7301 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007302 return;
7303 }
7304
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007305 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7306 if (S.SourceMgr.isInSystemMacro(CC))
7307 return;
7308
David Blaikie9455da02012-04-12 22:40:54 +00007309 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007310 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7311 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007312 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007313 }
7314
7315 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7316 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7317 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007318
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007319 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007320 return;
7321
John McCallcc7e5bf2010-05-06 08:58:33 +00007322 unsigned DiagID = diag::warn_impcast_integer_sign;
7323
7324 // Traditionally, gcc has warned about this under -Wsign-compare.
7325 // We also want to warn about it in -Wconversion.
7326 // So if -Wconversion is off, use a completely identical diagnostic
7327 // in the sign-compare group.
7328 // The conditional-checking code will
7329 if (ICContext) {
7330 DiagID = diag::warn_impcast_integer_sign_conditional;
7331 *ICContext = true;
7332 }
7333
John McCallacf0ee52010-10-08 02:01:28 +00007334 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007335 }
7336
Douglas Gregora78f1932011-02-22 02:45:07 +00007337 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007338 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7339 // type, to give us better diagnostics.
7340 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007341 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7343 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7344 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7345 SourceType = S.Context.getTypeDeclType(Enum);
7346 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7347 }
7348 }
7349
Douglas Gregora78f1932011-02-22 02:45:07 +00007350 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7351 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007352 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7353 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007354 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007355 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007356 return;
7357
Douglas Gregor364f7db2011-03-12 00:14:31 +00007358 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007359 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007360 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007361
John McCall263a48b2010-01-04 23:31:57 +00007362 return;
7363}
7364
David Blaikie18e9ac72012-05-15 21:57:38 +00007365void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7366 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007367
7368void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007369 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007370 E = E->IgnoreParenImpCasts();
7371
7372 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007373 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007374
John McCallacf0ee52010-10-08 02:01:28 +00007375 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007376 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007377 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007378 return;
7379}
7380
David Blaikie18e9ac72012-05-15 21:57:38 +00007381void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7382 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007383 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007384
7385 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007386 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7387 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007388
7389 // If -Wconversion would have warned about either of the candidates
7390 // for a signedness conversion to the context type...
7391 if (!Suspicious) return;
7392
7393 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007394 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007395 return;
7396
John McCallcc7e5bf2010-05-06 08:58:33 +00007397 // ...then check whether it would have warned about either of the
7398 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007399 if (E->getType() == T) return;
7400
7401 Suspicious = false;
7402 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7403 E->getType(), CC, &Suspicious);
7404 if (!Suspicious)
7405 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007406 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007407}
7408
Richard Trieu65724892014-11-15 06:37:39 +00007409/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7410/// Input argument E is a logical expression.
7411static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7412 if (S.getLangOpts().Bool)
7413 return;
7414 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7415}
7416
John McCallcc7e5bf2010-05-06 08:58:33 +00007417/// AnalyzeImplicitConversions - Find and report any interesting
7418/// implicit conversions in the given expression. There are a couple
7419/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007420void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007421 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007422 Expr *E = OrigE->IgnoreParenImpCasts();
7423
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007424 if (E->isTypeDependent() || E->isValueDependent())
7425 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007426
John McCallcc7e5bf2010-05-06 08:58:33 +00007427 // For conditional operators, we analyze the arguments as if they
7428 // were being fed directly into the output.
7429 if (isa<ConditionalOperator>(E)) {
7430 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007431 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007432 return;
7433 }
7434
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007435 // Check implicit argument conversions for function calls.
7436 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7437 CheckImplicitArgumentConversions(S, Call, CC);
7438
John McCallcc7e5bf2010-05-06 08:58:33 +00007439 // Go ahead and check any implicit conversions we might have skipped.
7440 // The non-canonical typecheck is just an optimization;
7441 // CheckImplicitConversion will filter out dead implicit conversions.
7442 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007443 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007444
7445 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007446
7447 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007448 if (POE->getResultExpr())
7449 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007450 }
7451
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007452 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7453 if (OVE->getSourceExpr())
7454 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7455 return;
7456 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007457
John McCallcc7e5bf2010-05-06 08:58:33 +00007458 // Skip past explicit casts.
7459 if (isa<ExplicitCastExpr>(E)) {
7460 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007461 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007462 }
7463
John McCalld2a53122010-11-09 23:24:47 +00007464 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7465 // Do a somewhat different check with comparison operators.
7466 if (BO->isComparisonOp())
7467 return AnalyzeComparison(S, BO);
7468
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007469 // And with simple assignments.
7470 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007471 return AnalyzeAssignment(S, BO);
7472 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007473
7474 // These break the otherwise-useful invariant below. Fortunately,
7475 // we don't really need to recurse into them, because any internal
7476 // expressions should have been analyzed already when they were
7477 // built into statements.
7478 if (isa<StmtExpr>(E)) return;
7479
7480 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007481 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007482
7483 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007484 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007485 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007486 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007487 for (Stmt *SubStmt : E->children()) {
7488 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007489 if (!ChildExpr)
7490 continue;
7491
Richard Trieu955231d2014-01-25 01:10:35 +00007492 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007493 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007494 // Ignore checking string literals that are in logical and operators.
7495 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007496 continue;
7497 AnalyzeImplicitConversions(S, ChildExpr, CC);
7498 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007499
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007500 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007501 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7502 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007503 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007504
7505 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7506 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007507 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007508 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007509
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007510 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7511 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007512 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007513}
7514
7515} // end anonymous namespace
7516
Richard Trieu3bb8b562014-02-26 02:36:06 +00007517enum {
7518 AddressOf,
7519 FunctionPointer,
7520 ArrayPointer
7521};
7522
Richard Trieuc1888e02014-06-28 23:25:37 +00007523// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7524// Returns true when emitting a warning about taking the address of a reference.
7525static bool CheckForReference(Sema &SemaRef, const Expr *E,
7526 PartialDiagnostic PD) {
7527 E = E->IgnoreParenImpCasts();
7528
7529 const FunctionDecl *FD = nullptr;
7530
7531 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7532 if (!DRE->getDecl()->getType()->isReferenceType())
7533 return false;
7534 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7535 if (!M->getMemberDecl()->getType()->isReferenceType())
7536 return false;
7537 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007538 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007539 return false;
7540 FD = Call->getDirectCallee();
7541 } else {
7542 return false;
7543 }
7544
7545 SemaRef.Diag(E->getExprLoc(), PD);
7546
7547 // If possible, point to location of function.
7548 if (FD) {
7549 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7550 }
7551
7552 return true;
7553}
7554
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007555// Returns true if the SourceLocation is expanded from any macro body.
7556// Returns false if the SourceLocation is invalid, is from not in a macro
7557// expansion, or is from expanded from a top-level macro argument.
7558static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7559 if (Loc.isInvalid())
7560 return false;
7561
7562 while (Loc.isMacroID()) {
7563 if (SM.isMacroBodyExpansion(Loc))
7564 return true;
7565 Loc = SM.getImmediateMacroCallerLoc(Loc);
7566 }
7567
7568 return false;
7569}
7570
Richard Trieu3bb8b562014-02-26 02:36:06 +00007571/// \brief Diagnose pointers that are always non-null.
7572/// \param E the expression containing the pointer
7573/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7574/// compared to a null pointer
7575/// \param IsEqual True when the comparison is equal to a null pointer
7576/// \param Range Extra SourceRange to highlight in the diagnostic
7577void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7578 Expr::NullPointerConstantKind NullKind,
7579 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007580 if (!E)
7581 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007582
7583 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007584 if (E->getExprLoc().isMacroID()) {
7585 const SourceManager &SM = getSourceManager();
7586 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7587 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007588 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007589 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007590 E = E->IgnoreImpCasts();
7591
7592 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7593
Richard Trieuf7432752014-06-06 21:39:26 +00007594 if (isa<CXXThisExpr>(E)) {
7595 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7596 : diag::warn_this_bool_conversion;
7597 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7598 return;
7599 }
7600
Richard Trieu3bb8b562014-02-26 02:36:06 +00007601 bool IsAddressOf = false;
7602
7603 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7604 if (UO->getOpcode() != UO_AddrOf)
7605 return;
7606 IsAddressOf = true;
7607 E = UO->getSubExpr();
7608 }
7609
Richard Trieuc1888e02014-06-28 23:25:37 +00007610 if (IsAddressOf) {
7611 unsigned DiagID = IsCompare
7612 ? diag::warn_address_of_reference_null_compare
7613 : diag::warn_address_of_reference_bool_conversion;
7614 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7615 << IsEqual;
7616 if (CheckForReference(*this, E, PD)) {
7617 return;
7618 }
7619 }
7620
Richard Trieu3bb8b562014-02-26 02:36:06 +00007621 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007622 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007623 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7624 D = R->getDecl();
7625 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7626 D = M->getMemberDecl();
7627 }
7628
7629 // Weak Decls can be null.
7630 if (!D || D->isWeak())
7631 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007632
7633 // Check for parameter decl with nonnull attribute
7634 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7635 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7636 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7637 unsigned NumArgs = FD->getNumParams();
7638 llvm::SmallBitVector AttrNonNull(NumArgs);
7639 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7640 if (!NonNull->args_size()) {
7641 AttrNonNull.set(0, NumArgs);
7642 break;
7643 }
7644 for (unsigned Val : NonNull->args()) {
7645 if (Val >= NumArgs)
7646 continue;
7647 AttrNonNull.set(Val);
7648 }
7649 }
7650 if (!AttrNonNull.empty())
7651 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007652 if (FD->getParamDecl(i) == PV &&
7653 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007654 std::string Str;
7655 llvm::raw_string_ostream S(Str);
7656 E->printPretty(S, nullptr, getPrintingPolicy());
7657 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7658 : diag::warn_cast_nonnull_to_bool;
7659 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7660 << Range << IsEqual;
7661 return;
7662 }
7663 }
7664 }
7665
Richard Trieu3bb8b562014-02-26 02:36:06 +00007666 QualType T = D->getType();
7667 const bool IsArray = T->isArrayType();
7668 const bool IsFunction = T->isFunctionType();
7669
Richard Trieuc1888e02014-06-28 23:25:37 +00007670 // Address of function is used to silence the function warning.
7671 if (IsAddressOf && IsFunction) {
7672 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007673 }
7674
7675 // Found nothing.
7676 if (!IsAddressOf && !IsFunction && !IsArray)
7677 return;
7678
7679 // Pretty print the expression for the diagnostic.
7680 std::string Str;
7681 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007682 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007683
7684 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7685 : diag::warn_impcast_pointer_to_bool;
7686 unsigned DiagType;
7687 if (IsAddressOf)
7688 DiagType = AddressOf;
7689 else if (IsFunction)
7690 DiagType = FunctionPointer;
7691 else if (IsArray)
7692 DiagType = ArrayPointer;
7693 else
7694 llvm_unreachable("Could not determine diagnostic.");
7695 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7696 << Range << IsEqual;
7697
7698 if (!IsFunction)
7699 return;
7700
7701 // Suggest '&' to silence the function warning.
7702 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7703 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7704
7705 // Check to see if '()' fixit should be emitted.
7706 QualType ReturnType;
7707 UnresolvedSet<4> NonTemplateOverloads;
7708 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7709 if (ReturnType.isNull())
7710 return;
7711
7712 if (IsCompare) {
7713 // There are two cases here. If there is null constant, the only suggest
7714 // for a pointer return type. If the null is 0, then suggest if the return
7715 // type is a pointer or an integer type.
7716 if (!ReturnType->isPointerType()) {
7717 if (NullKind == Expr::NPCK_ZeroExpression ||
7718 NullKind == Expr::NPCK_ZeroLiteral) {
7719 if (!ReturnType->isIntegerType())
7720 return;
7721 } else {
7722 return;
7723 }
7724 }
7725 } else { // !IsCompare
7726 // For function to bool, only suggest if the function pointer has bool
7727 // return type.
7728 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7729 return;
7730 }
7731 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007732 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007733}
7734
7735
John McCallcc7e5bf2010-05-06 08:58:33 +00007736/// Diagnoses "dangerous" implicit conversions within the given
7737/// expression (which is a full expression). Implements -Wconversion
7738/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007739///
7740/// \param CC the "context" location of the implicit conversion, i.e.
7741/// the most location of the syntactic entity requiring the implicit
7742/// conversion
7743void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007744 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007745 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007746 return;
7747
7748 // Don't diagnose for value- or type-dependent expressions.
7749 if (E->isTypeDependent() || E->isValueDependent())
7750 return;
7751
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007752 // Check for array bounds violations in cases where the check isn't triggered
7753 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7754 // ArraySubscriptExpr is on the RHS of a variable initialization.
7755 CheckArrayAccess(E);
7756
John McCallacf0ee52010-10-08 02:01:28 +00007757 // This is not the right CC for (e.g.) a variable initialization.
7758 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007759}
7760
Richard Trieu65724892014-11-15 06:37:39 +00007761/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7762/// Input argument E is a logical expression.
7763void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7764 ::CheckBoolLikeConversion(*this, E, CC);
7765}
7766
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007767/// Diagnose when expression is an integer constant expression and its evaluation
7768/// results in integer overflow
7769void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007770 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7771 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007772}
7773
Richard Smithc406cb72013-01-17 01:17:56 +00007774namespace {
7775/// \brief Visitor for expressions which looks for unsequenced operations on the
7776/// same object.
7777class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007778 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7779
Richard Smithc406cb72013-01-17 01:17:56 +00007780 /// \brief A tree of sequenced regions within an expression. Two regions are
7781 /// unsequenced if one is an ancestor or a descendent of the other. When we
7782 /// finish processing an expression with sequencing, such as a comma
7783 /// expression, we fold its tree nodes into its parent, since they are
7784 /// unsequenced with respect to nodes we will visit later.
7785 class SequenceTree {
7786 struct Value {
7787 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7788 unsigned Parent : 31;
7789 bool Merged : 1;
7790 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007791 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007792
7793 public:
7794 /// \brief A region within an expression which may be sequenced with respect
7795 /// to some other region.
7796 class Seq {
7797 explicit Seq(unsigned N) : Index(N) {}
7798 unsigned Index;
7799 friend class SequenceTree;
7800 public:
7801 Seq() : Index(0) {}
7802 };
7803
7804 SequenceTree() { Values.push_back(Value(0)); }
7805 Seq root() const { return Seq(0); }
7806
7807 /// \brief Create a new sequence of operations, which is an unsequenced
7808 /// subset of \p Parent. This sequence of operations is sequenced with
7809 /// respect to other children of \p Parent.
7810 Seq allocate(Seq Parent) {
7811 Values.push_back(Value(Parent.Index));
7812 return Seq(Values.size() - 1);
7813 }
7814
7815 /// \brief Merge a sequence of operations into its parent.
7816 void merge(Seq S) {
7817 Values[S.Index].Merged = true;
7818 }
7819
7820 /// \brief Determine whether two operations are unsequenced. This operation
7821 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7822 /// should have been merged into its parent as appropriate.
7823 bool isUnsequenced(Seq Cur, Seq Old) {
7824 unsigned C = representative(Cur.Index);
7825 unsigned Target = representative(Old.Index);
7826 while (C >= Target) {
7827 if (C == Target)
7828 return true;
7829 C = Values[C].Parent;
7830 }
7831 return false;
7832 }
7833
7834 private:
7835 /// \brief Pick a representative for a sequence.
7836 unsigned representative(unsigned K) {
7837 if (Values[K].Merged)
7838 // Perform path compression as we go.
7839 return Values[K].Parent = representative(Values[K].Parent);
7840 return K;
7841 }
7842 };
7843
7844 /// An object for which we can track unsequenced uses.
7845 typedef NamedDecl *Object;
7846
7847 /// Different flavors of object usage which we track. We only track the
7848 /// least-sequenced usage of each kind.
7849 enum UsageKind {
7850 /// A read of an object. Multiple unsequenced reads are OK.
7851 UK_Use,
7852 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007853 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007854 UK_ModAsValue,
7855 /// A modification of an object which is not sequenced before the value
7856 /// computation of the expression, such as n++.
7857 UK_ModAsSideEffect,
7858
7859 UK_Count = UK_ModAsSideEffect + 1
7860 };
7861
7862 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007863 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007864 Expr *Use;
7865 SequenceTree::Seq Seq;
7866 };
7867
7868 struct UsageInfo {
7869 UsageInfo() : Diagnosed(false) {}
7870 Usage Uses[UK_Count];
7871 /// Have we issued a diagnostic for this variable already?
7872 bool Diagnosed;
7873 };
7874 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7875
7876 Sema &SemaRef;
7877 /// Sequenced regions within the expression.
7878 SequenceTree Tree;
7879 /// Declaration modifications and references which we have seen.
7880 UsageInfoMap UsageMap;
7881 /// The region we are currently within.
7882 SequenceTree::Seq Region;
7883 /// Filled in with declarations which were modified as a side-effect
7884 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007885 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007886 /// Expressions to check later. We defer checking these to reduce
7887 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007888 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007889
7890 /// RAII object wrapping the visitation of a sequenced subexpression of an
7891 /// expression. At the end of this process, the side-effects of the evaluation
7892 /// become sequenced with respect to the value computation of the result, so
7893 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7894 /// UK_ModAsValue.
7895 struct SequencedSubexpression {
7896 SequencedSubexpression(SequenceChecker &Self)
7897 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7898 Self.ModAsSideEffect = &ModAsSideEffect;
7899 }
7900 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007901 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7902 MI != ME; ++MI) {
7903 UsageInfo &U = Self.UsageMap[MI->first];
7904 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7905 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7906 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007907 }
7908 Self.ModAsSideEffect = OldModAsSideEffect;
7909 }
7910
7911 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007912 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7913 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007914 };
7915
Richard Smith40238f02013-06-20 22:21:56 +00007916 /// RAII object wrapping the visitation of a subexpression which we might
7917 /// choose to evaluate as a constant. If any subexpression is evaluated and
7918 /// found to be non-constant, this allows us to suppress the evaluation of
7919 /// the outer expression.
7920 class EvaluationTracker {
7921 public:
7922 EvaluationTracker(SequenceChecker &Self)
7923 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7924 Self.EvalTracker = this;
7925 }
7926 ~EvaluationTracker() {
7927 Self.EvalTracker = Prev;
7928 if (Prev)
7929 Prev->EvalOK &= EvalOK;
7930 }
7931
7932 bool evaluate(const Expr *E, bool &Result) {
7933 if (!EvalOK || E->isValueDependent())
7934 return false;
7935 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7936 return EvalOK;
7937 }
7938
7939 private:
7940 SequenceChecker &Self;
7941 EvaluationTracker *Prev;
7942 bool EvalOK;
7943 } *EvalTracker;
7944
Richard Smithc406cb72013-01-17 01:17:56 +00007945 /// \brief Find the object which is produced by the specified expression,
7946 /// if any.
7947 Object getObject(Expr *E, bool Mod) const {
7948 E = E->IgnoreParenCasts();
7949 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7950 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7951 return getObject(UO->getSubExpr(), Mod);
7952 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7953 if (BO->getOpcode() == BO_Comma)
7954 return getObject(BO->getRHS(), Mod);
7955 if (Mod && BO->isAssignmentOp())
7956 return getObject(BO->getLHS(), Mod);
7957 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7958 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7959 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7960 return ME->getMemberDecl();
7961 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7962 // FIXME: If this is a reference, map through to its value.
7963 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007964 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007965 }
7966
7967 /// \brief Note that an object was modified or used by an expression.
7968 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7969 Usage &U = UI.Uses[UK];
7970 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7971 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7972 ModAsSideEffect->push_back(std::make_pair(O, U));
7973 U.Use = Ref;
7974 U.Seq = Region;
7975 }
7976 }
7977 /// \brief Check whether a modification or use conflicts with a prior usage.
7978 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7979 bool IsModMod) {
7980 if (UI.Diagnosed)
7981 return;
7982
7983 const Usage &U = UI.Uses[OtherKind];
7984 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7985 return;
7986
7987 Expr *Mod = U.Use;
7988 Expr *ModOrUse = Ref;
7989 if (OtherKind == UK_Use)
7990 std::swap(Mod, ModOrUse);
7991
7992 SemaRef.Diag(Mod->getExprLoc(),
7993 IsModMod ? diag::warn_unsequenced_mod_mod
7994 : diag::warn_unsequenced_mod_use)
7995 << O << SourceRange(ModOrUse->getExprLoc());
7996 UI.Diagnosed = true;
7997 }
7998
7999 void notePreUse(Object O, Expr *Use) {
8000 UsageInfo &U = UsageMap[O];
8001 // Uses conflict with other modifications.
8002 checkUsage(O, U, Use, UK_ModAsValue, false);
8003 }
8004 void notePostUse(Object O, Expr *Use) {
8005 UsageInfo &U = UsageMap[O];
8006 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8007 addUsage(U, O, Use, UK_Use);
8008 }
8009
8010 void notePreMod(Object O, Expr *Mod) {
8011 UsageInfo &U = UsageMap[O];
8012 // Modifications conflict with other modifications and with uses.
8013 checkUsage(O, U, Mod, UK_ModAsValue, true);
8014 checkUsage(O, U, Mod, UK_Use, false);
8015 }
8016 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8017 UsageInfo &U = UsageMap[O];
8018 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8019 addUsage(U, O, Use, UK);
8020 }
8021
8022public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008023 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008024 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8025 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008026 Visit(E);
8027 }
8028
8029 void VisitStmt(Stmt *S) {
8030 // Skip all statements which aren't expressions for now.
8031 }
8032
8033 void VisitExpr(Expr *E) {
8034 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008035 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008036 }
8037
8038 void VisitCastExpr(CastExpr *E) {
8039 Object O = Object();
8040 if (E->getCastKind() == CK_LValueToRValue)
8041 O = getObject(E->getSubExpr(), false);
8042
8043 if (O)
8044 notePreUse(O, E);
8045 VisitExpr(E);
8046 if (O)
8047 notePostUse(O, E);
8048 }
8049
8050 void VisitBinComma(BinaryOperator *BO) {
8051 // C++11 [expr.comma]p1:
8052 // Every value computation and side effect associated with the left
8053 // expression is sequenced before every value computation and side
8054 // effect associated with the right expression.
8055 SequenceTree::Seq LHS = Tree.allocate(Region);
8056 SequenceTree::Seq RHS = Tree.allocate(Region);
8057 SequenceTree::Seq OldRegion = Region;
8058
8059 {
8060 SequencedSubexpression SeqLHS(*this);
8061 Region = LHS;
8062 Visit(BO->getLHS());
8063 }
8064
8065 Region = RHS;
8066 Visit(BO->getRHS());
8067
8068 Region = OldRegion;
8069
8070 // Forget that LHS and RHS are sequenced. They are both unsequenced
8071 // with respect to other stuff.
8072 Tree.merge(LHS);
8073 Tree.merge(RHS);
8074 }
8075
8076 void VisitBinAssign(BinaryOperator *BO) {
8077 // The modification is sequenced after the value computation of the LHS
8078 // and RHS, so check it before inspecting the operands and update the
8079 // map afterwards.
8080 Object O = getObject(BO->getLHS(), true);
8081 if (!O)
8082 return VisitExpr(BO);
8083
8084 notePreMod(O, BO);
8085
8086 // C++11 [expr.ass]p7:
8087 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8088 // only once.
8089 //
8090 // Therefore, for a compound assignment operator, O is considered used
8091 // everywhere except within the evaluation of E1 itself.
8092 if (isa<CompoundAssignOperator>(BO))
8093 notePreUse(O, BO);
8094
8095 Visit(BO->getLHS());
8096
8097 if (isa<CompoundAssignOperator>(BO))
8098 notePostUse(O, BO);
8099
8100 Visit(BO->getRHS());
8101
Richard Smith83e37bee2013-06-26 23:16:51 +00008102 // C++11 [expr.ass]p1:
8103 // the assignment is sequenced [...] before the value computation of the
8104 // assignment expression.
8105 // C11 6.5.16/3 has no such rule.
8106 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8107 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008108 }
8109 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8110 VisitBinAssign(CAO);
8111 }
8112
8113 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8114 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8115 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8116 Object O = getObject(UO->getSubExpr(), true);
8117 if (!O)
8118 return VisitExpr(UO);
8119
8120 notePreMod(O, UO);
8121 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008122 // C++11 [expr.pre.incr]p1:
8123 // the expression ++x is equivalent to x+=1
8124 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8125 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008126 }
8127
8128 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8129 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8130 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8131 Object O = getObject(UO->getSubExpr(), true);
8132 if (!O)
8133 return VisitExpr(UO);
8134
8135 notePreMod(O, UO);
8136 Visit(UO->getSubExpr());
8137 notePostMod(O, UO, UK_ModAsSideEffect);
8138 }
8139
8140 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8141 void VisitBinLOr(BinaryOperator *BO) {
8142 // The side-effects of the LHS of an '&&' are sequenced before the
8143 // value computation of the RHS, and hence before the value computation
8144 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8145 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008146 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008147 {
8148 SequencedSubexpression Sequenced(*this);
8149 Visit(BO->getLHS());
8150 }
8151
8152 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008153 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008154 if (!Result)
8155 Visit(BO->getRHS());
8156 } else {
8157 // Check for unsequenced operations in the RHS, treating it as an
8158 // entirely separate evaluation.
8159 //
8160 // FIXME: If there are operations in the RHS which are unsequenced
8161 // with respect to operations outside the RHS, and those operations
8162 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008163 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008164 }
Richard Smithc406cb72013-01-17 01:17:56 +00008165 }
8166 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008167 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008168 {
8169 SequencedSubexpression Sequenced(*this);
8170 Visit(BO->getLHS());
8171 }
8172
8173 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008174 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008175 if (Result)
8176 Visit(BO->getRHS());
8177 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008178 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008179 }
Richard Smithc406cb72013-01-17 01:17:56 +00008180 }
8181
8182 // Only visit the condition, unless we can be sure which subexpression will
8183 // be chosen.
8184 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008185 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008186 {
8187 SequencedSubexpression Sequenced(*this);
8188 Visit(CO->getCond());
8189 }
Richard Smithc406cb72013-01-17 01:17:56 +00008190
8191 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008192 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008193 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008194 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008195 WorkList.push_back(CO->getTrueExpr());
8196 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008197 }
Richard Smithc406cb72013-01-17 01:17:56 +00008198 }
8199
Richard Smithe3dbfe02013-06-30 10:40:20 +00008200 void VisitCallExpr(CallExpr *CE) {
8201 // C++11 [intro.execution]p15:
8202 // When calling a function [...], every value computation and side effect
8203 // associated with any argument expression, or with the postfix expression
8204 // designating the called function, is sequenced before execution of every
8205 // expression or statement in the body of the function [and thus before
8206 // the value computation of its result].
8207 SequencedSubexpression Sequenced(*this);
8208 Base::VisitCallExpr(CE);
8209
8210 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8211 }
8212
Richard Smithc406cb72013-01-17 01:17:56 +00008213 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008214 // This is a call, so all subexpressions are sequenced before the result.
8215 SequencedSubexpression Sequenced(*this);
8216
Richard Smithc406cb72013-01-17 01:17:56 +00008217 if (!CCE->isListInitialization())
8218 return VisitExpr(CCE);
8219
8220 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008221 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008222 SequenceTree::Seq Parent = Region;
8223 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8224 E = CCE->arg_end();
8225 I != E; ++I) {
8226 Region = Tree.allocate(Parent);
8227 Elts.push_back(Region);
8228 Visit(*I);
8229 }
8230
8231 // Forget that the initializers are sequenced.
8232 Region = Parent;
8233 for (unsigned I = 0; I < Elts.size(); ++I)
8234 Tree.merge(Elts[I]);
8235 }
8236
8237 void VisitInitListExpr(InitListExpr *ILE) {
8238 if (!SemaRef.getLangOpts().CPlusPlus11)
8239 return VisitExpr(ILE);
8240
8241 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008242 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008243 SequenceTree::Seq Parent = Region;
8244 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8245 Expr *E = ILE->getInit(I);
8246 if (!E) continue;
8247 Region = Tree.allocate(Parent);
8248 Elts.push_back(Region);
8249 Visit(E);
8250 }
8251
8252 // Forget that the initializers are sequenced.
8253 Region = Parent;
8254 for (unsigned I = 0; I < Elts.size(); ++I)
8255 Tree.merge(Elts[I]);
8256 }
8257};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008258}
Richard Smithc406cb72013-01-17 01:17:56 +00008259
8260void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008261 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008262 WorkList.push_back(E);
8263 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008264 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008265 SequenceChecker(*this, Item, WorkList);
8266 }
Richard Smithc406cb72013-01-17 01:17:56 +00008267}
8268
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008269void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8270 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008271 CheckImplicitConversions(E, CheckLoc);
8272 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008273 if (!IsConstexpr && !E->isValueDependent())
8274 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008275}
8276
John McCall1f425642010-11-11 03:21:53 +00008277void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8278 FieldDecl *BitField,
8279 Expr *Init) {
8280 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8281}
8282
David Majnemer61a5bbf2015-04-07 22:08:51 +00008283static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8284 SourceLocation Loc) {
8285 if (!PType->isVariablyModifiedType())
8286 return;
8287 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8288 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8289 return;
8290 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008291 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8292 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8293 return;
8294 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008295 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8296 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8297 return;
8298 }
8299
8300 const ArrayType *AT = S.Context.getAsArrayType(PType);
8301 if (!AT)
8302 return;
8303
8304 if (AT->getSizeModifier() != ArrayType::Star) {
8305 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8306 return;
8307 }
8308
8309 S.Diag(Loc, diag::err_array_star_in_function_definition);
8310}
8311
Mike Stump0c2ec772010-01-21 03:59:47 +00008312/// CheckParmsForFunctionDef - Check that the parameters of the given
8313/// function are appropriate for the definition of a function. This
8314/// takes care of any checks that cannot be performed on the
8315/// declaration itself, e.g., that the types of each of the function
8316/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008317bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8318 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008319 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008320 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008321 for (; P != PEnd; ++P) {
8322 ParmVarDecl *Param = *P;
8323
Mike Stump0c2ec772010-01-21 03:59:47 +00008324 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8325 // function declarator that is part of a function definition of
8326 // that function shall not have incomplete type.
8327 //
8328 // This is also C++ [dcl.fct]p6.
8329 if (!Param->isInvalidDecl() &&
8330 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008331 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008332 Param->setInvalidDecl();
8333 HasInvalidParm = true;
8334 }
8335
8336 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8337 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008338 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008339 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008340 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008341 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008342 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008343
8344 // C99 6.7.5.3p12:
8345 // If the function declarator is not part of a definition of that
8346 // function, parameters may have incomplete type and may use the [*]
8347 // notation in their sequences of declarator specifiers to specify
8348 // variable length array types.
8349 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008350 // FIXME: This diagnostic should point the '[*]' if source-location
8351 // information is added for it.
8352 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008353
8354 // MSVC destroys objects passed by value in the callee. Therefore a
8355 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008356 // object's destructor. However, we don't perform any direct access check
8357 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008358 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8359 .getCXXABI()
8360 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008361 if (!Param->isInvalidDecl()) {
8362 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8363 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8364 if (!ClassDecl->isInvalidDecl() &&
8365 !ClassDecl->hasIrrelevantDestructor() &&
8366 !ClassDecl->isDependentContext()) {
8367 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8368 MarkFunctionReferenced(Param->getLocation(), Destructor);
8369 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8370 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008371 }
8372 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008373 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008374 }
8375
8376 return HasInvalidParm;
8377}
John McCall2b5c1b22010-08-12 21:44:57 +00008378
8379/// CheckCastAlign - Implements -Wcast-align, which warns when a
8380/// pointer cast increases the alignment requirements.
8381void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8382 // This is actually a lot of work to potentially be doing on every
8383 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008384 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008385 return;
8386
8387 // Ignore dependent types.
8388 if (T->isDependentType() || Op->getType()->isDependentType())
8389 return;
8390
8391 // Require that the destination be a pointer type.
8392 const PointerType *DestPtr = T->getAs<PointerType>();
8393 if (!DestPtr) return;
8394
8395 // If the destination has alignment 1, we're done.
8396 QualType DestPointee = DestPtr->getPointeeType();
8397 if (DestPointee->isIncompleteType()) return;
8398 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8399 if (DestAlign.isOne()) return;
8400
8401 // Require that the source be a pointer type.
8402 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8403 if (!SrcPtr) return;
8404 QualType SrcPointee = SrcPtr->getPointeeType();
8405
8406 // Whitelist casts from cv void*. We already implicitly
8407 // whitelisted casts to cv void*, since they have alignment 1.
8408 // Also whitelist casts involving incomplete types, which implicitly
8409 // includes 'void'.
8410 if (SrcPointee->isIncompleteType()) return;
8411
8412 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8413 if (SrcAlign >= DestAlign) return;
8414
8415 Diag(TRange.getBegin(), diag::warn_cast_align)
8416 << Op->getType() << T
8417 << static_cast<unsigned>(SrcAlign.getQuantity())
8418 << static_cast<unsigned>(DestAlign.getQuantity())
8419 << TRange << Op->getSourceRange();
8420}
8421
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008422static const Type* getElementType(const Expr *BaseExpr) {
8423 const Type* EltType = BaseExpr->getType().getTypePtr();
8424 if (EltType->isAnyPointerType())
8425 return EltType->getPointeeType().getTypePtr();
8426 else if (EltType->isArrayType())
8427 return EltType->getBaseElementTypeUnsafe();
8428 return EltType;
8429}
8430
Chandler Carruth28389f02011-08-05 09:10:50 +00008431/// \brief Check whether this array fits the idiom of a size-one tail padded
8432/// array member of a struct.
8433///
8434/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8435/// commonly used to emulate flexible arrays in C89 code.
8436static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8437 const NamedDecl *ND) {
8438 if (Size != 1 || !ND) return false;
8439
8440 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8441 if (!FD) return false;
8442
8443 // Don't consider sizes resulting from macro expansions or template argument
8444 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008445
8446 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008447 while (TInfo) {
8448 TypeLoc TL = TInfo->getTypeLoc();
8449 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008450 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8451 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008452 TInfo = TDL->getTypeSourceInfo();
8453 continue;
8454 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008455 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8456 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008457 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8458 return false;
8459 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008460 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008461 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008462
8463 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008464 if (!RD) return false;
8465 if (RD->isUnion()) return false;
8466 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8467 if (!CRD->isStandardLayout()) return false;
8468 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008469
Benjamin Kramer8c543672011-08-06 03:04:42 +00008470 // See if this is the last field decl in the record.
8471 const Decl *D = FD;
8472 while ((D = D->getNextDeclInContext()))
8473 if (isa<FieldDecl>(D))
8474 return false;
8475 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008476}
8477
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008478void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008479 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008480 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008481 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008482 if (IndexExpr->isValueDependent())
8483 return;
8484
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008485 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008486 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008487 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008488 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008489 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008490 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008491
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008492 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008493 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008494 return;
Richard Smith13f67182011-12-16 19:31:14 +00008495 if (IndexNegated)
8496 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008497
Craig Topperc3ec1492014-05-26 06:22:03 +00008498 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008499 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8500 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008501 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008502 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008503
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008504 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008505 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008506 if (!size.isStrictlyPositive())
8507 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008508
8509 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008510 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008511 // Make sure we're comparing apples to apples when comparing index to size
8512 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8513 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008514 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008515 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008516 if (ptrarith_typesize != array_typesize) {
8517 // There's a cast to a different size type involved
8518 uint64_t ratio = array_typesize / ptrarith_typesize;
8519 // TODO: Be smarter about handling cases where array_typesize is not a
8520 // multiple of ptrarith_typesize
8521 if (ptrarith_typesize * ratio == array_typesize)
8522 size *= llvm::APInt(size.getBitWidth(), ratio);
8523 }
8524 }
8525
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008526 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008527 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008528 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008529 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008530
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008531 // For array subscripting the index must be less than size, but for pointer
8532 // arithmetic also allow the index (offset) to be equal to size since
8533 // computing the next address after the end of the array is legal and
8534 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008535 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008536 return;
8537
8538 // Also don't warn for arrays of size 1 which are members of some
8539 // structure. These are often used to approximate flexible arrays in C89
8540 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008541 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008542 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008543
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008544 // Suppress the warning if the subscript expression (as identified by the
8545 // ']' location) and the index expression are both from macro expansions
8546 // within a system header.
8547 if (ASE) {
8548 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8549 ASE->getRBracketLoc());
8550 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8551 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8552 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008553 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008554 return;
8555 }
8556 }
8557
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008558 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008559 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008560 DiagID = diag::warn_array_index_exceeds_bounds;
8561
8562 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8563 PDiag(DiagID) << index.toString(10, true)
8564 << size.toString(10, true)
8565 << (unsigned)size.getLimitedValue(~0U)
8566 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008567 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008568 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008569 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008570 DiagID = diag::warn_ptr_arith_precedes_bounds;
8571 if (index.isNegative()) index = -index;
8572 }
8573
8574 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8575 PDiag(DiagID) << index.toString(10, true)
8576 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008577 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008578
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008579 if (!ND) {
8580 // Try harder to find a NamedDecl to point at in the note.
8581 while (const ArraySubscriptExpr *ASE =
8582 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8583 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8584 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8585 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8586 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8587 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8588 }
8589
Chandler Carruth1af88f12011-02-17 21:10:52 +00008590 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008591 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8592 PDiag(diag::note_array_index_out_of_bounds)
8593 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008594}
8595
Ted Kremenekdf26df72011-03-01 18:41:00 +00008596void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008597 int AllowOnePastEnd = 0;
8598 while (expr) {
8599 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008600 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008601 case Stmt::ArraySubscriptExprClass: {
8602 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008603 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008604 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008605 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008606 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008607 case Stmt::OMPArraySectionExprClass: {
8608 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8609 if (ASE->getLowerBound())
8610 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8611 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8612 return;
8613 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008614 case Stmt::UnaryOperatorClass: {
8615 // Only unwrap the * and & unary operators
8616 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8617 expr = UO->getSubExpr();
8618 switch (UO->getOpcode()) {
8619 case UO_AddrOf:
8620 AllowOnePastEnd++;
8621 break;
8622 case UO_Deref:
8623 AllowOnePastEnd--;
8624 break;
8625 default:
8626 return;
8627 }
8628 break;
8629 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008630 case Stmt::ConditionalOperatorClass: {
8631 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8632 if (const Expr *lhs = cond->getLHS())
8633 CheckArrayAccess(lhs);
8634 if (const Expr *rhs = cond->getRHS())
8635 CheckArrayAccess(rhs);
8636 return;
8637 }
8638 default:
8639 return;
8640 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008641 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008642}
John McCall31168b02011-06-15 23:02:42 +00008643
8644//===--- CHECK: Objective-C retain cycles ----------------------------------//
8645
8646namespace {
8647 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008648 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008649 VarDecl *Variable;
8650 SourceRange Range;
8651 SourceLocation Loc;
8652 bool Indirect;
8653
8654 void setLocsFrom(Expr *e) {
8655 Loc = e->getExprLoc();
8656 Range = e->getSourceRange();
8657 }
8658 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008659}
John McCall31168b02011-06-15 23:02:42 +00008660
8661/// Consider whether capturing the given variable can possibly lead to
8662/// a retain cycle.
8663static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008664 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008665 // lifetime. In MRR, it's captured strongly if the variable is
8666 // __block and has an appropriate type.
8667 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8668 return false;
8669
8670 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008671 if (ref)
8672 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008673 return true;
8674}
8675
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008676static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008677 while (true) {
8678 e = e->IgnoreParens();
8679 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8680 switch (cast->getCastKind()) {
8681 case CK_BitCast:
8682 case CK_LValueBitCast:
8683 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008684 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008685 e = cast->getSubExpr();
8686 continue;
8687
John McCall31168b02011-06-15 23:02:42 +00008688 default:
8689 return false;
8690 }
8691 }
8692
8693 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8694 ObjCIvarDecl *ivar = ref->getDecl();
8695 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8696 return false;
8697
8698 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008699 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008700 return false;
8701
8702 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8703 owner.Indirect = true;
8704 return true;
8705 }
8706
8707 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8708 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8709 if (!var) return false;
8710 return considerVariable(var, ref, owner);
8711 }
8712
John McCall31168b02011-06-15 23:02:42 +00008713 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8714 if (member->isArrow()) return false;
8715
8716 // Don't count this as an indirect ownership.
8717 e = member->getBase();
8718 continue;
8719 }
8720
John McCallfe96e0b2011-11-06 09:01:30 +00008721 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8722 // Only pay attention to pseudo-objects on property references.
8723 ObjCPropertyRefExpr *pre
8724 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8725 ->IgnoreParens());
8726 if (!pre) return false;
8727 if (pre->isImplicitProperty()) return false;
8728 ObjCPropertyDecl *property = pre->getExplicitProperty();
8729 if (!property->isRetaining() &&
8730 !(property->getPropertyIvarDecl() &&
8731 property->getPropertyIvarDecl()->getType()
8732 .getObjCLifetime() == Qualifiers::OCL_Strong))
8733 return false;
8734
8735 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008736 if (pre->isSuperReceiver()) {
8737 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8738 if (!owner.Variable)
8739 return false;
8740 owner.Loc = pre->getLocation();
8741 owner.Range = pre->getSourceRange();
8742 return true;
8743 }
John McCallfe96e0b2011-11-06 09:01:30 +00008744 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8745 ->getSourceExpr());
8746 continue;
8747 }
8748
John McCall31168b02011-06-15 23:02:42 +00008749 // Array ivars?
8750
8751 return false;
8752 }
8753}
8754
8755namespace {
8756 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8757 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8758 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008759 Context(Context), Variable(variable), Capturer(nullptr),
8760 VarWillBeReased(false) {}
8761 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008762 VarDecl *Variable;
8763 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008764 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008765
8766 void VisitDeclRefExpr(DeclRefExpr *ref) {
8767 if (ref->getDecl() == Variable && !Capturer)
8768 Capturer = ref;
8769 }
8770
John McCall31168b02011-06-15 23:02:42 +00008771 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8772 if (Capturer) return;
8773 Visit(ref->getBase());
8774 if (Capturer && ref->isFreeIvar())
8775 Capturer = ref;
8776 }
8777
8778 void VisitBlockExpr(BlockExpr *block) {
8779 // Look inside nested blocks
8780 if (block->getBlockDecl()->capturesVariable(Variable))
8781 Visit(block->getBlockDecl()->getBody());
8782 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008783
8784 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8785 if (Capturer) return;
8786 if (OVE->getSourceExpr())
8787 Visit(OVE->getSourceExpr());
8788 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008789 void VisitBinaryOperator(BinaryOperator *BinOp) {
8790 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8791 return;
8792 Expr *LHS = BinOp->getLHS();
8793 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8794 if (DRE->getDecl() != Variable)
8795 return;
8796 if (Expr *RHS = BinOp->getRHS()) {
8797 RHS = RHS->IgnoreParenCasts();
8798 llvm::APSInt Value;
8799 VarWillBeReased =
8800 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8801 }
8802 }
8803 }
John McCall31168b02011-06-15 23:02:42 +00008804 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008805}
John McCall31168b02011-06-15 23:02:42 +00008806
8807/// Check whether the given argument is a block which captures a
8808/// variable.
8809static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8810 assert(owner.Variable && owner.Loc.isValid());
8811
8812 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008813
8814 // Look through [^{...} copy] and Block_copy(^{...}).
8815 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8816 Selector Cmd = ME->getSelector();
8817 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8818 e = ME->getInstanceReceiver();
8819 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008820 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008821 e = e->IgnoreParenCasts();
8822 }
8823 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8824 if (CE->getNumArgs() == 1) {
8825 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008826 if (Fn) {
8827 const IdentifierInfo *FnI = Fn->getIdentifier();
8828 if (FnI && FnI->isStr("_Block_copy")) {
8829 e = CE->getArg(0)->IgnoreParenCasts();
8830 }
8831 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008832 }
8833 }
8834
John McCall31168b02011-06-15 23:02:42 +00008835 BlockExpr *block = dyn_cast<BlockExpr>(e);
8836 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008837 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008838
8839 FindCaptureVisitor visitor(S.Context, owner.Variable);
8840 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008841 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008842}
8843
8844static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8845 RetainCycleOwner &owner) {
8846 assert(capturer);
8847 assert(owner.Variable && owner.Loc.isValid());
8848
8849 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8850 << owner.Variable << capturer->getSourceRange();
8851 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8852 << owner.Indirect << owner.Range;
8853}
8854
8855/// Check for a keyword selector that starts with the word 'add' or
8856/// 'set'.
8857static bool isSetterLikeSelector(Selector sel) {
8858 if (sel.isUnarySelector()) return false;
8859
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008860 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008861 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008862 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008863 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008864 else if (str.startswith("add")) {
8865 // Specially whitelist 'addOperationWithBlock:'.
8866 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8867 return false;
8868 str = str.substr(3);
8869 }
John McCall31168b02011-06-15 23:02:42 +00008870 else
8871 return false;
8872
8873 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008874 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008875}
8876
Benjamin Kramer3a743452015-03-09 15:03:32 +00008877static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8878 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008879 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8880 Message->getReceiverInterface(),
8881 NSAPI::ClassId_NSMutableArray);
8882 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008883 return None;
8884 }
8885
8886 Selector Sel = Message->getSelector();
8887
8888 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8889 S.NSAPIObj->getNSArrayMethodKind(Sel);
8890 if (!MKOpt) {
8891 return None;
8892 }
8893
8894 NSAPI::NSArrayMethodKind MK = *MKOpt;
8895
8896 switch (MK) {
8897 case NSAPI::NSMutableArr_addObject:
8898 case NSAPI::NSMutableArr_insertObjectAtIndex:
8899 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8900 return 0;
8901 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8902 return 1;
8903
8904 default:
8905 return None;
8906 }
8907
8908 return None;
8909}
8910
8911static
8912Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8913 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008914 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8915 Message->getReceiverInterface(),
8916 NSAPI::ClassId_NSMutableDictionary);
8917 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008918 return None;
8919 }
8920
8921 Selector Sel = Message->getSelector();
8922
8923 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8924 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8925 if (!MKOpt) {
8926 return None;
8927 }
8928
8929 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8930
8931 switch (MK) {
8932 case NSAPI::NSMutableDict_setObjectForKey:
8933 case NSAPI::NSMutableDict_setValueForKey:
8934 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8935 return 0;
8936
8937 default:
8938 return None;
8939 }
8940
8941 return None;
8942}
8943
8944static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008945 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8946 Message->getReceiverInterface(),
8947 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00008948
Alex Denisov5dfac812015-08-06 04:51:14 +00008949 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8950 Message->getReceiverInterface(),
8951 NSAPI::ClassId_NSMutableOrderedSet);
8952 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008953 return None;
8954 }
8955
8956 Selector Sel = Message->getSelector();
8957
8958 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8959 if (!MKOpt) {
8960 return None;
8961 }
8962
8963 NSAPI::NSSetMethodKind MK = *MKOpt;
8964
8965 switch (MK) {
8966 case NSAPI::NSMutableSet_addObject:
8967 case NSAPI::NSOrderedSet_setObjectAtIndex:
8968 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8969 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8970 return 0;
8971 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8972 return 1;
8973 }
8974
8975 return None;
8976}
8977
8978void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8979 if (!Message->isInstanceMessage()) {
8980 return;
8981 }
8982
8983 Optional<int> ArgOpt;
8984
8985 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8986 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8987 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8988 return;
8989 }
8990
8991 int ArgIndex = *ArgOpt;
8992
Alex Denisove1d882c2015-03-04 17:55:52 +00008993 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8994 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8995 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8996 }
8997
Alex Denisov5dfac812015-08-06 04:51:14 +00008998 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008999 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009000 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009001 Diag(Message->getSourceRange().getBegin(),
9002 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009003 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009004 }
9005 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009006 } else {
9007 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9008
9009 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9010 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9011 }
9012
9013 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9014 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9015 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9016 ValueDecl *Decl = ReceiverRE->getDecl();
9017 Diag(Message->getSourceRange().getBegin(),
9018 diag::warn_objc_circular_container)
9019 << Decl->getName() << Decl->getName();
9020 if (!ArgRE->isObjCSelfExpr()) {
9021 Diag(Decl->getLocation(),
9022 diag::note_objc_circular_container_declared_here)
9023 << Decl->getName();
9024 }
9025 }
9026 }
9027 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9028 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9029 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9030 ObjCIvarDecl *Decl = IvarRE->getDecl();
9031 Diag(Message->getSourceRange().getBegin(),
9032 diag::warn_objc_circular_container)
9033 << Decl->getName() << Decl->getName();
9034 Diag(Decl->getLocation(),
9035 diag::note_objc_circular_container_declared_here)
9036 << Decl->getName();
9037 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009038 }
9039 }
9040 }
9041
9042}
9043
John McCall31168b02011-06-15 23:02:42 +00009044/// Check a message send to see if it's likely to cause a retain cycle.
9045void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9046 // Only check instance methods whose selector looks like a setter.
9047 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9048 return;
9049
9050 // Try to find a variable that the receiver is strongly owned by.
9051 RetainCycleOwner owner;
9052 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009053 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009054 return;
9055 } else {
9056 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9057 owner.Variable = getCurMethodDecl()->getSelfDecl();
9058 owner.Loc = msg->getSuperLoc();
9059 owner.Range = msg->getSuperLoc();
9060 }
9061
9062 // Check whether the receiver is captured by any of the arguments.
9063 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9064 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9065 return diagnoseRetainCycle(*this, capturer, owner);
9066}
9067
9068/// Check a property assign to see if it's likely to cause a retain cycle.
9069void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9070 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009071 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009072 return;
9073
9074 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9075 diagnoseRetainCycle(*this, capturer, owner);
9076}
9077
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009078void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9079 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009080 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009081 return;
9082
9083 // Because we don't have an expression for the variable, we have to set the
9084 // location explicitly here.
9085 Owner.Loc = Var->getLocation();
9086 Owner.Range = Var->getSourceRange();
9087
9088 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9089 diagnoseRetainCycle(*this, Capturer, Owner);
9090}
9091
Ted Kremenek9304da92012-12-21 08:04:28 +00009092static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9093 Expr *RHS, bool isProperty) {
9094 // Check if RHS is an Objective-C object literal, which also can get
9095 // immediately zapped in a weak reference. Note that we explicitly
9096 // allow ObjCStringLiterals, since those are designed to never really die.
9097 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009098
Ted Kremenek64873352012-12-21 22:46:35 +00009099 // This enum needs to match with the 'select' in
9100 // warn_objc_arc_literal_assign (off-by-1).
9101 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9102 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9103 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009104
9105 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009106 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009107 << (isProperty ? 0 : 1)
9108 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009109
9110 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009111}
9112
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009113static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9114 Qualifiers::ObjCLifetime LT,
9115 Expr *RHS, bool isProperty) {
9116 // Strip off any implicit cast added to get to the one ARC-specific.
9117 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9118 if (cast->getCastKind() == CK_ARCConsumeObject) {
9119 S.Diag(Loc, diag::warn_arc_retained_assign)
9120 << (LT == Qualifiers::OCL_ExplicitNone)
9121 << (isProperty ? 0 : 1)
9122 << RHS->getSourceRange();
9123 return true;
9124 }
9125 RHS = cast->getSubExpr();
9126 }
9127
9128 if (LT == Qualifiers::OCL_Weak &&
9129 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9130 return true;
9131
9132 return false;
9133}
9134
Ted Kremenekb36234d2012-12-21 08:04:20 +00009135bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9136 QualType LHS, Expr *RHS) {
9137 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9138
9139 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9140 return false;
9141
9142 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9143 return true;
9144
9145 return false;
9146}
9147
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009148void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9149 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009150 QualType LHSType;
9151 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009152 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009153 ObjCPropertyRefExpr *PRE
9154 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9155 if (PRE && !PRE->isImplicitProperty()) {
9156 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9157 if (PD)
9158 LHSType = PD->getType();
9159 }
9160
9161 if (LHSType.isNull())
9162 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009163
9164 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9165
9166 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009167 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009168 getCurFunction()->markSafeWeakUse(LHS);
9169 }
9170
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009171 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9172 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009173
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009174 // FIXME. Check for other life times.
9175 if (LT != Qualifiers::OCL_None)
9176 return;
9177
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009178 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009179 if (PRE->isImplicitProperty())
9180 return;
9181 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9182 if (!PD)
9183 return;
9184
Bill Wendling44426052012-12-20 19:22:21 +00009185 unsigned Attributes = PD->getPropertyAttributes();
9186 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009187 // when 'assign' attribute was not explicitly specified
9188 // by user, ignore it and rely on property type itself
9189 // for lifetime info.
9190 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9191 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9192 LHSType->isObjCRetainableType())
9193 return;
9194
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009195 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009196 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009197 Diag(Loc, diag::warn_arc_retained_property_assign)
9198 << RHS->getSourceRange();
9199 return;
9200 }
9201 RHS = cast->getSubExpr();
9202 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009203 }
Bill Wendling44426052012-12-20 19:22:21 +00009204 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009205 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9206 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009207 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009208 }
9209}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009210
9211//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9212
9213namespace {
9214bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9215 SourceLocation StmtLoc,
9216 const NullStmt *Body) {
9217 // Do not warn if the body is a macro that expands to nothing, e.g:
9218 //
9219 // #define CALL(x)
9220 // if (condition)
9221 // CALL(0);
9222 //
9223 if (Body->hasLeadingEmptyMacro())
9224 return false;
9225
9226 // Get line numbers of statement and body.
9227 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009228 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009229 &StmtLineInvalid);
9230 if (StmtLineInvalid)
9231 return false;
9232
9233 bool BodyLineInvalid;
9234 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9235 &BodyLineInvalid);
9236 if (BodyLineInvalid)
9237 return false;
9238
9239 // Warn if null statement and body are on the same line.
9240 if (StmtLine != BodyLine)
9241 return false;
9242
9243 return true;
9244}
9245} // Unnamed namespace
9246
9247void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9248 const Stmt *Body,
9249 unsigned DiagID) {
9250 // Since this is a syntactic check, don't emit diagnostic for template
9251 // instantiations, this just adds noise.
9252 if (CurrentInstantiationScope)
9253 return;
9254
9255 // The body should be a null statement.
9256 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9257 if (!NBody)
9258 return;
9259
9260 // Do the usual checks.
9261 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9262 return;
9263
9264 Diag(NBody->getSemiLoc(), DiagID);
9265 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9266}
9267
9268void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9269 const Stmt *PossibleBody) {
9270 assert(!CurrentInstantiationScope); // Ensured by caller
9271
9272 SourceLocation StmtLoc;
9273 const Stmt *Body;
9274 unsigned DiagID;
9275 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9276 StmtLoc = FS->getRParenLoc();
9277 Body = FS->getBody();
9278 DiagID = diag::warn_empty_for_body;
9279 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9280 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9281 Body = WS->getBody();
9282 DiagID = diag::warn_empty_while_body;
9283 } else
9284 return; // Neither `for' nor `while'.
9285
9286 // The body should be a null statement.
9287 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9288 if (!NBody)
9289 return;
9290
9291 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009292 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009293 return;
9294
9295 // Do the usual checks.
9296 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9297 return;
9298
9299 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9300 // noise level low, emit diagnostics only if for/while is followed by a
9301 // CompoundStmt, e.g.:
9302 // for (int i = 0; i < n; i++);
9303 // {
9304 // a(i);
9305 // }
9306 // or if for/while is followed by a statement with more indentation
9307 // than for/while itself:
9308 // for (int i = 0; i < n; i++);
9309 // a(i);
9310 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9311 if (!ProbableTypo) {
9312 bool BodyColInvalid;
9313 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9314 PossibleBody->getLocStart(),
9315 &BodyColInvalid);
9316 if (BodyColInvalid)
9317 return;
9318
9319 bool StmtColInvalid;
9320 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9321 S->getLocStart(),
9322 &StmtColInvalid);
9323 if (StmtColInvalid)
9324 return;
9325
9326 if (BodyCol > StmtCol)
9327 ProbableTypo = true;
9328 }
9329
9330 if (ProbableTypo) {
9331 Diag(NBody->getSemiLoc(), DiagID);
9332 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9333 }
9334}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009335
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009336//===--- CHECK: Warn on self move with std::move. -------------------------===//
9337
9338/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9339void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9340 SourceLocation OpLoc) {
9341
9342 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9343 return;
9344
9345 if (!ActiveTemplateInstantiations.empty())
9346 return;
9347
9348 // Strip parens and casts away.
9349 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9350 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9351
9352 // Check for a call expression
9353 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9354 if (!CE || CE->getNumArgs() != 1)
9355 return;
9356
9357 // Check for a call to std::move
9358 const FunctionDecl *FD = CE->getDirectCallee();
9359 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9360 !FD->getIdentifier()->isStr("move"))
9361 return;
9362
9363 // Get argument from std::move
9364 RHSExpr = CE->getArg(0);
9365
9366 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9367 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9368
9369 // Two DeclRefExpr's, check that the decls are the same.
9370 if (LHSDeclRef && RHSDeclRef) {
9371 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9372 return;
9373 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9374 RHSDeclRef->getDecl()->getCanonicalDecl())
9375 return;
9376
9377 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9378 << LHSExpr->getSourceRange()
9379 << RHSExpr->getSourceRange();
9380 return;
9381 }
9382
9383 // Member variables require a different approach to check for self moves.
9384 // MemberExpr's are the same if every nested MemberExpr refers to the same
9385 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9386 // the base Expr's are CXXThisExpr's.
9387 const Expr *LHSBase = LHSExpr;
9388 const Expr *RHSBase = RHSExpr;
9389 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9390 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9391 if (!LHSME || !RHSME)
9392 return;
9393
9394 while (LHSME && RHSME) {
9395 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9396 RHSME->getMemberDecl()->getCanonicalDecl())
9397 return;
9398
9399 LHSBase = LHSME->getBase();
9400 RHSBase = RHSME->getBase();
9401 LHSME = dyn_cast<MemberExpr>(LHSBase);
9402 RHSME = dyn_cast<MemberExpr>(RHSBase);
9403 }
9404
9405 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9406 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9407 if (LHSDeclRef && RHSDeclRef) {
9408 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9409 return;
9410 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9411 RHSDeclRef->getDecl()->getCanonicalDecl())
9412 return;
9413
9414 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9415 << LHSExpr->getSourceRange()
9416 << RHSExpr->getSourceRange();
9417 return;
9418 }
9419
9420 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9421 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9422 << LHSExpr->getSourceRange()
9423 << RHSExpr->getSourceRange();
9424}
9425
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009426//===--- Layout compatibility ----------------------------------------------//
9427
9428namespace {
9429
9430bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9431
9432/// \brief Check if two enumeration types are layout-compatible.
9433bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9434 // C++11 [dcl.enum] p8:
9435 // Two enumeration types are layout-compatible if they have the same
9436 // underlying type.
9437 return ED1->isComplete() && ED2->isComplete() &&
9438 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9439}
9440
9441/// \brief Check if two fields are layout-compatible.
9442bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9443 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9444 return false;
9445
9446 if (Field1->isBitField() != Field2->isBitField())
9447 return false;
9448
9449 if (Field1->isBitField()) {
9450 // Make sure that the bit-fields are the same length.
9451 unsigned Bits1 = Field1->getBitWidthValue(C);
9452 unsigned Bits2 = Field2->getBitWidthValue(C);
9453
9454 if (Bits1 != Bits2)
9455 return false;
9456 }
9457
9458 return true;
9459}
9460
9461/// \brief Check if two standard-layout structs are layout-compatible.
9462/// (C++11 [class.mem] p17)
9463bool isLayoutCompatibleStruct(ASTContext &C,
9464 RecordDecl *RD1,
9465 RecordDecl *RD2) {
9466 // If both records are C++ classes, check that base classes match.
9467 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9468 // If one of records is a CXXRecordDecl we are in C++ mode,
9469 // thus the other one is a CXXRecordDecl, too.
9470 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9471 // Check number of base classes.
9472 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9473 return false;
9474
9475 // Check the base classes.
9476 for (CXXRecordDecl::base_class_const_iterator
9477 Base1 = D1CXX->bases_begin(),
9478 BaseEnd1 = D1CXX->bases_end(),
9479 Base2 = D2CXX->bases_begin();
9480 Base1 != BaseEnd1;
9481 ++Base1, ++Base2) {
9482 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9483 return false;
9484 }
9485 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9486 // If only RD2 is a C++ class, it should have zero base classes.
9487 if (D2CXX->getNumBases() > 0)
9488 return false;
9489 }
9490
9491 // Check the fields.
9492 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9493 Field2End = RD2->field_end(),
9494 Field1 = RD1->field_begin(),
9495 Field1End = RD1->field_end();
9496 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9497 if (!isLayoutCompatible(C, *Field1, *Field2))
9498 return false;
9499 }
9500 if (Field1 != Field1End || Field2 != Field2End)
9501 return false;
9502
9503 return true;
9504}
9505
9506/// \brief Check if two standard-layout unions are layout-compatible.
9507/// (C++11 [class.mem] p18)
9508bool isLayoutCompatibleUnion(ASTContext &C,
9509 RecordDecl *RD1,
9510 RecordDecl *RD2) {
9511 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009512 for (auto *Field2 : RD2->fields())
9513 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009514
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009515 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009516 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9517 I = UnmatchedFields.begin(),
9518 E = UnmatchedFields.end();
9519
9520 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009521 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009522 bool Result = UnmatchedFields.erase(*I);
9523 (void) Result;
9524 assert(Result);
9525 break;
9526 }
9527 }
9528 if (I == E)
9529 return false;
9530 }
9531
9532 return UnmatchedFields.empty();
9533}
9534
9535bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9536 if (RD1->isUnion() != RD2->isUnion())
9537 return false;
9538
9539 if (RD1->isUnion())
9540 return isLayoutCompatibleUnion(C, RD1, RD2);
9541 else
9542 return isLayoutCompatibleStruct(C, RD1, RD2);
9543}
9544
9545/// \brief Check if two types are layout-compatible in C++11 sense.
9546bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9547 if (T1.isNull() || T2.isNull())
9548 return false;
9549
9550 // C++11 [basic.types] p11:
9551 // If two types T1 and T2 are the same type, then T1 and T2 are
9552 // layout-compatible types.
9553 if (C.hasSameType(T1, T2))
9554 return true;
9555
9556 T1 = T1.getCanonicalType().getUnqualifiedType();
9557 T2 = T2.getCanonicalType().getUnqualifiedType();
9558
9559 const Type::TypeClass TC1 = T1->getTypeClass();
9560 const Type::TypeClass TC2 = T2->getTypeClass();
9561
9562 if (TC1 != TC2)
9563 return false;
9564
9565 if (TC1 == Type::Enum) {
9566 return isLayoutCompatible(C,
9567 cast<EnumType>(T1)->getDecl(),
9568 cast<EnumType>(T2)->getDecl());
9569 } else if (TC1 == Type::Record) {
9570 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9571 return false;
9572
9573 return isLayoutCompatible(C,
9574 cast<RecordType>(T1)->getDecl(),
9575 cast<RecordType>(T2)->getDecl());
9576 }
9577
9578 return false;
9579}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009580}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009581
9582//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9583
9584namespace {
9585/// \brief Given a type tag expression find the type tag itself.
9586///
9587/// \param TypeExpr Type tag expression, as it appears in user's code.
9588///
9589/// \param VD Declaration of an identifier that appears in a type tag.
9590///
9591/// \param MagicValue Type tag magic value.
9592bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9593 const ValueDecl **VD, uint64_t *MagicValue) {
9594 while(true) {
9595 if (!TypeExpr)
9596 return false;
9597
9598 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9599
9600 switch (TypeExpr->getStmtClass()) {
9601 case Stmt::UnaryOperatorClass: {
9602 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9603 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9604 TypeExpr = UO->getSubExpr();
9605 continue;
9606 }
9607 return false;
9608 }
9609
9610 case Stmt::DeclRefExprClass: {
9611 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9612 *VD = DRE->getDecl();
9613 return true;
9614 }
9615
9616 case Stmt::IntegerLiteralClass: {
9617 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9618 llvm::APInt MagicValueAPInt = IL->getValue();
9619 if (MagicValueAPInt.getActiveBits() <= 64) {
9620 *MagicValue = MagicValueAPInt.getZExtValue();
9621 return true;
9622 } else
9623 return false;
9624 }
9625
9626 case Stmt::BinaryConditionalOperatorClass:
9627 case Stmt::ConditionalOperatorClass: {
9628 const AbstractConditionalOperator *ACO =
9629 cast<AbstractConditionalOperator>(TypeExpr);
9630 bool Result;
9631 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9632 if (Result)
9633 TypeExpr = ACO->getTrueExpr();
9634 else
9635 TypeExpr = ACO->getFalseExpr();
9636 continue;
9637 }
9638 return false;
9639 }
9640
9641 case Stmt::BinaryOperatorClass: {
9642 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9643 if (BO->getOpcode() == BO_Comma) {
9644 TypeExpr = BO->getRHS();
9645 continue;
9646 }
9647 return false;
9648 }
9649
9650 default:
9651 return false;
9652 }
9653 }
9654}
9655
9656/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9657///
9658/// \param TypeExpr Expression that specifies a type tag.
9659///
9660/// \param MagicValues Registered magic values.
9661///
9662/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9663/// kind.
9664///
9665/// \param TypeInfo Information about the corresponding C type.
9666///
9667/// \returns true if the corresponding C type was found.
9668bool GetMatchingCType(
9669 const IdentifierInfo *ArgumentKind,
9670 const Expr *TypeExpr, const ASTContext &Ctx,
9671 const llvm::DenseMap<Sema::TypeTagMagicValue,
9672 Sema::TypeTagData> *MagicValues,
9673 bool &FoundWrongKind,
9674 Sema::TypeTagData &TypeInfo) {
9675 FoundWrongKind = false;
9676
9677 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009678 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009679
9680 uint64_t MagicValue;
9681
9682 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9683 return false;
9684
9685 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009686 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009687 if (I->getArgumentKind() != ArgumentKind) {
9688 FoundWrongKind = true;
9689 return false;
9690 }
9691 TypeInfo.Type = I->getMatchingCType();
9692 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9693 TypeInfo.MustBeNull = I->getMustBeNull();
9694 return true;
9695 }
9696 return false;
9697 }
9698
9699 if (!MagicValues)
9700 return false;
9701
9702 llvm::DenseMap<Sema::TypeTagMagicValue,
9703 Sema::TypeTagData>::const_iterator I =
9704 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9705 if (I == MagicValues->end())
9706 return false;
9707
9708 TypeInfo = I->second;
9709 return true;
9710}
9711} // unnamed namespace
9712
9713void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9714 uint64_t MagicValue, QualType Type,
9715 bool LayoutCompatible,
9716 bool MustBeNull) {
9717 if (!TypeTagForDatatypeMagicValues)
9718 TypeTagForDatatypeMagicValues.reset(
9719 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9720
9721 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9722 (*TypeTagForDatatypeMagicValues)[Magic] =
9723 TypeTagData(Type, LayoutCompatible, MustBeNull);
9724}
9725
9726namespace {
9727bool IsSameCharType(QualType T1, QualType T2) {
9728 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9729 if (!BT1)
9730 return false;
9731
9732 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9733 if (!BT2)
9734 return false;
9735
9736 BuiltinType::Kind T1Kind = BT1->getKind();
9737 BuiltinType::Kind T2Kind = BT2->getKind();
9738
9739 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9740 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9741 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9742 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9743}
9744} // unnamed namespace
9745
9746void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9747 const Expr * const *ExprArgs) {
9748 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9749 bool IsPointerAttr = Attr->getIsPointer();
9750
9751 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9752 bool FoundWrongKind;
9753 TypeTagData TypeInfo;
9754 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9755 TypeTagForDatatypeMagicValues.get(),
9756 FoundWrongKind, TypeInfo)) {
9757 if (FoundWrongKind)
9758 Diag(TypeTagExpr->getExprLoc(),
9759 diag::warn_type_tag_for_datatype_wrong_kind)
9760 << TypeTagExpr->getSourceRange();
9761 return;
9762 }
9763
9764 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9765 if (IsPointerAttr) {
9766 // Skip implicit cast of pointer to `void *' (as a function argument).
9767 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009768 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009769 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009770 ArgumentExpr = ICE->getSubExpr();
9771 }
9772 QualType ArgumentType = ArgumentExpr->getType();
9773
9774 // Passing a `void*' pointer shouldn't trigger a warning.
9775 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9776 return;
9777
9778 if (TypeInfo.MustBeNull) {
9779 // Type tag with matching void type requires a null pointer.
9780 if (!ArgumentExpr->isNullPointerConstant(Context,
9781 Expr::NPC_ValueDependentIsNotNull)) {
9782 Diag(ArgumentExpr->getExprLoc(),
9783 diag::warn_type_safety_null_pointer_required)
9784 << ArgumentKind->getName()
9785 << ArgumentExpr->getSourceRange()
9786 << TypeTagExpr->getSourceRange();
9787 }
9788 return;
9789 }
9790
9791 QualType RequiredType = TypeInfo.Type;
9792 if (IsPointerAttr)
9793 RequiredType = Context.getPointerType(RequiredType);
9794
9795 bool mismatch = false;
9796 if (!TypeInfo.LayoutCompatible) {
9797 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9798
9799 // C++11 [basic.fundamental] p1:
9800 // Plain char, signed char, and unsigned char are three distinct types.
9801 //
9802 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9803 // char' depending on the current char signedness mode.
9804 if (mismatch)
9805 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9806 RequiredType->getPointeeType())) ||
9807 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9808 mismatch = false;
9809 } else
9810 if (IsPointerAttr)
9811 mismatch = !isLayoutCompatible(Context,
9812 ArgumentType->getPointeeType(),
9813 RequiredType->getPointeeType());
9814 else
9815 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9816
9817 if (mismatch)
9818 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009819 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009820 << TypeInfo.LayoutCompatible << RequiredType
9821 << ArgumentExpr->getSourceRange()
9822 << TypeTagExpr->getSourceRange();
9823}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009824