blob: 599a0e4be214626f91dd6dcd01660d9a329ad633 [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))
Ted Kremeneka146db32014-01-17 06:24:47 +00001154 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1155}
1156
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001157bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1158 FormatStringInfo FSI;
1159 if ((GetFormatStringType(Format) == FST_NSString) &&
1160 getFormatStringInfo(Format, false, &FSI)) {
1161 Idx = FSI.FormatIdx;
1162 return true;
1163 }
1164 return false;
1165}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001166/// \brief Diagnose use of %s directive in an NSString which is being passed
1167/// as formatting string to formatting method.
1168static void
1169DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1170 const NamedDecl *FDecl,
1171 Expr **Args,
1172 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001173 unsigned Idx = 0;
1174 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001175 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1176 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001177 Idx = 2;
1178 Format = true;
1179 }
1180 else
1181 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1182 if (S.GetFormatNSStringIdx(I, Idx)) {
1183 Format = true;
1184 break;
1185 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001186 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001187 if (!Format || NumArgs <= Idx)
1188 return;
1189 const Expr *FormatExpr = Args[Idx];
1190 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1191 FormatExpr = CSCE->getSubExpr();
1192 const StringLiteral *FormatString;
1193 if (const ObjCStringLiteral *OSL =
1194 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1195 FormatString = OSL->getString();
1196 else
1197 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1198 if (!FormatString)
1199 return;
1200 if (S.FormatStringHasSArg(FormatString)) {
1201 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1202 << "%s" << 1 << 1;
1203 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1204 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001205 }
1206}
1207
Douglas Gregorb4866e82015-06-19 18:13:19 +00001208/// Determine whether the given type has a non-null nullability annotation.
1209static bool isNonNullType(ASTContext &ctx, QualType type) {
1210 if (auto nullability = type->getNullability(ctx))
1211 return *nullability == NullabilityKind::NonNull;
1212
1213 return false;
1214}
1215
Ted Kremenek2bc73332014-01-17 06:24:43 +00001216static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001217 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001218 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001219 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001220 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001221 assert((FDecl || Proto) && "Need a function declaration or prototype");
1222
Ted Kremenek9aedc152014-01-17 06:24:56 +00001223 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001224 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001225 if (FDecl) {
1226 // Handle the nonnull attribute on the function/method declaration itself.
1227 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1228 if (!NonNull->args_size()) {
1229 // Easy case: all pointer arguments are nonnull.
1230 for (const auto *Arg : Args)
1231 if (S.isValidPointerAttrType(Arg->getType()))
1232 CheckNonNullArgument(S, Arg, CallSiteLoc);
1233 return;
1234 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001235
Douglas Gregorb4866e82015-06-19 18:13:19 +00001236 for (unsigned Val : NonNull->args()) {
1237 if (Val >= Args.size())
1238 continue;
1239 if (NonNullArgs.empty())
1240 NonNullArgs.resize(Args.size());
1241 NonNullArgs.set(Val);
1242 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001243 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001244 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001245
Douglas Gregorb4866e82015-06-19 18:13:19 +00001246 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1247 // Handle the nonnull attribute on the parameters of the
1248 // function/method.
1249 ArrayRef<ParmVarDecl*> parms;
1250 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1251 parms = FD->parameters();
1252 else
1253 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1254
1255 unsigned ParamIndex = 0;
1256 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1257 I != E; ++I, ++ParamIndex) {
1258 const ParmVarDecl *PVD = *I;
1259 if (PVD->hasAttr<NonNullAttr>() ||
1260 isNonNullType(S.Context, PVD->getType())) {
1261 if (NonNullArgs.empty())
1262 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001263
Douglas Gregorb4866e82015-06-19 18:13:19 +00001264 NonNullArgs.set(ParamIndex);
1265 }
1266 }
1267 } else {
1268 // If we have a non-function, non-method declaration but no
1269 // function prototype, try to dig out the function prototype.
1270 if (!Proto) {
1271 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1272 QualType type = VD->getType().getNonReferenceType();
1273 if (auto pointerType = type->getAs<PointerType>())
1274 type = pointerType->getPointeeType();
1275 else if (auto blockType = type->getAs<BlockPointerType>())
1276 type = blockType->getPointeeType();
1277 // FIXME: data member pointers?
1278
1279 // Dig out the function prototype, if there is one.
1280 Proto = type->getAs<FunctionProtoType>();
1281 }
1282 }
1283
1284 // Fill in non-null argument information from the nullability
1285 // information on the parameter types (if we have them).
1286 if (Proto) {
1287 unsigned Index = 0;
1288 for (auto paramType : Proto->getParamTypes()) {
1289 if (isNonNullType(S.Context, paramType)) {
1290 if (NonNullArgs.empty())
1291 NonNullArgs.resize(Args.size());
1292
1293 NonNullArgs.set(Index);
1294 }
1295
1296 ++Index;
1297 }
1298 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001299 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001300
Douglas Gregorb4866e82015-06-19 18:13:19 +00001301 // Check for non-null arguments.
1302 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1303 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001304 if (NonNullArgs[ArgIndex])
1305 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001306 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001307}
1308
Richard Smith55ce3522012-06-25 20:30:08 +00001309/// Handles the checks for format strings, non-POD arguments to vararg
1310/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001311void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1312 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001313 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001314 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001315 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001316 if (CurContext->isDependentContext())
1317 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001318
Ted Kremenekb8176da2010-09-09 04:33:05 +00001319 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001320 llvm::SmallBitVector CheckedVarArgs;
1321 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001322 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001323 // Only create vector if there are format attributes.
1324 CheckedVarArgs.resize(Args.size());
1325
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001326 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001327 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001328 }
Richard Smithd7293d72013-08-05 18:49:43 +00001329 }
Richard Smith55ce3522012-06-25 20:30:08 +00001330
1331 // Refuse POD arguments that weren't caught by the format string
1332 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001333 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001334 unsigned NumParams = Proto ? Proto->getNumParams()
1335 : FDecl && isa<FunctionDecl>(FDecl)
1336 ? cast<FunctionDecl>(FDecl)->getNumParams()
1337 : FDecl && isa<ObjCMethodDecl>(FDecl)
1338 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1339 : 0;
1340
Alp Toker9cacbab2014-01-20 20:26:09 +00001341 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001342 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001343 if (const Expr *Arg = Args[ArgIdx]) {
1344 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1345 checkVariadicArgument(Arg, CallType);
1346 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001347 }
Richard Smithd7293d72013-08-05 18:49:43 +00001348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Douglas Gregorb4866e82015-06-19 18:13:19 +00001350 if (FDecl || Proto) {
1351 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001352
Richard Trieu41bc0992013-06-22 00:20:41 +00001353 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001354 if (FDecl) {
1355 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1356 CheckArgumentWithTypeTag(I, Args.data());
1357 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001358 }
Richard Smith55ce3522012-06-25 20:30:08 +00001359}
1360
1361/// CheckConstructorCall - Check a constructor call for correctness and safety
1362/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001363void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1364 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001365 const FunctionProtoType *Proto,
1366 SourceLocation Loc) {
1367 VariadicCallType CallType =
1368 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001369 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1370 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001371}
1372
1373/// CheckFunctionCall - Check a direct function call for various correctness
1374/// and safety properties not strictly enforced by the C type system.
1375bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1376 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001377 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1378 isa<CXXMethodDecl>(FDecl);
1379 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1380 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001381 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1382 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001383 Expr** Args = TheCall->getArgs();
1384 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001385 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001386 // If this is a call to a member operator, hide the first argument
1387 // from checkCall.
1388 // FIXME: Our choice of AST representation here is less than ideal.
1389 ++Args;
1390 --NumArgs;
1391 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001392 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001393 IsMemberFunction, TheCall->getRParenLoc(),
1394 TheCall->getCallee()->getSourceRange(), CallType);
1395
1396 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1397 // None of the checks below are needed for functions that don't have
1398 // simple names (e.g., C++ conversion functions).
1399 if (!FnInfo)
1400 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001401
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001402 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001403 if (getLangOpts().ObjC1)
1404 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001405
Anna Zaks22122702012-01-17 00:37:07 +00001406 unsigned CMId = FDecl->getMemoryFunctionKind();
1407 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001408 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001409
Anna Zaks201d4892012-01-13 21:52:01 +00001410 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001411 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001412 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001413 else if (CMId == Builtin::BIstrncat)
1414 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001415 else
Anna Zaks22122702012-01-17 00:37:07 +00001416 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001417
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001418 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001419}
1420
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001421bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001422 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001423 VariadicCallType CallType =
1424 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001425
Douglas Gregorb4866e82015-06-19 18:13:19 +00001426 checkCall(Method, nullptr, Args,
1427 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1428 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001429
1430 return false;
1431}
1432
Richard Trieu664c4c62013-06-20 21:03:13 +00001433bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1434 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001435 QualType Ty;
1436 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001437 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001438 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001439 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001440 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001441 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Douglas Gregorb4866e82015-06-19 18:13:19 +00001443 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1444 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Richard Trieu664c4c62013-06-20 21:03:13 +00001447 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001448 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001449 CallType = VariadicDoesNotApply;
1450 } else if (Ty->isBlockPointerType()) {
1451 CallType = VariadicBlock;
1452 } else { // Ty->isFunctionPointerType()
1453 CallType = VariadicFunction;
1454 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001455
Douglas Gregorb4866e82015-06-19 18:13:19 +00001456 checkCall(NDecl, Proto,
1457 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1458 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001459 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001460
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001461 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001462}
1463
Richard Trieu41bc0992013-06-22 00:20:41 +00001464/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1465/// such as function pointers returned from functions.
1466bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001467 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001468 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001469 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001470 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001471 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001472 TheCall->getCallee()->getSourceRange(), CallType);
1473
1474 return false;
1475}
1476
Tim Northovere94a34c2014-03-11 10:49:14 +00001477static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1478 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1479 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1480 return false;
1481
1482 switch (Op) {
1483 case AtomicExpr::AO__c11_atomic_init:
1484 llvm_unreachable("There is no ordering argument for an init");
1485
1486 case AtomicExpr::AO__c11_atomic_load:
1487 case AtomicExpr::AO__atomic_load_n:
1488 case AtomicExpr::AO__atomic_load:
1489 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1490 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1491
1492 case AtomicExpr::AO__c11_atomic_store:
1493 case AtomicExpr::AO__atomic_store:
1494 case AtomicExpr::AO__atomic_store_n:
1495 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1496 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1497 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1498
1499 default:
1500 return true;
1501 }
1502}
1503
Richard Smithfeea8832012-04-12 05:08:17 +00001504ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1505 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001506 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001508
Richard Smithfeea8832012-04-12 05:08:17 +00001509 // All these operations take one of the following forms:
1510 enum {
1511 // C __c11_atomic_init(A *, C)
1512 Init,
1513 // C __c11_atomic_load(A *, int)
1514 Load,
1515 // void __atomic_load(A *, CP, int)
1516 Copy,
1517 // C __c11_atomic_add(A *, M, int)
1518 Arithmetic,
1519 // C __atomic_exchange_n(A *, CP, int)
1520 Xchg,
1521 // void __atomic_exchange(A *, C *, CP, int)
1522 GNUXchg,
1523 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1524 C11CmpXchg,
1525 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1526 GNUCmpXchg
1527 } Form = Init;
1528 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1529 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1530 // where:
1531 // C is an appropriate type,
1532 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1533 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1534 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1535 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001536
Gabor Horvath98bd0982015-03-16 09:59:54 +00001537 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1538 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1539 AtomicExpr::AO__atomic_load,
1540 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001541 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1542 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1543 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1544 Op == AtomicExpr::AO__atomic_store_n ||
1545 Op == AtomicExpr::AO__atomic_exchange_n ||
1546 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1547 bool IsAddSub = false;
1548
1549 switch (Op) {
1550 case AtomicExpr::AO__c11_atomic_init:
1551 Form = Init;
1552 break;
1553
1554 case AtomicExpr::AO__c11_atomic_load:
1555 case AtomicExpr::AO__atomic_load_n:
1556 Form = Load;
1557 break;
1558
1559 case AtomicExpr::AO__c11_atomic_store:
1560 case AtomicExpr::AO__atomic_load:
1561 case AtomicExpr::AO__atomic_store:
1562 case AtomicExpr::AO__atomic_store_n:
1563 Form = Copy;
1564 break;
1565
1566 case AtomicExpr::AO__c11_atomic_fetch_add:
1567 case AtomicExpr::AO__c11_atomic_fetch_sub:
1568 case AtomicExpr::AO__atomic_fetch_add:
1569 case AtomicExpr::AO__atomic_fetch_sub:
1570 case AtomicExpr::AO__atomic_add_fetch:
1571 case AtomicExpr::AO__atomic_sub_fetch:
1572 IsAddSub = true;
1573 // Fall through.
1574 case AtomicExpr::AO__c11_atomic_fetch_and:
1575 case AtomicExpr::AO__c11_atomic_fetch_or:
1576 case AtomicExpr::AO__c11_atomic_fetch_xor:
1577 case AtomicExpr::AO__atomic_fetch_and:
1578 case AtomicExpr::AO__atomic_fetch_or:
1579 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001580 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001581 case AtomicExpr::AO__atomic_and_fetch:
1582 case AtomicExpr::AO__atomic_or_fetch:
1583 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001584 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001585 Form = Arithmetic;
1586 break;
1587
1588 case AtomicExpr::AO__c11_atomic_exchange:
1589 case AtomicExpr::AO__atomic_exchange_n:
1590 Form = Xchg;
1591 break;
1592
1593 case AtomicExpr::AO__atomic_exchange:
1594 Form = GNUXchg;
1595 break;
1596
1597 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1598 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1599 Form = C11CmpXchg;
1600 break;
1601
1602 case AtomicExpr::AO__atomic_compare_exchange:
1603 case AtomicExpr::AO__atomic_compare_exchange_n:
1604 Form = GNUCmpXchg;
1605 break;
1606 }
1607
1608 // Check we have the right number of arguments.
1609 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001610 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001611 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001612 << TheCall->getCallee()->getSourceRange();
1613 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001614 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1615 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001616 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001617 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001618 << TheCall->getCallee()->getSourceRange();
1619 return ExprError();
1620 }
1621
Richard Smithfeea8832012-04-12 05:08:17 +00001622 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001623 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001624 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1625 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1626 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001627 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001628 << Ptr->getType() << Ptr->getSourceRange();
1629 return ExprError();
1630 }
1631
Richard Smithfeea8832012-04-12 05:08:17 +00001632 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1633 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1634 QualType ValType = AtomTy; // 'C'
1635 if (IsC11) {
1636 if (!AtomTy->isAtomicType()) {
1637 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1638 << Ptr->getType() << Ptr->getSourceRange();
1639 return ExprError();
1640 }
Richard Smithe00921a2012-09-15 06:09:58 +00001641 if (AtomTy.isConstQualified()) {
1642 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1643 << Ptr->getType() << Ptr->getSourceRange();
1644 return ExprError();
1645 }
Richard Smithfeea8832012-04-12 05:08:17 +00001646 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001647 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1648 if (ValType.isConstQualified()) {
1649 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1650 << Ptr->getType() << Ptr->getSourceRange();
1651 return ExprError();
1652 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001653 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001654
Richard Smithfeea8832012-04-12 05:08:17 +00001655 // For an arithmetic operation, the implied arithmetic must be well-formed.
1656 if (Form == Arithmetic) {
1657 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1658 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1659 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1660 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1661 return ExprError();
1662 }
1663 if (!IsAddSub && !ValType->isIntegerType()) {
1664 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1665 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1666 return ExprError();
1667 }
David Majnemere85cff82015-01-28 05:48:06 +00001668 if (IsC11 && ValType->isPointerType() &&
1669 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1670 diag::err_incomplete_type)) {
1671 return ExprError();
1672 }
Richard Smithfeea8832012-04-12 05:08:17 +00001673 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1674 // For __atomic_*_n operations, the value type must be a scalar integral or
1675 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001676 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001677 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1678 return ExprError();
1679 }
1680
Eli Friedmanaa769812013-09-11 03:49:34 +00001681 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1682 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001683 // For GNU atomics, require a trivially-copyable type. This is not part of
1684 // the GNU atomics specification, but we enforce it for sanity.
1685 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001686 << Ptr->getType() << Ptr->getSourceRange();
1687 return ExprError();
1688 }
1689
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001690 switch (ValType.getObjCLifetime()) {
1691 case Qualifiers::OCL_None:
1692 case Qualifiers::OCL_ExplicitNone:
1693 // okay
1694 break;
1695
1696 case Qualifiers::OCL_Weak:
1697 case Qualifiers::OCL_Strong:
1698 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001699 // FIXME: Can this happen? By this point, ValType should be known
1700 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001701 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1702 << ValType << Ptr->getSourceRange();
1703 return ExprError();
1704 }
1705
David Majnemerc6eb6502015-06-03 00:26:35 +00001706 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1707 // volatile-ness of the pointee-type inject itself into the result or the
1708 // other operands.
1709 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001710 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001711 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001712 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001713 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001714 ResultType = Context.BoolTy;
1715
Richard Smithfeea8832012-04-12 05:08:17 +00001716 // The type of a parameter passed 'by value'. In the GNU atomics, such
1717 // arguments are actually passed as pointers.
1718 QualType ByValType = ValType; // 'CP'
1719 if (!IsC11 && !IsN)
1720 ByValType = Ptr->getType();
1721
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001722 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1723 // but not the second argument. We need to manually remove possible const
1724 // qualifiers.
1725
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001726 // The first argument --- the pointer --- has a fixed type; we
1727 // deduce the types of the rest of the arguments accordingly. Walk
1728 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001729 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001730 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001731 if (i < NumVals[Form] + 1) {
1732 switch (i) {
1733 case 1:
1734 // The second argument is the non-atomic operand. For arithmetic, this
1735 // is always passed by value, and for a compare_exchange it is always
1736 // passed by address. For the rest, GNU uses by-address and C11 uses
1737 // by-value.
1738 assert(Form != Load);
1739 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1740 Ty = ValType;
1741 else if (Form == Copy || Form == Xchg)
1742 Ty = ByValType;
1743 else if (Form == Arithmetic)
1744 Ty = Context.getPointerDiffType();
1745 else
1746 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1747 break;
1748 case 2:
1749 // The third argument to compare_exchange / GNU exchange is a
1750 // (pointer to a) desired value.
1751 Ty = ByValType;
1752 break;
1753 case 3:
1754 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1755 Ty = Context.BoolTy;
1756 break;
1757 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001758 } else {
1759 // The order(s) are always converted to int.
1760 Ty = Context.IntTy;
1761 }
Richard Smithfeea8832012-04-12 05:08:17 +00001762
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001763 InitializedEntity Entity =
1764 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001765 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001766 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1767 if (Arg.isInvalid())
1768 return true;
1769 TheCall->setArg(i, Arg.get());
1770 }
1771
Richard Smithfeea8832012-04-12 05:08:17 +00001772 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001773 SmallVector<Expr*, 5> SubExprs;
1774 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001775 switch (Form) {
1776 case Init:
1777 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001778 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001779 break;
1780 case Load:
1781 SubExprs.push_back(TheCall->getArg(1)); // Order
1782 break;
1783 case Copy:
1784 case Arithmetic:
1785 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001786 SubExprs.push_back(TheCall->getArg(2)); // Order
1787 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001788 break;
1789 case GNUXchg:
1790 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1791 SubExprs.push_back(TheCall->getArg(3)); // Order
1792 SubExprs.push_back(TheCall->getArg(1)); // Val1
1793 SubExprs.push_back(TheCall->getArg(2)); // Val2
1794 break;
1795 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001796 SubExprs.push_back(TheCall->getArg(3)); // Order
1797 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001798 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001799 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001800 break;
1801 case GNUCmpXchg:
1802 SubExprs.push_back(TheCall->getArg(4)); // Order
1803 SubExprs.push_back(TheCall->getArg(1)); // Val1
1804 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1805 SubExprs.push_back(TheCall->getArg(2)); // Val2
1806 SubExprs.push_back(TheCall->getArg(3)); // Weak
1807 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001808 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001809
1810 if (SubExprs.size() >= 2 && Form != Init) {
1811 llvm::APSInt Result(32);
1812 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1813 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001814 Diag(SubExprs[1]->getLocStart(),
1815 diag::warn_atomic_op_has_invalid_memory_order)
1816 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001817 }
1818
Fariborz Jahanian615de762013-05-28 17:37:39 +00001819 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1820 SubExprs, ResultType, Op,
1821 TheCall->getRParenLoc());
1822
1823 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1824 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1825 Context.AtomicUsesUnsupportedLibcall(AE))
1826 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1827 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001828
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001829 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001830}
1831
1832
John McCall29ad95b2011-08-27 01:09:30 +00001833/// checkBuiltinArgument - Given a call to a builtin function, perform
1834/// normal type-checking on the given argument, updating the call in
1835/// place. This is useful when a builtin function requires custom
1836/// type-checking for some of its arguments but not necessarily all of
1837/// them.
1838///
1839/// Returns true on error.
1840static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1841 FunctionDecl *Fn = E->getDirectCallee();
1842 assert(Fn && "builtin call without direct callee!");
1843
1844 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1845 InitializedEntity Entity =
1846 InitializedEntity::InitializeParameter(S.Context, Param);
1847
1848 ExprResult Arg = E->getArg(0);
1849 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1850 if (Arg.isInvalid())
1851 return true;
1852
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001853 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001854 return false;
1855}
1856
Chris Lattnerdc046542009-05-08 06:58:22 +00001857/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1858/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1859/// type of its first argument. The main ActOnCallExpr routines have already
1860/// promoted the types of arguments because all of these calls are prototyped as
1861/// void(...).
1862///
1863/// This function goes through and does final semantic checking for these
1864/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001865ExprResult
1866Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001867 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001868 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1869 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1870
1871 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001872 if (TheCall->getNumArgs() < 1) {
1873 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1874 << 0 << 1 << TheCall->getNumArgs()
1875 << TheCall->getCallee()->getSourceRange();
1876 return ExprError();
1877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattnerdc046542009-05-08 06:58:22 +00001879 // Inspect the first argument of the atomic builtin. This should always be
1880 // a pointer type, whose element is an integral scalar or pointer type.
1881 // Because it is a pointer type, we don't have to worry about any implicit
1882 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001883 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001884 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001885 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1886 if (FirstArgResult.isInvalid())
1887 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001888 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001889 TheCall->setArg(0, FirstArg);
1890
John McCall31168b02011-06-15 23:02:42 +00001891 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1892 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001893 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1894 << FirstArg->getType() << FirstArg->getSourceRange();
1895 return ExprError();
1896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897
John McCall31168b02011-06-15 23:02:42 +00001898 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001899 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001900 !ValType->isBlockPointerType()) {
1901 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1902 << FirstArg->getType() << FirstArg->getSourceRange();
1903 return ExprError();
1904 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001905
John McCall31168b02011-06-15 23:02:42 +00001906 switch (ValType.getObjCLifetime()) {
1907 case Qualifiers::OCL_None:
1908 case Qualifiers::OCL_ExplicitNone:
1909 // okay
1910 break;
1911
1912 case Qualifiers::OCL_Weak:
1913 case Qualifiers::OCL_Strong:
1914 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001915 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001916 << ValType << FirstArg->getSourceRange();
1917 return ExprError();
1918 }
1919
John McCallb50451a2011-10-05 07:41:44 +00001920 // Strip any qualifiers off ValType.
1921 ValType = ValType.getUnqualifiedType();
1922
Chandler Carruth3973af72010-07-18 20:54:12 +00001923 // The majority of builtins return a value, but a few have special return
1924 // types, so allow them to override appropriately below.
1925 QualType ResultType = ValType;
1926
Chris Lattnerdc046542009-05-08 06:58:22 +00001927 // We need to figure out which concrete builtin this maps onto. For example,
1928 // __sync_fetch_and_add with a 2 byte object turns into
1929 // __sync_fetch_and_add_2.
1930#define BUILTIN_ROW(x) \
1931 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1932 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001933
Chris Lattnerdc046542009-05-08 06:58:22 +00001934 static const unsigned BuiltinIndices[][5] = {
1935 BUILTIN_ROW(__sync_fetch_and_add),
1936 BUILTIN_ROW(__sync_fetch_and_sub),
1937 BUILTIN_ROW(__sync_fetch_and_or),
1938 BUILTIN_ROW(__sync_fetch_and_and),
1939 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001940 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 BUILTIN_ROW(__sync_add_and_fetch),
1943 BUILTIN_ROW(__sync_sub_and_fetch),
1944 BUILTIN_ROW(__sync_and_and_fetch),
1945 BUILTIN_ROW(__sync_or_and_fetch),
1946 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001947 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001948
Chris Lattnerdc046542009-05-08 06:58:22 +00001949 BUILTIN_ROW(__sync_val_compare_and_swap),
1950 BUILTIN_ROW(__sync_bool_compare_and_swap),
1951 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001952 BUILTIN_ROW(__sync_lock_release),
1953 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001954 };
Mike Stump11289f42009-09-09 15:08:12 +00001955#undef BUILTIN_ROW
1956
Chris Lattnerdc046542009-05-08 06:58:22 +00001957 // Determine the index of the size.
1958 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001959 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001960 case 1: SizeIndex = 0; break;
1961 case 2: SizeIndex = 1; break;
1962 case 4: SizeIndex = 2; break;
1963 case 8: SizeIndex = 3; break;
1964 case 16: SizeIndex = 4; break;
1965 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001966 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1967 << FirstArg->getType() << FirstArg->getSourceRange();
1968 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001969 }
Mike Stump11289f42009-09-09 15:08:12 +00001970
Chris Lattnerdc046542009-05-08 06:58:22 +00001971 // Each of these builtins has one pointer argument, followed by some number of
1972 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1973 // that we ignore. Find out which row of BuiltinIndices to read from as well
1974 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001975 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001976 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001977 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001978 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001979 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001980 case Builtin::BI__sync_fetch_and_add:
1981 case Builtin::BI__sync_fetch_and_add_1:
1982 case Builtin::BI__sync_fetch_and_add_2:
1983 case Builtin::BI__sync_fetch_and_add_4:
1984 case Builtin::BI__sync_fetch_and_add_8:
1985 case Builtin::BI__sync_fetch_and_add_16:
1986 BuiltinIndex = 0;
1987 break;
1988
1989 case Builtin::BI__sync_fetch_and_sub:
1990 case Builtin::BI__sync_fetch_and_sub_1:
1991 case Builtin::BI__sync_fetch_and_sub_2:
1992 case Builtin::BI__sync_fetch_and_sub_4:
1993 case Builtin::BI__sync_fetch_and_sub_8:
1994 case Builtin::BI__sync_fetch_and_sub_16:
1995 BuiltinIndex = 1;
1996 break;
1997
1998 case Builtin::BI__sync_fetch_and_or:
1999 case Builtin::BI__sync_fetch_and_or_1:
2000 case Builtin::BI__sync_fetch_and_or_2:
2001 case Builtin::BI__sync_fetch_and_or_4:
2002 case Builtin::BI__sync_fetch_and_or_8:
2003 case Builtin::BI__sync_fetch_and_or_16:
2004 BuiltinIndex = 2;
2005 break;
2006
2007 case Builtin::BI__sync_fetch_and_and:
2008 case Builtin::BI__sync_fetch_and_and_1:
2009 case Builtin::BI__sync_fetch_and_and_2:
2010 case Builtin::BI__sync_fetch_and_and_4:
2011 case Builtin::BI__sync_fetch_and_and_8:
2012 case Builtin::BI__sync_fetch_and_and_16:
2013 BuiltinIndex = 3;
2014 break;
Mike Stump11289f42009-09-09 15:08:12 +00002015
Douglas Gregor73722482011-11-28 16:30:08 +00002016 case Builtin::BI__sync_fetch_and_xor:
2017 case Builtin::BI__sync_fetch_and_xor_1:
2018 case Builtin::BI__sync_fetch_and_xor_2:
2019 case Builtin::BI__sync_fetch_and_xor_4:
2020 case Builtin::BI__sync_fetch_and_xor_8:
2021 case Builtin::BI__sync_fetch_and_xor_16:
2022 BuiltinIndex = 4;
2023 break;
2024
Hal Finkeld2208b52014-10-02 20:53:50 +00002025 case Builtin::BI__sync_fetch_and_nand:
2026 case Builtin::BI__sync_fetch_and_nand_1:
2027 case Builtin::BI__sync_fetch_and_nand_2:
2028 case Builtin::BI__sync_fetch_and_nand_4:
2029 case Builtin::BI__sync_fetch_and_nand_8:
2030 case Builtin::BI__sync_fetch_and_nand_16:
2031 BuiltinIndex = 5;
2032 WarnAboutSemanticsChange = true;
2033 break;
2034
Douglas Gregor73722482011-11-28 16:30:08 +00002035 case Builtin::BI__sync_add_and_fetch:
2036 case Builtin::BI__sync_add_and_fetch_1:
2037 case Builtin::BI__sync_add_and_fetch_2:
2038 case Builtin::BI__sync_add_and_fetch_4:
2039 case Builtin::BI__sync_add_and_fetch_8:
2040 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002041 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002042 break;
2043
2044 case Builtin::BI__sync_sub_and_fetch:
2045 case Builtin::BI__sync_sub_and_fetch_1:
2046 case Builtin::BI__sync_sub_and_fetch_2:
2047 case Builtin::BI__sync_sub_and_fetch_4:
2048 case Builtin::BI__sync_sub_and_fetch_8:
2049 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002050 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002051 break;
2052
2053 case Builtin::BI__sync_and_and_fetch:
2054 case Builtin::BI__sync_and_and_fetch_1:
2055 case Builtin::BI__sync_and_and_fetch_2:
2056 case Builtin::BI__sync_and_and_fetch_4:
2057 case Builtin::BI__sync_and_and_fetch_8:
2058 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002059 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002060 break;
2061
2062 case Builtin::BI__sync_or_and_fetch:
2063 case Builtin::BI__sync_or_and_fetch_1:
2064 case Builtin::BI__sync_or_and_fetch_2:
2065 case Builtin::BI__sync_or_and_fetch_4:
2066 case Builtin::BI__sync_or_and_fetch_8:
2067 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002068 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002069 break;
2070
2071 case Builtin::BI__sync_xor_and_fetch:
2072 case Builtin::BI__sync_xor_and_fetch_1:
2073 case Builtin::BI__sync_xor_and_fetch_2:
2074 case Builtin::BI__sync_xor_and_fetch_4:
2075 case Builtin::BI__sync_xor_and_fetch_8:
2076 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002077 BuiltinIndex = 10;
2078 break;
2079
2080 case Builtin::BI__sync_nand_and_fetch:
2081 case Builtin::BI__sync_nand_and_fetch_1:
2082 case Builtin::BI__sync_nand_and_fetch_2:
2083 case Builtin::BI__sync_nand_and_fetch_4:
2084 case Builtin::BI__sync_nand_and_fetch_8:
2085 case Builtin::BI__sync_nand_and_fetch_16:
2086 BuiltinIndex = 11;
2087 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002088 break;
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattnerdc046542009-05-08 06:58:22 +00002090 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002091 case Builtin::BI__sync_val_compare_and_swap_1:
2092 case Builtin::BI__sync_val_compare_and_swap_2:
2093 case Builtin::BI__sync_val_compare_and_swap_4:
2094 case Builtin::BI__sync_val_compare_and_swap_8:
2095 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002096 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002097 NumFixed = 2;
2098 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002099
Chris Lattnerdc046542009-05-08 06:58:22 +00002100 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002101 case Builtin::BI__sync_bool_compare_and_swap_1:
2102 case Builtin::BI__sync_bool_compare_and_swap_2:
2103 case Builtin::BI__sync_bool_compare_and_swap_4:
2104 case Builtin::BI__sync_bool_compare_and_swap_8:
2105 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002106 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002107 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002108 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002109 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002110
2111 case Builtin::BI__sync_lock_test_and_set:
2112 case Builtin::BI__sync_lock_test_and_set_1:
2113 case Builtin::BI__sync_lock_test_and_set_2:
2114 case Builtin::BI__sync_lock_test_and_set_4:
2115 case Builtin::BI__sync_lock_test_and_set_8:
2116 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002117 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002118 break;
2119
Chris Lattnerdc046542009-05-08 06:58:22 +00002120 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002121 case Builtin::BI__sync_lock_release_1:
2122 case Builtin::BI__sync_lock_release_2:
2123 case Builtin::BI__sync_lock_release_4:
2124 case Builtin::BI__sync_lock_release_8:
2125 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002126 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002127 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002128 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002129 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002130
2131 case Builtin::BI__sync_swap:
2132 case Builtin::BI__sync_swap_1:
2133 case Builtin::BI__sync_swap_2:
2134 case Builtin::BI__sync_swap_4:
2135 case Builtin::BI__sync_swap_8:
2136 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002137 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002138 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002139 }
Mike Stump11289f42009-09-09 15:08:12 +00002140
Chris Lattnerdc046542009-05-08 06:58:22 +00002141 // Now that we know how many fixed arguments we expect, first check that we
2142 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002143 if (TheCall->getNumArgs() < 1+NumFixed) {
2144 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2145 << 0 << 1+NumFixed << TheCall->getNumArgs()
2146 << TheCall->getCallee()->getSourceRange();
2147 return ExprError();
2148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
Hal Finkeld2208b52014-10-02 20:53:50 +00002150 if (WarnAboutSemanticsChange) {
2151 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2152 << TheCall->getCallee()->getSourceRange();
2153 }
2154
Chris Lattner5b9241b2009-05-08 15:36:58 +00002155 // Get the decl for the concrete builtin from this, we can tell what the
2156 // concrete integer type we should convert to is.
2157 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002158 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002159 FunctionDecl *NewBuiltinDecl;
2160 if (NewBuiltinID == BuiltinID)
2161 NewBuiltinDecl = FDecl;
2162 else {
2163 // Perform builtin lookup to avoid redeclaring it.
2164 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2165 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2166 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2167 assert(Res.getFoundDecl());
2168 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002169 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002170 return ExprError();
2171 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002172
John McCallcf142162010-08-07 06:22:56 +00002173 // The first argument --- the pointer --- has a fixed type; we
2174 // deduce the types of the rest of the arguments accordingly. Walk
2175 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002176 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002177 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002178
Chris Lattnerdc046542009-05-08 06:58:22 +00002179 // GCC does an implicit conversion to the pointer or integer ValType. This
2180 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002181 // Initialize the argument.
2182 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2183 ValType, /*consume*/ false);
2184 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002185 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002186 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattnerdc046542009-05-08 06:58:22 +00002188 // Okay, we have something that *can* be converted to the right type. Check
2189 // to see if there is a potentially weird extension going on here. This can
2190 // happen when you do an atomic operation on something like an char* and
2191 // pass in 42. The 42 gets converted to char. This is even more strange
2192 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002193 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002194 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002195 }
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002197 ASTContext& Context = this->getASTContext();
2198
2199 // Create a new DeclRefExpr to refer to the new decl.
2200 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2201 Context,
2202 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002203 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002204 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002205 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002206 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002207 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002208 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002209
Chris Lattnerdc046542009-05-08 06:58:22 +00002210 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002211 // FIXME: This loses syntactic information.
2212 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2213 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2214 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002215 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002217 // Change the result type of the call to match the original value type. This
2218 // is arbitrary, but the codegen for these builtins ins design to handle it
2219 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002220 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002221
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002222 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002223}
2224
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002225/// SemaBuiltinNontemporalOverloaded - We have a call to
2226/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2227/// overloaded function based on the pointer type of its last argument.
2228///
2229/// This function goes through and does final semantic checking for these
2230/// builtins.
2231ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2232 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2233 DeclRefExpr *DRE =
2234 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2235 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2236 unsigned BuiltinID = FDecl->getBuiltinID();
2237 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2238 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2239 "Unexpected nontemporal load/store builtin!");
2240 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2241 unsigned numArgs = isStore ? 2 : 1;
2242
2243 // Ensure that we have the proper number of arguments.
2244 if (checkArgCount(*this, TheCall, numArgs))
2245 return ExprError();
2246
2247 // Inspect the last argument of the nontemporal builtin. This should always
2248 // be a pointer type, from which we imply the type of the memory access.
2249 // Because it is a pointer type, we don't have to worry about any implicit
2250 // casts here.
2251 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2252 ExprResult PointerArgResult =
2253 DefaultFunctionArrayLvalueConversion(PointerArg);
2254
2255 if (PointerArgResult.isInvalid())
2256 return ExprError();
2257 PointerArg = PointerArgResult.get();
2258 TheCall->setArg(numArgs - 1, PointerArg);
2259
2260 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2261 if (!pointerType) {
2262 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2263 << PointerArg->getType() << PointerArg->getSourceRange();
2264 return ExprError();
2265 }
2266
2267 QualType ValType = pointerType->getPointeeType();
2268
2269 // Strip any qualifiers off ValType.
2270 ValType = ValType.getUnqualifiedType();
2271 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2272 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2273 !ValType->isVectorType()) {
2274 Diag(DRE->getLocStart(),
2275 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2276 << PointerArg->getType() << PointerArg->getSourceRange();
2277 return ExprError();
2278 }
2279
2280 if (!isStore) {
2281 TheCall->setType(ValType);
2282 return TheCallResult;
2283 }
2284
2285 ExprResult ValArg = TheCall->getArg(0);
2286 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2287 Context, ValType, /*consume*/ false);
2288 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2289 if (ValArg.isInvalid())
2290 return ExprError();
2291
2292 TheCall->setArg(0, ValArg.get());
2293 TheCall->setType(Context.VoidTy);
2294 return TheCallResult;
2295}
2296
Chris Lattner6436fb62009-02-18 06:01:06 +00002297/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002298/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002299/// Note: It might also make sense to do the UTF-16 conversion here (would
2300/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002301bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002302 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002303 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2304
Douglas Gregorfb65e592011-07-27 05:40:30 +00002305 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002306 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2307 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002308 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002309 }
Mike Stump11289f42009-09-09 15:08:12 +00002310
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002311 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002312 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002313 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002314 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002315 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002316 UTF16 *ToPtr = &ToBuf[0];
2317
2318 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2319 &ToPtr, ToPtr + NumBytes,
2320 strictConversion);
2321 // Check for conversion failure.
2322 if (Result != conversionOK)
2323 Diag(Arg->getLocStart(),
2324 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2325 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002326 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002327}
2328
Charles Davisc7d5c942015-09-17 20:55:33 +00002329/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2330/// for validity. Emit an error and return true on failure; return false
2331/// on success.
2332bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002333 Expr *Fn = TheCall->getCallee();
2334 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002335 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002336 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002337 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2338 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002339 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002340 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002341 return true;
2342 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002343
2344 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002345 return Diag(TheCall->getLocEnd(),
2346 diag::err_typecheck_call_too_few_args_at_least)
2347 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002348 }
2349
John McCall29ad95b2011-08-27 01:09:30 +00002350 // Type-check the first argument normally.
2351 if (checkBuiltinArgument(*this, TheCall, 0))
2352 return true;
2353
Chris Lattnere202e6a2007-12-20 00:05:45 +00002354 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002355 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002356 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002357 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002358 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002359 else if (FunctionDecl *FD = getCurFunctionDecl())
2360 isVariadic = FD->isVariadic();
2361 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002362 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002363
Chris Lattnere202e6a2007-12-20 00:05:45 +00002364 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002365 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2366 return true;
2367 }
Mike Stump11289f42009-09-09 15:08:12 +00002368
Chris Lattner43be2e62007-12-19 23:59:04 +00002369 // Verify that the second argument to the builtin is the last argument of the
2370 // current function or method.
2371 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002372 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002373
Nico Weber9eea7642013-05-24 23:31:57 +00002374 // These are valid if SecondArgIsLastNamedArgument is false after the next
2375 // block.
2376 QualType Type;
2377 SourceLocation ParamLoc;
2378
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002379 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2380 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002381 // FIXME: This isn't correct for methods (results in bogus warning).
2382 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002383 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002384 if (CurBlock)
2385 LastArg = *(CurBlock->TheDecl->param_end()-1);
2386 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002387 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002388 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002389 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002390 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002391
2392 Type = PV->getType();
2393 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002394 }
2395 }
Mike Stump11289f42009-09-09 15:08:12 +00002396
Chris Lattner43be2e62007-12-19 23:59:04 +00002397 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002398 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002399 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002400 else if (Type->isReferenceType()) {
2401 Diag(Arg->getLocStart(),
2402 diag::warn_va_start_of_reference_type_is_undefined);
2403 Diag(ParamLoc, diag::note_parameter_type) << Type;
2404 }
2405
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002406 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002407 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002408}
Chris Lattner43be2e62007-12-19 23:59:04 +00002409
Charles Davisc7d5c942015-09-17 20:55:33 +00002410/// Check the arguments to '__builtin_va_start' for validity, and that
2411/// it was called from a function of the native ABI.
2412/// Emit an error and return true on failure; return false on success.
2413bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2414 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2415 // On x64 Windows, don't allow this in System V ABI functions.
2416 // (Yes, that means there's no corresponding way to support variadic
2417 // System V ABI functions on Windows.)
2418 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2419 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2420 clang::CallingConv CC = CC_C;
2421 if (const FunctionDecl *FD = getCurFunctionDecl())
2422 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2423 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2424 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2425 return Diag(TheCall->getCallee()->getLocStart(),
2426 diag::err_va_start_used_in_wrong_abi_function)
2427 << (OS != llvm::Triple::Win32);
2428 }
2429 return SemaBuiltinVAStartImpl(TheCall);
2430}
2431
2432/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2433/// it was called from a Win64 ABI function.
2434/// Emit an error and return true on failure; return false on success.
2435bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2436 // This only makes sense for x86-64.
2437 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2438 Expr *Callee = TheCall->getCallee();
2439 if (TT.getArch() != llvm::Triple::x86_64)
2440 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2441 // Don't allow this in System V ABI functions.
2442 clang::CallingConv CC = CC_C;
2443 if (const FunctionDecl *FD = getCurFunctionDecl())
2444 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2445 if (CC == CC_X86_64SysV ||
2446 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2447 return Diag(Callee->getLocStart(),
2448 diag::err_ms_va_start_used_in_sysv_function);
2449 return SemaBuiltinVAStartImpl(TheCall);
2450}
2451
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002452bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2453 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2454 // const char *named_addr);
2455
2456 Expr *Func = Call->getCallee();
2457
2458 if (Call->getNumArgs() < 3)
2459 return Diag(Call->getLocEnd(),
2460 diag::err_typecheck_call_too_few_args_at_least)
2461 << 0 /*function call*/ << 3 << Call->getNumArgs();
2462
2463 // Determine whether the current function is variadic or not.
2464 bool IsVariadic;
2465 if (BlockScopeInfo *CurBlock = getCurBlock())
2466 IsVariadic = CurBlock->TheDecl->isVariadic();
2467 else if (FunctionDecl *FD = getCurFunctionDecl())
2468 IsVariadic = FD->isVariadic();
2469 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2470 IsVariadic = MD->isVariadic();
2471 else
2472 llvm_unreachable("unexpected statement type");
2473
2474 if (!IsVariadic) {
2475 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2476 return true;
2477 }
2478
2479 // Type-check the first argument normally.
2480 if (checkBuiltinArgument(*this, Call, 0))
2481 return true;
2482
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002483 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002484 unsigned ArgNo;
2485 QualType Type;
2486 } ArgumentTypes[] = {
2487 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2488 { 2, Context.getSizeType() },
2489 };
2490
2491 for (const auto &AT : ArgumentTypes) {
2492 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2493 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2494 continue;
2495 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2496 << Arg->getType() << AT.Type << 1 /* different class */
2497 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2498 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2499 }
2500
2501 return false;
2502}
2503
Chris Lattner2da14fb2007-12-20 00:26:33 +00002504/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2505/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002506bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2507 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002508 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002509 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002510 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002511 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002512 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002513 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002514 << SourceRange(TheCall->getArg(2)->getLocStart(),
2515 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002516
John Wiegley01296292011-04-08 18:41:53 +00002517 ExprResult OrigArg0 = TheCall->getArg(0);
2518 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002519
Chris Lattner2da14fb2007-12-20 00:26:33 +00002520 // Do standard promotions between the two arguments, returning their common
2521 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002522 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002523 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2524 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002525
2526 // Make sure any conversions are pushed back into the call; this is
2527 // type safe since unordered compare builtins are declared as "_Bool
2528 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002529 TheCall->setArg(0, OrigArg0.get());
2530 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002531
John Wiegley01296292011-04-08 18:41:53 +00002532 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002533 return false;
2534
Chris Lattner2da14fb2007-12-20 00:26:33 +00002535 // If the common type isn't a real floating type, then the arguments were
2536 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002537 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002538 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002539 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002540 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2541 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002542
Chris Lattner2da14fb2007-12-20 00:26:33 +00002543 return false;
2544}
2545
Benjamin Kramer634fc102010-02-15 22:42:31 +00002546/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2547/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002548/// to check everything. We expect the last argument to be a floating point
2549/// value.
2550bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2551 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002552 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002553 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002554 if (TheCall->getNumArgs() > NumArgs)
2555 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002556 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002557 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002558 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002559 (*(TheCall->arg_end()-1))->getLocEnd());
2560
Benjamin Kramer64aae502010-02-16 10:07:31 +00002561 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002562
Eli Friedman7e4faac2009-08-31 20:06:00 +00002563 if (OrigArg->isTypeDependent())
2564 return false;
2565
Chris Lattner68784ef2010-05-06 05:50:07 +00002566 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002567 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002568 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002569 diag::err_typecheck_call_invalid_unary_fp)
2570 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002571
Chris Lattner68784ef2010-05-06 05:50:07 +00002572 // If this is an implicit conversion from float -> double, remove it.
2573 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2574 Expr *CastArg = Cast->getSubExpr();
2575 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2576 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2577 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002578 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002579 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002580 }
2581 }
2582
Eli Friedman7e4faac2009-08-31 20:06:00 +00002583 return false;
2584}
2585
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002586/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2587// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002588ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002589 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002590 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002591 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002592 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2593 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002594
Nate Begemana0110022010-06-08 00:16:34 +00002595 // Determine which of the following types of shufflevector we're checking:
2596 // 1) unary, vector mask: (lhs, mask)
2597 // 2) binary, vector mask: (lhs, rhs, mask)
2598 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2599 QualType resType = TheCall->getArg(0)->getType();
2600 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002601
Douglas Gregorc25f7662009-05-19 22:10:17 +00002602 if (!TheCall->getArg(0)->isTypeDependent() &&
2603 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002604 QualType LHSType = TheCall->getArg(0)->getType();
2605 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002606
Craig Topperbaca3892013-07-29 06:47:04 +00002607 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2608 return ExprError(Diag(TheCall->getLocStart(),
2609 diag::err_shufflevector_non_vector)
2610 << SourceRange(TheCall->getArg(0)->getLocStart(),
2611 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002612
Nate Begemana0110022010-06-08 00:16:34 +00002613 numElements = LHSType->getAs<VectorType>()->getNumElements();
2614 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002615
Nate Begemana0110022010-06-08 00:16:34 +00002616 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2617 // with mask. If so, verify that RHS is an integer vector type with the
2618 // same number of elts as lhs.
2619 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002620 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002621 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002622 return ExprError(Diag(TheCall->getLocStart(),
2623 diag::err_shufflevector_incompatible_vector)
2624 << SourceRange(TheCall->getArg(1)->getLocStart(),
2625 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002626 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002627 return ExprError(Diag(TheCall->getLocStart(),
2628 diag::err_shufflevector_incompatible_vector)
2629 << SourceRange(TheCall->getArg(0)->getLocStart(),
2630 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002631 } else if (numElements != numResElements) {
2632 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002633 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002634 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002635 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002636 }
2637
2638 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002639 if (TheCall->getArg(i)->isTypeDependent() ||
2640 TheCall->getArg(i)->isValueDependent())
2641 continue;
2642
Nate Begemana0110022010-06-08 00:16:34 +00002643 llvm::APSInt Result(32);
2644 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2645 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002646 diag::err_shufflevector_nonconstant_argument)
2647 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002648
Craig Topper50ad5b72013-08-03 17:40:38 +00002649 // Allow -1 which will be translated to undef in the IR.
2650 if (Result.isSigned() && Result.isAllOnesValue())
2651 continue;
2652
Chris Lattner7ab824e2008-08-10 02:05:13 +00002653 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002654 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002655 diag::err_shufflevector_argument_too_large)
2656 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002657 }
2658
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002659 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002660
Chris Lattner7ab824e2008-08-10 02:05:13 +00002661 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002662 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002663 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002664 }
2665
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002666 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2667 TheCall->getCallee()->getLocStart(),
2668 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002669}
Chris Lattner43be2e62007-12-19 23:59:04 +00002670
Hal Finkelc4d7c822013-09-18 03:29:45 +00002671/// SemaConvertVectorExpr - Handle __builtin_convertvector
2672ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2673 SourceLocation BuiltinLoc,
2674 SourceLocation RParenLoc) {
2675 ExprValueKind VK = VK_RValue;
2676 ExprObjectKind OK = OK_Ordinary;
2677 QualType DstTy = TInfo->getType();
2678 QualType SrcTy = E->getType();
2679
2680 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2681 return ExprError(Diag(BuiltinLoc,
2682 diag::err_convertvector_non_vector)
2683 << E->getSourceRange());
2684 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2685 return ExprError(Diag(BuiltinLoc,
2686 diag::err_convertvector_non_vector_type));
2687
2688 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2689 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2690 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2691 if (SrcElts != DstElts)
2692 return ExprError(Diag(BuiltinLoc,
2693 diag::err_convertvector_incompatible_vector)
2694 << E->getSourceRange());
2695 }
2696
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002697 return new (Context)
2698 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002699}
2700
Daniel Dunbarb7257262008-07-21 22:59:13 +00002701/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2702// This is declared to take (const void*, ...) and can take two
2703// optional constant int args.
2704bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002705 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002706
Chris Lattner3b054132008-11-19 05:08:23 +00002707 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002708 return Diag(TheCall->getLocEnd(),
2709 diag::err_typecheck_call_too_many_args_at_most)
2710 << 0 /*function call*/ << 3 << NumArgs
2711 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002712
2713 // Argument 0 is checked for us and the remaining arguments must be
2714 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002715 for (unsigned i = 1; i != NumArgs; ++i)
2716 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002717 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002718
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002719 return false;
2720}
2721
Hal Finkelf0417332014-07-17 14:25:55 +00002722/// SemaBuiltinAssume - Handle __assume (MS Extension).
2723// __assume does not evaluate its arguments, and should warn if its argument
2724// has side effects.
2725bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2726 Expr *Arg = TheCall->getArg(0);
2727 if (Arg->isInstantiationDependent()) return false;
2728
2729 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002730 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002731 << Arg->getSourceRange()
2732 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2733
2734 return false;
2735}
2736
2737/// Handle __builtin_assume_aligned. This is declared
2738/// as (const void*, size_t, ...) and can take one optional constant int arg.
2739bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2740 unsigned NumArgs = TheCall->getNumArgs();
2741
2742 if (NumArgs > 3)
2743 return Diag(TheCall->getLocEnd(),
2744 diag::err_typecheck_call_too_many_args_at_most)
2745 << 0 /*function call*/ << 3 << NumArgs
2746 << TheCall->getSourceRange();
2747
2748 // The alignment must be a constant integer.
2749 Expr *Arg = TheCall->getArg(1);
2750
2751 // We can't check the value of a dependent argument.
2752 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2753 llvm::APSInt Result;
2754 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2755 return true;
2756
2757 if (!Result.isPowerOf2())
2758 return Diag(TheCall->getLocStart(),
2759 diag::err_alignment_not_power_of_two)
2760 << Arg->getSourceRange();
2761 }
2762
2763 if (NumArgs > 2) {
2764 ExprResult Arg(TheCall->getArg(2));
2765 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2766 Context.getSizeType(), false);
2767 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2768 if (Arg.isInvalid()) return true;
2769 TheCall->setArg(2, Arg.get());
2770 }
Hal Finkelf0417332014-07-17 14:25:55 +00002771
2772 return false;
2773}
2774
Eric Christopher8d0c6212010-04-17 02:26:23 +00002775/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2776/// TheCall is a constant expression.
2777bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2778 llvm::APSInt &Result) {
2779 Expr *Arg = TheCall->getArg(ArgNum);
2780 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2781 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2782
2783 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2784
2785 if (!Arg->isIntegerConstantExpr(Result, Context))
2786 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002787 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002788
Chris Lattnerd545ad12009-09-23 06:06:36 +00002789 return false;
2790}
2791
Richard Sandiford28940af2014-04-16 08:47:51 +00002792/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2793/// TheCall is a constant expression in the range [Low, High].
2794bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2795 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002796 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002797
2798 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002799 Expr *Arg = TheCall->getArg(ArgNum);
2800 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002801 return false;
2802
Eric Christopher8d0c6212010-04-17 02:26:23 +00002803 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002804 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002805 return true;
2806
Richard Sandiford28940af2014-04-16 08:47:51 +00002807 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002808 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002809 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002810
2811 return false;
2812}
2813
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002814/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2815/// TheCall is an ARM/AArch64 special register string literal.
2816bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2817 int ArgNum, unsigned ExpectedFieldNum,
2818 bool AllowName) {
2819 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2820 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2821 BuiltinID == ARM::BI__builtin_arm_rsr ||
2822 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2823 BuiltinID == ARM::BI__builtin_arm_wsr ||
2824 BuiltinID == ARM::BI__builtin_arm_wsrp;
2825 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2826 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2827 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2828 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2829 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2830 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2831 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2832
2833 // We can't check the value of a dependent argument.
2834 Expr *Arg = TheCall->getArg(ArgNum);
2835 if (Arg->isTypeDependent() || Arg->isValueDependent())
2836 return false;
2837
2838 // Check if the argument is a string literal.
2839 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2840 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2841 << Arg->getSourceRange();
2842
2843 // Check the type of special register given.
2844 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2845 SmallVector<StringRef, 6> Fields;
2846 Reg.split(Fields, ":");
2847
2848 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2849 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2850 << Arg->getSourceRange();
2851
2852 // If the string is the name of a register then we cannot check that it is
2853 // valid here but if the string is of one the forms described in ACLE then we
2854 // can check that the supplied fields are integers and within the valid
2855 // ranges.
2856 if (Fields.size() > 1) {
2857 bool FiveFields = Fields.size() == 5;
2858
2859 bool ValidString = true;
2860 if (IsARMBuiltin) {
2861 ValidString &= Fields[0].startswith_lower("cp") ||
2862 Fields[0].startswith_lower("p");
2863 if (ValidString)
2864 Fields[0] =
2865 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2866
2867 ValidString &= Fields[2].startswith_lower("c");
2868 if (ValidString)
2869 Fields[2] = Fields[2].drop_front(1);
2870
2871 if (FiveFields) {
2872 ValidString &= Fields[3].startswith_lower("c");
2873 if (ValidString)
2874 Fields[3] = Fields[3].drop_front(1);
2875 }
2876 }
2877
2878 SmallVector<int, 5> Ranges;
2879 if (FiveFields)
2880 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2881 else
2882 Ranges.append({15, 7, 15});
2883
2884 for (unsigned i=0; i<Fields.size(); ++i) {
2885 int IntField;
2886 ValidString &= !Fields[i].getAsInteger(10, IntField);
2887 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2888 }
2889
2890 if (!ValidString)
2891 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2892 << Arg->getSourceRange();
2893
2894 } else if (IsAArch64Builtin && Fields.size() == 1) {
2895 // If the register name is one of those that appear in the condition below
2896 // and the special register builtin being used is one of the write builtins,
2897 // then we require that the argument provided for writing to the register
2898 // is an integer constant expression. This is because it will be lowered to
2899 // an MSR (immediate) instruction, so we need to know the immediate at
2900 // compile time.
2901 if (TheCall->getNumArgs() != 2)
2902 return false;
2903
2904 std::string RegLower = Reg.lower();
2905 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2906 RegLower != "pan" && RegLower != "uao")
2907 return false;
2908
2909 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2910 }
2911
2912 return false;
2913}
2914
Eric Christopherd9832702015-06-29 21:00:05 +00002915/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2916/// This checks that the target supports __builtin_cpu_supports and
2917/// that the string argument is constant and valid.
2918bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2919 Expr *Arg = TheCall->getArg(0);
2920
2921 // Check if the argument is a string literal.
2922 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2923 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2924 << Arg->getSourceRange();
2925
2926 // Check the contents of the string.
2927 StringRef Feature =
2928 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2929 if (!Context.getTargetInfo().validateCpuSupports(Feature))
2930 return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2931 << Arg->getSourceRange();
2932 return false;
2933}
2934
Eli Friedmanc97d0142009-05-03 06:04:26 +00002935/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002936/// This checks that the target supports __builtin_longjmp and
2937/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002938bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002939 if (!Context.getTargetInfo().hasSjLjLowering())
2940 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2941 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2942
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002943 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002944 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002945
Eric Christopher8d0c6212010-04-17 02:26:23 +00002946 // TODO: This is less than ideal. Overload this to take a value.
2947 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2948 return true;
2949
2950 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002951 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2952 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2953
2954 return false;
2955}
2956
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002957
2958/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2959/// This checks that the target supports __builtin_setjmp.
2960bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2961 if (!Context.getTargetInfo().hasSjLjLowering())
2962 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2963 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2964 return false;
2965}
2966
Richard Smithd7293d72013-08-05 18:49:43 +00002967namespace {
2968enum StringLiteralCheckType {
2969 SLCT_NotALiteral,
2970 SLCT_UncheckedLiteral,
2971 SLCT_CheckedLiteral
2972};
2973}
2974
Richard Smith55ce3522012-06-25 20:30:08 +00002975// Determine if an expression is a string literal or constant string.
2976// If this function returns false on the arguments to a function expecting a
2977// format string, we will usually need to emit a warning.
2978// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002979static StringLiteralCheckType
2980checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2981 bool HasVAListArg, unsigned format_idx,
2982 unsigned firstDataArg, Sema::FormatStringType Type,
2983 Sema::VariadicCallType CallType, bool InFunctionCall,
2984 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002985 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002986 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002987 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002988
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002989 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002990
Richard Smithd7293d72013-08-05 18:49:43 +00002991 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002992 // Technically -Wformat-nonliteral does not warn about this case.
2993 // The behavior of printf and friends in this case is implementation
2994 // dependent. Ideally if the format string cannot be null then
2995 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002996 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002997
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002998 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002999 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003000 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003001 // The expression is a literal if both sub-expressions were, and it was
3002 // completely checked only if both sub-expressions were checked.
3003 const AbstractConditionalOperator *C =
3004 cast<AbstractConditionalOperator>(E);
3005 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003006 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003007 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003008 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003009 if (Left == SLCT_NotALiteral)
3010 return SLCT_NotALiteral;
3011 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003012 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003013 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003014 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003015 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003016 }
3017
3018 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003019 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3020 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003021 }
3022
John McCallc07a0c72011-02-17 10:25:35 +00003023 case Stmt::OpaqueValueExprClass:
3024 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3025 E = src;
3026 goto tryAgain;
3027 }
Richard Smith55ce3522012-06-25 20:30:08 +00003028 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003029
Ted Kremeneka8890832011-02-24 23:03:04 +00003030 case Stmt::PredefinedExprClass:
3031 // While __func__, etc., are technically not string literals, they
3032 // cannot contain format specifiers and thus are not a security
3033 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003034 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003035
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003036 case Stmt::DeclRefExprClass: {
3037 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003038
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003039 // As an exception, do not flag errors for variables binding to
3040 // const string literals.
3041 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3042 bool isConstant = false;
3043 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003044
Richard Smithd7293d72013-08-05 18:49:43 +00003045 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3046 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003047 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003048 isConstant = T.isConstant(S.Context) &&
3049 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003050 } else if (T->isObjCObjectPointerType()) {
3051 // In ObjC, there is usually no "const ObjectPointer" type,
3052 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003053 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003054 }
Mike Stump11289f42009-09-09 15:08:12 +00003055
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003056 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003057 if (const Expr *Init = VD->getAnyInitializer()) {
3058 // Look through initializers like const char c[] = { "foo" }
3059 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3060 if (InitList->isStringLiteralInit())
3061 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3062 }
Richard Smithd7293d72013-08-05 18:49:43 +00003063 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003064 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003065 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003066 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003067 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003068 }
Mike Stump11289f42009-09-09 15:08:12 +00003069
Anders Carlssonb012ca92009-06-28 19:55:58 +00003070 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3071 // special check to see if the format string is a function parameter
3072 // of the function calling the printf function. If the function
3073 // has an attribute indicating it is a printf-like function, then we
3074 // should suppress warnings concerning non-literals being used in a call
3075 // to a vprintf function. For example:
3076 //
3077 // void
3078 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3079 // va_list ap;
3080 // va_start(ap, fmt);
3081 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3082 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003083 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003084 if (HasVAListArg) {
3085 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3086 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3087 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003088 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003089 // adjust for implicit parameter
3090 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3091 if (MD->isInstance())
3092 ++PVIndex;
3093 // We also check if the formats are compatible.
3094 // We can't pass a 'scanf' string to a 'printf' function.
3095 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003096 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003097 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003098 }
3099 }
3100 }
3101 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Richard Smith55ce3522012-06-25 20:30:08 +00003104 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003105 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003106
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003107 case Stmt::CallExprClass:
3108 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003109 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003110 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3111 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3112 unsigned ArgIndex = FA->getFormatIdx();
3113 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3114 if (MD->isInstance())
3115 --ArgIndex;
3116 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003117
Richard Smithd7293d72013-08-05 18:49:43 +00003118 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003119 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003120 Type, CallType, InFunctionCall,
3121 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003122 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3123 unsigned BuiltinID = FD->getBuiltinID();
3124 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3125 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3126 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003127 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003128 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003129 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003130 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003131 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003132 }
3133 }
Mike Stump11289f42009-09-09 15:08:12 +00003134
Richard Smith55ce3522012-06-25 20:30:08 +00003135 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003136 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003137 case Stmt::ObjCStringLiteralClass:
3138 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003139 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003140
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003141 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003142 StrE = ObjCFExpr->getString();
3143 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003144 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003145
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003146 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003147 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3148 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003149 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003150 }
Mike Stump11289f42009-09-09 15:08:12 +00003151
Richard Smith55ce3522012-06-25 20:30:08 +00003152 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003153 }
Mike Stump11289f42009-09-09 15:08:12 +00003154
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003155 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003156 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003157 }
3158}
3159
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003160Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003161 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003162 .Case("scanf", FST_Scanf)
3163 .Cases("printf", "printf0", FST_Printf)
3164 .Cases("NSString", "CFString", FST_NSString)
3165 .Case("strftime", FST_Strftime)
3166 .Case("strfmon", FST_Strfmon)
3167 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003168 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003169 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003170 .Default(FST_Unknown);
3171}
3172
Jordan Rose3e0ec582012-07-19 18:10:23 +00003173/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003174/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003175/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003176bool Sema::CheckFormatArguments(const FormatAttr *Format,
3177 ArrayRef<const Expr *> Args,
3178 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003179 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003180 SourceLocation Loc, SourceRange Range,
3181 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003182 FormatStringInfo FSI;
3183 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003184 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003185 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003186 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003187 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003188}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003189
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003190bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003191 bool HasVAListArg, unsigned format_idx,
3192 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003193 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003194 SourceLocation Loc, SourceRange Range,
3195 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003196 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003197 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003198 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003199 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003200 }
Mike Stump11289f42009-09-09 15:08:12 +00003201
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003202 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003203
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003204 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003205 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003206 // Dynamically generated format strings are difficult to
3207 // automatically vet at compile time. Requiring that format strings
3208 // are string literals: (1) permits the checking of format strings by
3209 // the compiler and thereby (2) can practically remove the source of
3210 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003211
Mike Stump11289f42009-09-09 15:08:12 +00003212 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003213 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003214 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003215 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003216 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003217 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3218 format_idx, firstDataArg, Type, CallType,
3219 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003220 if (CT != SLCT_NotALiteral)
3221 // Literal format string found, check done!
3222 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003223
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003224 // Strftime is particular as it always uses a single 'time' argument,
3225 // so it is safe to pass a non-literal string.
3226 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003227 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003228
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003229 // Do not emit diag when the string param is a macro expansion and the
3230 // format is either NSString or CFString. This is a hack to prevent
3231 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3232 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003233 if (Type == FST_NSString &&
3234 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003235 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003236
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003237 // If there are no arguments specified, warn with -Wformat-security, otherwise
3238 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003239 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003240 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003241 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003242 << OrigFormatExpr->getSourceRange();
3243 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003244 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003245 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003246 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003247 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003248}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003249
Ted Kremenekab278de2010-01-28 23:39:18 +00003250namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003251class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3252protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003253 Sema &S;
3254 const StringLiteral *FExpr;
3255 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003256 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003257 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003258 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003259 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003260 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003261 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003262 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003263 bool usesPositionalArgs;
3264 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003265 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003266 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003267 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003268public:
Ted Kremenek02087932010-07-16 02:11:22 +00003269 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003270 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003271 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003272 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003273 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003274 Sema::VariadicCallType callType,
3275 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003276 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003277 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3278 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003279 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003280 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003281 inFunctionCall(inFunctionCall), CallType(callType),
3282 CheckedVarArgs(CheckedVarArgs) {
3283 CoveredArgs.resize(numDataArgs);
3284 CoveredArgs.reset();
3285 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003286
Ted Kremenek019d2242010-01-29 01:50:07 +00003287 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003288
Ted Kremenek02087932010-07-16 02:11:22 +00003289 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003290 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003291
Jordan Rose92303592012-09-08 04:00:03 +00003292 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003293 const analyze_format_string::FormatSpecifier &FS,
3294 const analyze_format_string::ConversionSpecifier &CS,
3295 const char *startSpecifier, unsigned specifierLen,
3296 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003297
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003298 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003299 const analyze_format_string::FormatSpecifier &FS,
3300 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003301
3302 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003303 const analyze_format_string::ConversionSpecifier &CS,
3304 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003305
Craig Toppere14c0f82014-03-12 04:55:44 +00003306 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003307
Craig Toppere14c0f82014-03-12 04:55:44 +00003308 void HandleInvalidPosition(const char *startSpecifier,
3309 unsigned specifierLen,
3310 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003311
Craig Toppere14c0f82014-03-12 04:55:44 +00003312 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003313
Craig Toppere14c0f82014-03-12 04:55:44 +00003314 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003315
Richard Trieu03cf7b72011-10-28 00:41:25 +00003316 template <typename Range>
3317 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3318 const Expr *ArgumentExpr,
3319 PartialDiagnostic PDiag,
3320 SourceLocation StringLoc,
3321 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003322 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003323
Ted Kremenek02087932010-07-16 02:11:22 +00003324protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003325 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3326 const char *startSpec,
3327 unsigned specifierLen,
3328 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003329
3330 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3331 const char *startSpec,
3332 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003333
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003334 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003335 CharSourceRange getSpecifierRange(const char *startSpecifier,
3336 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003337 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003338
Ted Kremenek5739de72010-01-29 01:06:55 +00003339 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003340
3341 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3342 const analyze_format_string::ConversionSpecifier &CS,
3343 const char *startSpecifier, unsigned specifierLen,
3344 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003345
3346 template <typename Range>
3347 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3348 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003349 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003350};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003351}
Ted Kremenekab278de2010-01-28 23:39:18 +00003352
Ted Kremenek02087932010-07-16 02:11:22 +00003353SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003354 return OrigFormatExpr->getSourceRange();
3355}
3356
Ted Kremenek02087932010-07-16 02:11:22 +00003357CharSourceRange CheckFormatHandler::
3358getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003359 SourceLocation Start = getLocationOfByte(startSpecifier);
3360 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3361
3362 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003363 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003364
3365 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003366}
3367
Ted Kremenek02087932010-07-16 02:11:22 +00003368SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003369 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003370}
3371
Ted Kremenek02087932010-07-16 02:11:22 +00003372void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3373 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3375 getLocationOfByte(startSpecifier),
3376 /*IsStringLocation*/true,
3377 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003378}
3379
Jordan Rose92303592012-09-08 04:00:03 +00003380void CheckFormatHandler::HandleInvalidLengthModifier(
3381 const analyze_format_string::FormatSpecifier &FS,
3382 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003383 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003384 using namespace analyze_format_string;
3385
3386 const LengthModifier &LM = FS.getLengthModifier();
3387 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3388
3389 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003390 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003391 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003392 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003393 getLocationOfByte(LM.getStart()),
3394 /*IsStringLocation*/true,
3395 getSpecifierRange(startSpecifier, specifierLen));
3396
3397 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3398 << FixedLM->toString()
3399 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3400
3401 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003402 FixItHint Hint;
3403 if (DiagID == diag::warn_format_nonsensical_length)
3404 Hint = FixItHint::CreateRemoval(LMRange);
3405
3406 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003407 getLocationOfByte(LM.getStart()),
3408 /*IsStringLocation*/true,
3409 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003410 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003411 }
3412}
3413
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003414void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003415 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003416 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003417 using namespace analyze_format_string;
3418
3419 const LengthModifier &LM = FS.getLengthModifier();
3420 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3421
3422 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003423 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003424 if (FixedLM) {
3425 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3426 << LM.toString() << 0,
3427 getLocationOfByte(LM.getStart()),
3428 /*IsStringLocation*/true,
3429 getSpecifierRange(startSpecifier, specifierLen));
3430
3431 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3432 << FixedLM->toString()
3433 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3434
3435 } else {
3436 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3437 << LM.toString() << 0,
3438 getLocationOfByte(LM.getStart()),
3439 /*IsStringLocation*/true,
3440 getSpecifierRange(startSpecifier, specifierLen));
3441 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003442}
3443
3444void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3445 const analyze_format_string::ConversionSpecifier &CS,
3446 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003447 using namespace analyze_format_string;
3448
3449 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003450 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003451 if (FixedCS) {
3452 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3453 << CS.toString() << /*conversion specifier*/1,
3454 getLocationOfByte(CS.getStart()),
3455 /*IsStringLocation*/true,
3456 getSpecifierRange(startSpecifier, specifierLen));
3457
3458 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3459 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3460 << FixedCS->toString()
3461 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3462 } else {
3463 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3464 << CS.toString() << /*conversion specifier*/1,
3465 getLocationOfByte(CS.getStart()),
3466 /*IsStringLocation*/true,
3467 getSpecifierRange(startSpecifier, specifierLen));
3468 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003469}
3470
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003471void CheckFormatHandler::HandlePosition(const char *startPos,
3472 unsigned posLen) {
3473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3474 getLocationOfByte(startPos),
3475 /*IsStringLocation*/true,
3476 getSpecifierRange(startPos, posLen));
3477}
3478
Ted Kremenekd1668192010-02-27 01:41:03 +00003479void
Ted Kremenek02087932010-07-16 02:11:22 +00003480CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3481 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003482 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3483 << (unsigned) p,
3484 getLocationOfByte(startPos), /*IsStringLocation*/true,
3485 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003486}
3487
Ted Kremenek02087932010-07-16 02:11:22 +00003488void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003489 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3491 getLocationOfByte(startPos),
3492 /*IsStringLocation*/true,
3493 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003494}
3495
Ted Kremenek02087932010-07-16 02:11:22 +00003496void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003497 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003498 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003499 EmitFormatDiagnostic(
3500 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3501 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3502 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003503 }
Ted Kremenek02087932010-07-16 02:11:22 +00003504}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003505
Jordan Rose58bbe422012-07-19 18:10:08 +00003506// Note that this may return NULL if there was an error parsing or building
3507// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003508const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003509 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003510}
3511
3512void CheckFormatHandler::DoneProcessing() {
3513 // Does the number of data arguments exceed the number of
3514 // format conversions in the format string?
3515 if (!HasVAListArg) {
3516 // Find any arguments that weren't covered.
3517 CoveredArgs.flip();
3518 signed notCoveredArg = CoveredArgs.find_first();
3519 if (notCoveredArg >= 0) {
3520 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003521 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3522 SourceLocation Loc = E->getLocStart();
3523 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3524 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3525 Loc, /*IsStringLocation*/false,
3526 getFormatStringRange());
3527 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003528 }
Ted Kremenek02087932010-07-16 02:11:22 +00003529 }
3530 }
3531}
3532
Ted Kremenekce815422010-07-19 21:25:57 +00003533bool
3534CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3535 SourceLocation Loc,
3536 const char *startSpec,
3537 unsigned specifierLen,
3538 const char *csStart,
3539 unsigned csLen) {
3540
3541 bool keepGoing = true;
3542 if (argIndex < NumDataArgs) {
3543 // Consider the argument coverered, even though the specifier doesn't
3544 // make sense.
3545 CoveredArgs.set(argIndex);
3546 }
3547 else {
3548 // If argIndex exceeds the number of data arguments we
3549 // don't issue a warning because that is just a cascade of warnings (and
3550 // they may have intended '%%' anyway). We don't want to continue processing
3551 // the format string after this point, however, as we will like just get
3552 // gibberish when trying to match arguments.
3553 keepGoing = false;
3554 }
3555
Richard Trieu03cf7b72011-10-28 00:41:25 +00003556 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3557 << StringRef(csStart, csLen),
3558 Loc, /*IsStringLocation*/true,
3559 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003560
3561 return keepGoing;
3562}
3563
Richard Trieu03cf7b72011-10-28 00:41:25 +00003564void
3565CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3566 const char *startSpec,
3567 unsigned specifierLen) {
3568 EmitFormatDiagnostic(
3569 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3570 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3571}
3572
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003573bool
3574CheckFormatHandler::CheckNumArgs(
3575 const analyze_format_string::FormatSpecifier &FS,
3576 const analyze_format_string::ConversionSpecifier &CS,
3577 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3578
3579 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003580 PartialDiagnostic PDiag = FS.usesPositionalArg()
3581 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3582 << (argIndex+1) << NumDataArgs)
3583 : S.PDiag(diag::warn_printf_insufficient_data_args);
3584 EmitFormatDiagnostic(
3585 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3586 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003587 return false;
3588 }
3589 return true;
3590}
3591
Richard Trieu03cf7b72011-10-28 00:41:25 +00003592template<typename Range>
3593void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3594 SourceLocation Loc,
3595 bool IsStringLocation,
3596 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003597 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003598 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003599 Loc, IsStringLocation, StringRange, FixIt);
3600}
3601
3602/// \brief If the format string is not within the funcion call, emit a note
3603/// so that the function call and string are in diagnostic messages.
3604///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003605/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003606/// call and only one diagnostic message will be produced. Otherwise, an
3607/// extra note will be emitted pointing to location of the format string.
3608///
3609/// \param ArgumentExpr the expression that is passed as the format string
3610/// argument in the function call. Used for getting locations when two
3611/// diagnostics are emitted.
3612///
3613/// \param PDiag the callee should already have provided any strings for the
3614/// diagnostic message. This function only adds locations and fixits
3615/// to diagnostics.
3616///
3617/// \param Loc primary location for diagnostic. If two diagnostics are
3618/// required, one will be at Loc and a new SourceLocation will be created for
3619/// the other one.
3620///
3621/// \param IsStringLocation if true, Loc points to the format string should be
3622/// used for the note. Otherwise, Loc points to the argument list and will
3623/// be used with PDiag.
3624///
3625/// \param StringRange some or all of the string to highlight. This is
3626/// templated so it can accept either a CharSourceRange or a SourceRange.
3627///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003628/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003629template<typename Range>
3630void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3631 const Expr *ArgumentExpr,
3632 PartialDiagnostic PDiag,
3633 SourceLocation Loc,
3634 bool IsStringLocation,
3635 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003636 ArrayRef<FixItHint> FixIt) {
3637 if (InFunctionCall) {
3638 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3639 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003640 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003641 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003642 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3643 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003644
3645 const Sema::SemaDiagnosticBuilder &Note =
3646 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3647 diag::note_format_string_defined);
3648
3649 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003650 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003651 }
3652}
3653
Ted Kremenek02087932010-07-16 02:11:22 +00003654//===--- CHECK: Printf format string checking ------------------------------===//
3655
3656namespace {
3657class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003658 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003659public:
3660 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3661 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003662 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003663 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003664 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003665 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003666 Sema::VariadicCallType CallType,
3667 llvm::SmallBitVector &CheckedVarArgs)
3668 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3669 numDataArgs, beg, hasVAListArg, Args,
3670 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3671 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003672 {}
3673
Craig Toppere14c0f82014-03-12 04:55:44 +00003674
Ted Kremenek02087932010-07-16 02:11:22 +00003675 bool HandleInvalidPrintfConversionSpecifier(
3676 const analyze_printf::PrintfSpecifier &FS,
3677 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003678 unsigned specifierLen) override;
3679
Ted Kremenek02087932010-07-16 02:11:22 +00003680 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3681 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003682 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003683 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3684 const char *StartSpecifier,
3685 unsigned SpecifierLen,
3686 const Expr *E);
3687
Ted Kremenek02087932010-07-16 02:11:22 +00003688 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3689 const char *startSpecifier, unsigned specifierLen);
3690 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3691 const analyze_printf::OptionalAmount &Amt,
3692 unsigned type,
3693 const char *startSpecifier, unsigned specifierLen);
3694 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3695 const analyze_printf::OptionalFlag &flag,
3696 const char *startSpecifier, unsigned specifierLen);
3697 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3698 const analyze_printf::OptionalFlag &ignoredFlag,
3699 const analyze_printf::OptionalFlag &flag,
3700 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003701 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003702 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003703
3704 void HandleEmptyObjCModifierFlag(const char *startFlag,
3705 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003706
Ted Kremenek2b417712015-07-02 05:39:16 +00003707 void HandleInvalidObjCModifierFlag(const char *startFlag,
3708 unsigned flagLen) override;
3709
3710 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3711 const char *flagsEnd,
3712 const char *conversionPosition)
3713 override;
3714};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003715}
Ted Kremenek02087932010-07-16 02:11:22 +00003716
3717bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3718 const analyze_printf::PrintfSpecifier &FS,
3719 const char *startSpecifier,
3720 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003721 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003722 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003723
Ted Kremenekce815422010-07-19 21:25:57 +00003724 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3725 getLocationOfByte(CS.getStart()),
3726 startSpecifier, specifierLen,
3727 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003728}
3729
Ted Kremenek02087932010-07-16 02:11:22 +00003730bool CheckPrintfHandler::HandleAmount(
3731 const analyze_format_string::OptionalAmount &Amt,
3732 unsigned k, const char *startSpecifier,
3733 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003734
3735 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003736 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003737 unsigned argIndex = Amt.getArgIndex();
3738 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003739 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3740 << k,
3741 getLocationOfByte(Amt.getStart()),
3742 /*IsStringLocation*/true,
3743 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003744 // Don't do any more checking. We will just emit
3745 // spurious errors.
3746 return false;
3747 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003748
Ted Kremenek5739de72010-01-29 01:06:55 +00003749 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003750 // Although not in conformance with C99, we also allow the argument to be
3751 // an 'unsigned int' as that is a reasonably safe case. GCC also
3752 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003753 CoveredArgs.set(argIndex);
3754 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003755 if (!Arg)
3756 return false;
3757
Ted Kremenek5739de72010-01-29 01:06:55 +00003758 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003759
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003760 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3761 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003762
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003763 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003764 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003765 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003766 << T << Arg->getSourceRange(),
3767 getLocationOfByte(Amt.getStart()),
3768 /*IsStringLocation*/true,
3769 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003770 // Don't do any more checking. We will just emit
3771 // spurious errors.
3772 return false;
3773 }
3774 }
3775 }
3776 return true;
3777}
Ted Kremenek5739de72010-01-29 01:06:55 +00003778
Tom Careb49ec692010-06-17 19:00:27 +00003779void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003780 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003781 const analyze_printf::OptionalAmount &Amt,
3782 unsigned type,
3783 const char *startSpecifier,
3784 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003785 const analyze_printf::PrintfConversionSpecifier &CS =
3786 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003787
Richard Trieu03cf7b72011-10-28 00:41:25 +00003788 FixItHint fixit =
3789 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3790 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3791 Amt.getConstantLength()))
3792 : FixItHint();
3793
3794 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3795 << type << CS.toString(),
3796 getLocationOfByte(Amt.getStart()),
3797 /*IsStringLocation*/true,
3798 getSpecifierRange(startSpecifier, specifierLen),
3799 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003800}
3801
Ted Kremenek02087932010-07-16 02:11:22 +00003802void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003803 const analyze_printf::OptionalFlag &flag,
3804 const char *startSpecifier,
3805 unsigned specifierLen) {
3806 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003807 const analyze_printf::PrintfConversionSpecifier &CS =
3808 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003809 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3810 << flag.toString() << CS.toString(),
3811 getLocationOfByte(flag.getPosition()),
3812 /*IsStringLocation*/true,
3813 getSpecifierRange(startSpecifier, specifierLen),
3814 FixItHint::CreateRemoval(
3815 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003816}
3817
3818void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003819 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003820 const analyze_printf::OptionalFlag &ignoredFlag,
3821 const analyze_printf::OptionalFlag &flag,
3822 const char *startSpecifier,
3823 unsigned specifierLen) {
3824 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003825 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3826 << ignoredFlag.toString() << flag.toString(),
3827 getLocationOfByte(ignoredFlag.getPosition()),
3828 /*IsStringLocation*/true,
3829 getSpecifierRange(startSpecifier, specifierLen),
3830 FixItHint::CreateRemoval(
3831 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003832}
3833
Ted Kremenek2b417712015-07-02 05:39:16 +00003834// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3835// bool IsStringLocation, Range StringRange,
3836// ArrayRef<FixItHint> Fixit = None);
3837
3838void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3839 unsigned flagLen) {
3840 // Warn about an empty flag.
3841 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3842 getLocationOfByte(startFlag),
3843 /*IsStringLocation*/true,
3844 getSpecifierRange(startFlag, flagLen));
3845}
3846
3847void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3848 unsigned flagLen) {
3849 // Warn about an invalid flag.
3850 auto Range = getSpecifierRange(startFlag, flagLen);
3851 StringRef flag(startFlag, flagLen);
3852 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3853 getLocationOfByte(startFlag),
3854 /*IsStringLocation*/true,
3855 Range, FixItHint::CreateRemoval(Range));
3856}
3857
3858void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3859 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3860 // Warn about using '[...]' without a '@' conversion.
3861 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3862 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3863 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3864 getLocationOfByte(conversionPosition),
3865 /*IsStringLocation*/true,
3866 Range, FixItHint::CreateRemoval(Range));
3867}
3868
Richard Smith55ce3522012-06-25 20:30:08 +00003869// Determines if the specified is a C++ class or struct containing
3870// a member with the specified name and kind (e.g. a CXXMethodDecl named
3871// "c_str()").
3872template<typename MemberKind>
3873static llvm::SmallPtrSet<MemberKind*, 1>
3874CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3875 const RecordType *RT = Ty->getAs<RecordType>();
3876 llvm::SmallPtrSet<MemberKind*, 1> Results;
3877
3878 if (!RT)
3879 return Results;
3880 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003881 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003882 return Results;
3883
Alp Tokerb6cc5922014-05-03 03:45:55 +00003884 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003885 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003886 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003887
3888 // We just need to include all members of the right kind turned up by the
3889 // filter, at this point.
3890 if (S.LookupQualifiedName(R, RT->getDecl()))
3891 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3892 NamedDecl *decl = (*I)->getUnderlyingDecl();
3893 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3894 Results.insert(FK);
3895 }
3896 return Results;
3897}
3898
Richard Smith2868a732014-02-28 01:36:39 +00003899/// Check if we could call '.c_str()' on an object.
3900///
3901/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3902/// allow the call, or if it would be ambiguous).
3903bool Sema::hasCStrMethod(const Expr *E) {
3904 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3905 MethodSet Results =
3906 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3907 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3908 MI != ME; ++MI)
3909 if ((*MI)->getMinRequiredArguments() == 0)
3910 return true;
3911 return false;
3912}
3913
Richard Smith55ce3522012-06-25 20:30:08 +00003914// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003915// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003916// Returns true when a c_str() conversion method is found.
3917bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003918 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003919 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3920
3921 MethodSet Results =
3922 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3923
3924 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3925 MI != ME; ++MI) {
3926 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003927 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003928 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003929 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003930 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003931 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3932 << "c_str()"
3933 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3934 return true;
3935 }
3936 }
3937
3938 return false;
3939}
3940
Ted Kremenekab278de2010-01-28 23:39:18 +00003941bool
Ted Kremenek02087932010-07-16 02:11:22 +00003942CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003943 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003944 const char *startSpecifier,
3945 unsigned specifierLen) {
3946
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003947 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003948 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003949 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003950
Ted Kremenek6cd69422010-07-19 22:01:06 +00003951 if (FS.consumesDataArgument()) {
3952 if (atFirstArg) {
3953 atFirstArg = false;
3954 usesPositionalArgs = FS.usesPositionalArg();
3955 }
3956 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003957 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3958 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003959 return false;
3960 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003961 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003962
Ted Kremenekd1668192010-02-27 01:41:03 +00003963 // First check if the field width, precision, and conversion specifier
3964 // have matching data arguments.
3965 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3966 startSpecifier, specifierLen)) {
3967 return false;
3968 }
3969
3970 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3971 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003972 return false;
3973 }
3974
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003975 if (!CS.consumesDataArgument()) {
3976 // FIXME: Technically specifying a precision or field width here
3977 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003978 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003979 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003980
Ted Kremenek4a49d982010-02-26 19:18:41 +00003981 // Consume the argument.
3982 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003983 if (argIndex < NumDataArgs) {
3984 // The check to see if the argIndex is valid will come later.
3985 // We set the bit here because we may exit early from this
3986 // function if we encounter some other error.
3987 CoveredArgs.set(argIndex);
3988 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003989
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003990 // FreeBSD kernel extensions.
3991 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3992 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3993 // We need at least two arguments.
3994 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3995 return false;
3996
3997 // Claim the second argument.
3998 CoveredArgs.set(argIndex + 1);
3999
4000 // Type check the first argument (int for %b, pointer for %D)
4001 const Expr *Ex = getDataArg(argIndex);
4002 const analyze_printf::ArgType &AT =
4003 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4004 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4005 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4006 EmitFormatDiagnostic(
4007 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4008 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4009 << false << Ex->getSourceRange(),
4010 Ex->getLocStart(), /*IsStringLocation*/false,
4011 getSpecifierRange(startSpecifier, specifierLen));
4012
4013 // Type check the second argument (char * for both %b and %D)
4014 Ex = getDataArg(argIndex + 1);
4015 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4016 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4017 EmitFormatDiagnostic(
4018 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4019 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4020 << false << Ex->getSourceRange(),
4021 Ex->getLocStart(), /*IsStringLocation*/false,
4022 getSpecifierRange(startSpecifier, specifierLen));
4023
4024 return true;
4025 }
4026
Ted Kremenek4a49d982010-02-26 19:18:41 +00004027 // Check for using an Objective-C specific conversion specifier
4028 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004029 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004030 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4031 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004032 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004033
Tom Careb49ec692010-06-17 19:00:27 +00004034 // Check for invalid use of field width
4035 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004036 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004037 startSpecifier, specifierLen);
4038 }
4039
4040 // Check for invalid use of precision
4041 if (!FS.hasValidPrecision()) {
4042 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4043 startSpecifier, specifierLen);
4044 }
4045
4046 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004047 if (!FS.hasValidThousandsGroupingPrefix())
4048 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004049 if (!FS.hasValidLeadingZeros())
4050 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4051 if (!FS.hasValidPlusPrefix())
4052 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004053 if (!FS.hasValidSpacePrefix())
4054 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004055 if (!FS.hasValidAlternativeForm())
4056 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4057 if (!FS.hasValidLeftJustified())
4058 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4059
4060 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004061 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4062 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4063 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004064 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4065 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4066 startSpecifier, specifierLen);
4067
4068 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004069 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004070 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4071 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004072 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004073 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004074 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004075 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4076 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004077
Jordan Rose92303592012-09-08 04:00:03 +00004078 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4079 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4080
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004081 // The remaining checks depend on the data arguments.
4082 if (HasVAListArg)
4083 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004084
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004085 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004086 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004087
Jordan Rose58bbe422012-07-19 18:10:08 +00004088 const Expr *Arg = getDataArg(argIndex);
4089 if (!Arg)
4090 return true;
4091
4092 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004093}
4094
Jordan Roseaee34382012-09-05 22:56:26 +00004095static bool requiresParensToAddCast(const Expr *E) {
4096 // FIXME: We should have a general way to reason about operator
4097 // precedence and whether parens are actually needed here.
4098 // Take care of a few common cases where they aren't.
4099 const Expr *Inside = E->IgnoreImpCasts();
4100 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4101 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4102
4103 switch (Inside->getStmtClass()) {
4104 case Stmt::ArraySubscriptExprClass:
4105 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004106 case Stmt::CharacterLiteralClass:
4107 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004108 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004109 case Stmt::FloatingLiteralClass:
4110 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004111 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004112 case Stmt::ObjCArrayLiteralClass:
4113 case Stmt::ObjCBoolLiteralExprClass:
4114 case Stmt::ObjCBoxedExprClass:
4115 case Stmt::ObjCDictionaryLiteralClass:
4116 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004117 case Stmt::ObjCIvarRefExprClass:
4118 case Stmt::ObjCMessageExprClass:
4119 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004120 case Stmt::ObjCStringLiteralClass:
4121 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004122 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004123 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004124 case Stmt::UnaryOperatorClass:
4125 return false;
4126 default:
4127 return true;
4128 }
4129}
4130
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004131static std::pair<QualType, StringRef>
4132shouldNotPrintDirectly(const ASTContext &Context,
4133 QualType IntendedTy,
4134 const Expr *E) {
4135 // Use a 'while' to peel off layers of typedefs.
4136 QualType TyTy = IntendedTy;
4137 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4138 StringRef Name = UserTy->getDecl()->getName();
4139 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4140 .Case("NSInteger", Context.LongTy)
4141 .Case("NSUInteger", Context.UnsignedLongTy)
4142 .Case("SInt32", Context.IntTy)
4143 .Case("UInt32", Context.UnsignedIntTy)
4144 .Default(QualType());
4145
4146 if (!CastTy.isNull())
4147 return std::make_pair(CastTy, Name);
4148
4149 TyTy = UserTy->desugar();
4150 }
4151
4152 // Strip parens if necessary.
4153 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4154 return shouldNotPrintDirectly(Context,
4155 PE->getSubExpr()->getType(),
4156 PE->getSubExpr());
4157
4158 // If this is a conditional expression, then its result type is constructed
4159 // via usual arithmetic conversions and thus there might be no necessary
4160 // typedef sugar there. Recurse to operands to check for NSInteger &
4161 // Co. usage condition.
4162 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4163 QualType TrueTy, FalseTy;
4164 StringRef TrueName, FalseName;
4165
4166 std::tie(TrueTy, TrueName) =
4167 shouldNotPrintDirectly(Context,
4168 CO->getTrueExpr()->getType(),
4169 CO->getTrueExpr());
4170 std::tie(FalseTy, FalseName) =
4171 shouldNotPrintDirectly(Context,
4172 CO->getFalseExpr()->getType(),
4173 CO->getFalseExpr());
4174
4175 if (TrueTy == FalseTy)
4176 return std::make_pair(TrueTy, TrueName);
4177 else if (TrueTy.isNull())
4178 return std::make_pair(FalseTy, FalseName);
4179 else if (FalseTy.isNull())
4180 return std::make_pair(TrueTy, TrueName);
4181 }
4182
4183 return std::make_pair(QualType(), StringRef());
4184}
4185
Richard Smith55ce3522012-06-25 20:30:08 +00004186bool
4187CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4188 const char *StartSpecifier,
4189 unsigned SpecifierLen,
4190 const Expr *E) {
4191 using namespace analyze_format_string;
4192 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004193 // Now type check the data expression that matches the
4194 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004195 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4196 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004197 if (!AT.isValid())
4198 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004199
Jordan Rose598ec092012-12-05 18:44:40 +00004200 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004201 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4202 ExprTy = TET->getUnderlyingExpr()->getType();
4203 }
4204
Seth Cantrellb4802962015-03-04 03:12:10 +00004205 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4206
4207 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004208 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004209 }
Jordan Rose98709982012-06-04 22:48:57 +00004210
Jordan Rose22b74712012-09-05 22:56:19 +00004211 // Look through argument promotions for our error message's reported type.
4212 // This includes the integral and floating promotions, but excludes array
4213 // and function pointer decay; seeing that an argument intended to be a
4214 // string has type 'char [6]' is probably more confusing than 'char *'.
4215 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4216 if (ICE->getCastKind() == CK_IntegralCast ||
4217 ICE->getCastKind() == CK_FloatingCast) {
4218 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004219 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004220
4221 // Check if we didn't match because of an implicit cast from a 'char'
4222 // or 'short' to an 'int'. This is done because printf is a varargs
4223 // function.
4224 if (ICE->getType() == S.Context.IntTy ||
4225 ICE->getType() == S.Context.UnsignedIntTy) {
4226 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004227 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004228 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004229 }
Jordan Rose98709982012-06-04 22:48:57 +00004230 }
Jordan Rose598ec092012-12-05 18:44:40 +00004231 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4232 // Special case for 'a', which has type 'int' in C.
4233 // Note, however, that we do /not/ want to treat multibyte constants like
4234 // 'MooV' as characters! This form is deprecated but still exists.
4235 if (ExprTy == S.Context.IntTy)
4236 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4237 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004238 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004239
Jordan Rosebc53ed12014-05-31 04:12:14 +00004240 // Look through enums to their underlying type.
4241 bool IsEnum = false;
4242 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4243 ExprTy = EnumTy->getDecl()->getIntegerType();
4244 IsEnum = true;
4245 }
4246
Jordan Rose0e5badd2012-12-05 18:44:49 +00004247 // %C in an Objective-C context prints a unichar, not a wchar_t.
4248 // If the argument is an integer of some kind, believe the %C and suggest
4249 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004250 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004251 if (ObjCContext &&
4252 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4253 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4254 !ExprTy->isCharType()) {
4255 // 'unichar' is defined as a typedef of unsigned short, but we should
4256 // prefer using the typedef if it is visible.
4257 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004258
4259 // While we are here, check if the value is an IntegerLiteral that happens
4260 // to be within the valid range.
4261 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4262 const llvm::APInt &V = IL->getValue();
4263 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4264 return true;
4265 }
4266
Jordan Rose0e5badd2012-12-05 18:44:49 +00004267 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4268 Sema::LookupOrdinaryName);
4269 if (S.LookupName(Result, S.getCurScope())) {
4270 NamedDecl *ND = Result.getFoundDecl();
4271 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4272 if (TD->getUnderlyingType() == IntendedTy)
4273 IntendedTy = S.Context.getTypedefType(TD);
4274 }
4275 }
4276 }
4277
4278 // Special-case some of Darwin's platform-independence types by suggesting
4279 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004280 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004281 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004282 QualType CastTy;
4283 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4284 if (!CastTy.isNull()) {
4285 IntendedTy = CastTy;
4286 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004287 }
4288 }
4289
Jordan Rose22b74712012-09-05 22:56:19 +00004290 // We may be able to offer a FixItHint if it is a supported type.
4291 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004292 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004293 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004294
Jordan Rose22b74712012-09-05 22:56:19 +00004295 if (success) {
4296 // Get the fix string from the fixed format specifier
4297 SmallString<16> buf;
4298 llvm::raw_svector_ostream os(buf);
4299 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004300
Jordan Roseaee34382012-09-05 22:56:26 +00004301 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4302
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004303 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004304 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4305 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4306 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4307 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004308 // In this case, the specifier is wrong and should be changed to match
4309 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004310 EmitFormatDiagnostic(S.PDiag(diag)
4311 << AT.getRepresentativeTypeName(S.Context)
4312 << IntendedTy << IsEnum << E->getSourceRange(),
4313 E->getLocStart(),
4314 /*IsStringLocation*/ false, SpecRange,
4315 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004316
4317 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004318 // The canonical type for formatting this value is different from the
4319 // actual type of the expression. (This occurs, for example, with Darwin's
4320 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4321 // should be printed as 'long' for 64-bit compatibility.)
4322 // Rather than emitting a normal format/argument mismatch, we want to
4323 // add a cast to the recommended type (and correct the format string
4324 // if necessary).
4325 SmallString<16> CastBuf;
4326 llvm::raw_svector_ostream CastFix(CastBuf);
4327 CastFix << "(";
4328 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4329 CastFix << ")";
4330
4331 SmallVector<FixItHint,4> Hints;
4332 if (!AT.matchesType(S.Context, IntendedTy))
4333 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4334
4335 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4336 // If there's already a cast present, just replace it.
4337 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4338 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4339
4340 } else if (!requiresParensToAddCast(E)) {
4341 // If the expression has high enough precedence,
4342 // just write the C-style cast.
4343 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4344 CastFix.str()));
4345 } else {
4346 // Otherwise, add parens around the expression as well as the cast.
4347 CastFix << "(";
4348 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4349 CastFix.str()));
4350
Alp Tokerb6cc5922014-05-03 03:45:55 +00004351 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004352 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4353 }
4354
Jordan Rose0e5badd2012-12-05 18:44:49 +00004355 if (ShouldNotPrintDirectly) {
4356 // The expression has a type that should not be printed directly.
4357 // We extract the name from the typedef because we don't want to show
4358 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004359 StringRef Name;
4360 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4361 Name = TypedefTy->getDecl()->getName();
4362 else
4363 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004364 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004365 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004366 << E->getSourceRange(),
4367 E->getLocStart(), /*IsStringLocation=*/false,
4368 SpecRange, Hints);
4369 } else {
4370 // In this case, the expression could be printed using a different
4371 // specifier, but we've decided that the specifier is probably correct
4372 // and we should cast instead. Just use the normal warning message.
4373 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004374 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4375 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004376 << E->getSourceRange(),
4377 E->getLocStart(), /*IsStringLocation*/false,
4378 SpecRange, Hints);
4379 }
Jordan Roseaee34382012-09-05 22:56:26 +00004380 }
Jordan Rose22b74712012-09-05 22:56:19 +00004381 } else {
4382 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4383 SpecifierLen);
4384 // Since the warning for passing non-POD types to variadic functions
4385 // was deferred until now, we emit a warning for non-POD
4386 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004387 switch (S.isValidVarArgType(ExprTy)) {
4388 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004389 case Sema::VAK_ValidInCXX11: {
4390 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4391 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4392 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4393 }
Richard Smithd7293d72013-08-05 18:49:43 +00004394
Seth Cantrellb4802962015-03-04 03:12:10 +00004395 EmitFormatDiagnostic(
4396 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4397 << IsEnum << CSR << E->getSourceRange(),
4398 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4399 break;
4400 }
Richard Smithd7293d72013-08-05 18:49:43 +00004401 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004402 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004403 EmitFormatDiagnostic(
4404 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004405 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004406 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004407 << CallType
4408 << AT.getRepresentativeTypeName(S.Context)
4409 << CSR
4410 << E->getSourceRange(),
4411 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004412 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004413 break;
4414
4415 case Sema::VAK_Invalid:
4416 if (ExprTy->isObjCObjectType())
4417 EmitFormatDiagnostic(
4418 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4419 << S.getLangOpts().CPlusPlus11
4420 << ExprTy
4421 << CallType
4422 << AT.getRepresentativeTypeName(S.Context)
4423 << CSR
4424 << E->getSourceRange(),
4425 E->getLocStart(), /*IsStringLocation*/false, CSR);
4426 else
4427 // FIXME: If this is an initializer list, suggest removing the braces
4428 // or inserting a cast to the target type.
4429 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4430 << isa<InitListExpr>(E) << ExprTy << CallType
4431 << AT.getRepresentativeTypeName(S.Context)
4432 << E->getSourceRange();
4433 break;
4434 }
4435
4436 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4437 "format string specifier index out of range");
4438 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004439 }
4440
Ted Kremenekab278de2010-01-28 23:39:18 +00004441 return true;
4442}
4443
Ted Kremenek02087932010-07-16 02:11:22 +00004444//===--- CHECK: Scanf format string checking ------------------------------===//
4445
4446namespace {
4447class CheckScanfHandler : public CheckFormatHandler {
4448public:
4449 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4450 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004451 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004452 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004453 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004454 Sema::VariadicCallType CallType,
4455 llvm::SmallBitVector &CheckedVarArgs)
4456 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4457 numDataArgs, beg, hasVAListArg,
4458 Args, formatIdx, inFunctionCall, CallType,
4459 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004460 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004461
4462 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4463 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004464 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004465
4466 bool HandleInvalidScanfConversionSpecifier(
4467 const analyze_scanf::ScanfSpecifier &FS,
4468 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004469 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004470
Craig Toppere14c0f82014-03-12 04:55:44 +00004471 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004472};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004473}
Ted Kremenekab278de2010-01-28 23:39:18 +00004474
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004475void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4476 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004477 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4478 getLocationOfByte(end), /*IsStringLocation*/true,
4479 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004480}
4481
Ted Kremenekce815422010-07-19 21:25:57 +00004482bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4483 const analyze_scanf::ScanfSpecifier &FS,
4484 const char *startSpecifier,
4485 unsigned specifierLen) {
4486
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004487 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004488 FS.getConversionSpecifier();
4489
4490 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4491 getLocationOfByte(CS.getStart()),
4492 startSpecifier, specifierLen,
4493 CS.getStart(), CS.getLength());
4494}
4495
Ted Kremenek02087932010-07-16 02:11:22 +00004496bool CheckScanfHandler::HandleScanfSpecifier(
4497 const analyze_scanf::ScanfSpecifier &FS,
4498 const char *startSpecifier,
4499 unsigned specifierLen) {
4500
4501 using namespace analyze_scanf;
4502 using namespace analyze_format_string;
4503
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004504 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004505
Ted Kremenek6cd69422010-07-19 22:01:06 +00004506 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4507 // be used to decide if we are using positional arguments consistently.
4508 if (FS.consumesDataArgument()) {
4509 if (atFirstArg) {
4510 atFirstArg = false;
4511 usesPositionalArgs = FS.usesPositionalArg();
4512 }
4513 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004514 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4515 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004516 return false;
4517 }
Ted Kremenek02087932010-07-16 02:11:22 +00004518 }
4519
4520 // Check if the field with is non-zero.
4521 const OptionalAmount &Amt = FS.getFieldWidth();
4522 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4523 if (Amt.getConstantAmount() == 0) {
4524 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4525 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004526 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4527 getLocationOfByte(Amt.getStart()),
4528 /*IsStringLocation*/true, R,
4529 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004530 }
4531 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004532
Ted Kremenek02087932010-07-16 02:11:22 +00004533 if (!FS.consumesDataArgument()) {
4534 // FIXME: Technically specifying a precision or field width here
4535 // makes no sense. Worth issuing a warning at some point.
4536 return true;
4537 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004538
Ted Kremenek02087932010-07-16 02:11:22 +00004539 // Consume the argument.
4540 unsigned argIndex = FS.getArgIndex();
4541 if (argIndex < NumDataArgs) {
4542 // The check to see if the argIndex is valid will come later.
4543 // We set the bit here because we may exit early from this
4544 // function if we encounter some other error.
4545 CoveredArgs.set(argIndex);
4546 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004547
Ted Kremenek4407ea42010-07-20 20:04:47 +00004548 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004549 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004550 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4551 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004552 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004553 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004554 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004555 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4556 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004557
Jordan Rose92303592012-09-08 04:00:03 +00004558 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4559 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4560
Ted Kremenek02087932010-07-16 02:11:22 +00004561 // The remaining checks depend on the data arguments.
4562 if (HasVAListArg)
4563 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004564
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004565 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004566 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004567
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004568 // Check that the argument type matches the format specifier.
4569 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004570 if (!Ex)
4571 return true;
4572
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004573 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004574
4575 if (!AT.isValid()) {
4576 return true;
4577 }
4578
Seth Cantrellb4802962015-03-04 03:12:10 +00004579 analyze_format_string::ArgType::MatchKind match =
4580 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004581 if (match == analyze_format_string::ArgType::Match) {
4582 return true;
4583 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004584
Seth Cantrell79340072015-03-04 05:58:08 +00004585 ScanfSpecifier fixedFS = FS;
4586 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4587 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004588
Seth Cantrell79340072015-03-04 05:58:08 +00004589 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4590 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4591 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4592 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004593
Seth Cantrell79340072015-03-04 05:58:08 +00004594 if (success) {
4595 // Get the fix string from the fixed format specifier.
4596 SmallString<128> buf;
4597 llvm::raw_svector_ostream os(buf);
4598 fixedFS.toString(os);
4599
4600 EmitFormatDiagnostic(
4601 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4602 << Ex->getType() << false << Ex->getSourceRange(),
4603 Ex->getLocStart(),
4604 /*IsStringLocation*/ false,
4605 getSpecifierRange(startSpecifier, specifierLen),
4606 FixItHint::CreateReplacement(
4607 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4608 } else {
4609 EmitFormatDiagnostic(S.PDiag(diag)
4610 << AT.getRepresentativeTypeName(S.Context)
4611 << Ex->getType() << false << Ex->getSourceRange(),
4612 Ex->getLocStart(),
4613 /*IsStringLocation*/ false,
4614 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004615 }
4616
Ted Kremenek02087932010-07-16 02:11:22 +00004617 return true;
4618}
4619
4620void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004621 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004622 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004623 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004624 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004625 bool inFunctionCall, VariadicCallType CallType,
4626 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004627
Ted Kremenekab278de2010-01-28 23:39:18 +00004628 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004629 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004630 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004631 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004632 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4633 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004634 return;
4635 }
Ted Kremenek02087932010-07-16 02:11:22 +00004636
Ted Kremenekab278de2010-01-28 23:39:18 +00004637 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004638 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004639 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004640 // Account for cases where the string literal is truncated in a declaration.
4641 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4642 assert(T && "String literal not of constant array type!");
4643 size_t TypeSize = T->getSize().getZExtValue();
4644 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004645 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004646
4647 // Emit a warning if the string literal is truncated and does not contain an
4648 // embedded null character.
4649 if (TypeSize <= StrRef.size() &&
4650 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4651 CheckFormatHandler::EmitFormatDiagnostic(
4652 *this, inFunctionCall, Args[format_idx],
4653 PDiag(diag::warn_printf_format_string_not_null_terminated),
4654 FExpr->getLocStart(),
4655 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4656 return;
4657 }
4658
Ted Kremenekab278de2010-01-28 23:39:18 +00004659 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004660 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004661 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004662 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004663 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4664 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004665 return;
4666 }
Ted Kremenek02087932010-07-16 02:11:22 +00004667
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004668 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004669 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004670 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004671 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004672 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004673 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004674
Hans Wennborg23926bd2011-12-15 10:25:47 +00004675 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004676 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004677 Context.getTargetInfo(),
4678 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004679 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004680 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004681 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004682 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004683 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004684
Hans Wennborg23926bd2011-12-15 10:25:47 +00004685 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004686 getLangOpts(),
4687 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004688 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004689 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004690}
4691
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004692bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4693 // Str - The format string. NOTE: this is NOT null-terminated!
4694 StringRef StrRef = FExpr->getString();
4695 const char *Str = StrRef.data();
4696 // Account for cases where the string literal is truncated in a declaration.
4697 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4698 assert(T && "String literal not of constant array type!");
4699 size_t TypeSize = T->getSize().getZExtValue();
4700 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4701 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4702 getLangOpts(),
4703 Context.getTargetInfo());
4704}
4705
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004706//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4707
4708// Returns the related absolute value function that is larger, of 0 if one
4709// does not exist.
4710static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4711 switch (AbsFunction) {
4712 default:
4713 return 0;
4714
4715 case Builtin::BI__builtin_abs:
4716 return Builtin::BI__builtin_labs;
4717 case Builtin::BI__builtin_labs:
4718 return Builtin::BI__builtin_llabs;
4719 case Builtin::BI__builtin_llabs:
4720 return 0;
4721
4722 case Builtin::BI__builtin_fabsf:
4723 return Builtin::BI__builtin_fabs;
4724 case Builtin::BI__builtin_fabs:
4725 return Builtin::BI__builtin_fabsl;
4726 case Builtin::BI__builtin_fabsl:
4727 return 0;
4728
4729 case Builtin::BI__builtin_cabsf:
4730 return Builtin::BI__builtin_cabs;
4731 case Builtin::BI__builtin_cabs:
4732 return Builtin::BI__builtin_cabsl;
4733 case Builtin::BI__builtin_cabsl:
4734 return 0;
4735
4736 case Builtin::BIabs:
4737 return Builtin::BIlabs;
4738 case Builtin::BIlabs:
4739 return Builtin::BIllabs;
4740 case Builtin::BIllabs:
4741 return 0;
4742
4743 case Builtin::BIfabsf:
4744 return Builtin::BIfabs;
4745 case Builtin::BIfabs:
4746 return Builtin::BIfabsl;
4747 case Builtin::BIfabsl:
4748 return 0;
4749
4750 case Builtin::BIcabsf:
4751 return Builtin::BIcabs;
4752 case Builtin::BIcabs:
4753 return Builtin::BIcabsl;
4754 case Builtin::BIcabsl:
4755 return 0;
4756 }
4757}
4758
4759// Returns the argument type of the absolute value function.
4760static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4761 unsigned AbsType) {
4762 if (AbsType == 0)
4763 return QualType();
4764
4765 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4766 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4767 if (Error != ASTContext::GE_None)
4768 return QualType();
4769
4770 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4771 if (!FT)
4772 return QualType();
4773
4774 if (FT->getNumParams() != 1)
4775 return QualType();
4776
4777 return FT->getParamType(0);
4778}
4779
4780// Returns the best absolute value function, or zero, based on type and
4781// current absolute value function.
4782static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4783 unsigned AbsFunctionKind) {
4784 unsigned BestKind = 0;
4785 uint64_t ArgSize = Context.getTypeSize(ArgType);
4786 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4787 Kind = getLargerAbsoluteValueFunction(Kind)) {
4788 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4789 if (Context.getTypeSize(ParamType) >= ArgSize) {
4790 if (BestKind == 0)
4791 BestKind = Kind;
4792 else if (Context.hasSameType(ParamType, ArgType)) {
4793 BestKind = Kind;
4794 break;
4795 }
4796 }
4797 }
4798 return BestKind;
4799}
4800
4801enum AbsoluteValueKind {
4802 AVK_Integer,
4803 AVK_Floating,
4804 AVK_Complex
4805};
4806
4807static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4808 if (T->isIntegralOrEnumerationType())
4809 return AVK_Integer;
4810 if (T->isRealFloatingType())
4811 return AVK_Floating;
4812 if (T->isAnyComplexType())
4813 return AVK_Complex;
4814
4815 llvm_unreachable("Type not integer, floating, or complex");
4816}
4817
4818// Changes the absolute value function to a different type. Preserves whether
4819// the function is a builtin.
4820static unsigned changeAbsFunction(unsigned AbsKind,
4821 AbsoluteValueKind ValueKind) {
4822 switch (ValueKind) {
4823 case AVK_Integer:
4824 switch (AbsKind) {
4825 default:
4826 return 0;
4827 case Builtin::BI__builtin_fabsf:
4828 case Builtin::BI__builtin_fabs:
4829 case Builtin::BI__builtin_fabsl:
4830 case Builtin::BI__builtin_cabsf:
4831 case Builtin::BI__builtin_cabs:
4832 case Builtin::BI__builtin_cabsl:
4833 return Builtin::BI__builtin_abs;
4834 case Builtin::BIfabsf:
4835 case Builtin::BIfabs:
4836 case Builtin::BIfabsl:
4837 case Builtin::BIcabsf:
4838 case Builtin::BIcabs:
4839 case Builtin::BIcabsl:
4840 return Builtin::BIabs;
4841 }
4842 case AVK_Floating:
4843 switch (AbsKind) {
4844 default:
4845 return 0;
4846 case Builtin::BI__builtin_abs:
4847 case Builtin::BI__builtin_labs:
4848 case Builtin::BI__builtin_llabs:
4849 case Builtin::BI__builtin_cabsf:
4850 case Builtin::BI__builtin_cabs:
4851 case Builtin::BI__builtin_cabsl:
4852 return Builtin::BI__builtin_fabsf;
4853 case Builtin::BIabs:
4854 case Builtin::BIlabs:
4855 case Builtin::BIllabs:
4856 case Builtin::BIcabsf:
4857 case Builtin::BIcabs:
4858 case Builtin::BIcabsl:
4859 return Builtin::BIfabsf;
4860 }
4861 case AVK_Complex:
4862 switch (AbsKind) {
4863 default:
4864 return 0;
4865 case Builtin::BI__builtin_abs:
4866 case Builtin::BI__builtin_labs:
4867 case Builtin::BI__builtin_llabs:
4868 case Builtin::BI__builtin_fabsf:
4869 case Builtin::BI__builtin_fabs:
4870 case Builtin::BI__builtin_fabsl:
4871 return Builtin::BI__builtin_cabsf;
4872 case Builtin::BIabs:
4873 case Builtin::BIlabs:
4874 case Builtin::BIllabs:
4875 case Builtin::BIfabsf:
4876 case Builtin::BIfabs:
4877 case Builtin::BIfabsl:
4878 return Builtin::BIcabsf;
4879 }
4880 }
4881 llvm_unreachable("Unable to convert function");
4882}
4883
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004884static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004885 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4886 if (!FnInfo)
4887 return 0;
4888
4889 switch (FDecl->getBuiltinID()) {
4890 default:
4891 return 0;
4892 case Builtin::BI__builtin_abs:
4893 case Builtin::BI__builtin_fabs:
4894 case Builtin::BI__builtin_fabsf:
4895 case Builtin::BI__builtin_fabsl:
4896 case Builtin::BI__builtin_labs:
4897 case Builtin::BI__builtin_llabs:
4898 case Builtin::BI__builtin_cabs:
4899 case Builtin::BI__builtin_cabsf:
4900 case Builtin::BI__builtin_cabsl:
4901 case Builtin::BIabs:
4902 case Builtin::BIlabs:
4903 case Builtin::BIllabs:
4904 case Builtin::BIfabs:
4905 case Builtin::BIfabsf:
4906 case Builtin::BIfabsl:
4907 case Builtin::BIcabs:
4908 case Builtin::BIcabsf:
4909 case Builtin::BIcabsl:
4910 return FDecl->getBuiltinID();
4911 }
4912 llvm_unreachable("Unknown Builtin type");
4913}
4914
4915// If the replacement is valid, emit a note with replacement function.
4916// Additionally, suggest including the proper header if not already included.
4917static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004918 unsigned AbsKind, QualType ArgType) {
4919 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004920 const char *HeaderName = nullptr;
4921 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004922 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4923 FunctionName = "std::abs";
4924 if (ArgType->isIntegralOrEnumerationType()) {
4925 HeaderName = "cstdlib";
4926 } else if (ArgType->isRealFloatingType()) {
4927 HeaderName = "cmath";
4928 } else {
4929 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004930 }
Richard Trieubeffb832014-04-15 23:47:53 +00004931
4932 // Lookup all std::abs
4933 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004934 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004935 R.suppressDiagnostics();
4936 S.LookupQualifiedName(R, Std);
4937
4938 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004939 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004940 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4941 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4942 } else {
4943 FDecl = dyn_cast<FunctionDecl>(I);
4944 }
4945 if (!FDecl)
4946 continue;
4947
4948 // Found std::abs(), check that they are the right ones.
4949 if (FDecl->getNumParams() != 1)
4950 continue;
4951
4952 // Check that the parameter type can handle the argument.
4953 QualType ParamType = FDecl->getParamDecl(0)->getType();
4954 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4955 S.Context.getTypeSize(ArgType) <=
4956 S.Context.getTypeSize(ParamType)) {
4957 // Found a function, don't need the header hint.
4958 EmitHeaderHint = false;
4959 break;
4960 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004961 }
Richard Trieubeffb832014-04-15 23:47:53 +00004962 }
4963 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00004964 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00004965 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4966
4967 if (HeaderName) {
4968 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4969 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4970 R.suppressDiagnostics();
4971 S.LookupName(R, S.getCurScope());
4972
4973 if (R.isSingleResult()) {
4974 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4975 if (FD && FD->getBuiltinID() == AbsKind) {
4976 EmitHeaderHint = false;
4977 } else {
4978 return;
4979 }
4980 } else if (!R.empty()) {
4981 return;
4982 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004983 }
4984 }
4985
4986 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004987 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004988
Richard Trieubeffb832014-04-15 23:47:53 +00004989 if (!HeaderName)
4990 return;
4991
4992 if (!EmitHeaderHint)
4993 return;
4994
Alp Toker5d96e0a2014-07-11 20:53:51 +00004995 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4996 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004997}
4998
4999static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5000 if (!FDecl)
5001 return false;
5002
5003 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5004 return false;
5005
5006 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5007
5008 while (ND && ND->isInlineNamespace()) {
5009 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005010 }
Richard Trieubeffb832014-04-15 23:47:53 +00005011
5012 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5013 return false;
5014
5015 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5016 return false;
5017
5018 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005019}
5020
5021// Warn when using the wrong abs() function.
5022void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5023 const FunctionDecl *FDecl,
5024 IdentifierInfo *FnInfo) {
5025 if (Call->getNumArgs() != 1)
5026 return;
5027
5028 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005029 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5030 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005031 return;
5032
5033 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5034 QualType ParamType = Call->getArg(0)->getType();
5035
Alp Toker5d96e0a2014-07-11 20:53:51 +00005036 // Unsigned types cannot be negative. Suggest removing the absolute value
5037 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005038 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005039 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005040 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005041 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5042 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005043 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005044 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5045 return;
5046 }
5047
Richard Trieubeffb832014-04-15 23:47:53 +00005048 // std::abs has overloads which prevent most of the absolute value problems
5049 // from occurring.
5050 if (IsStdAbs)
5051 return;
5052
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005053 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5054 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5055
5056 // The argument and parameter are the same kind. Check if they are the right
5057 // size.
5058 if (ArgValueKind == ParamValueKind) {
5059 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5060 return;
5061
5062 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5063 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5064 << FDecl << ArgType << ParamType;
5065
5066 if (NewAbsKind == 0)
5067 return;
5068
5069 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005070 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005071 return;
5072 }
5073
5074 // ArgValueKind != ParamValueKind
5075 // The wrong type of absolute value function was used. Attempt to find the
5076 // proper one.
5077 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5078 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5079 if (NewAbsKind == 0)
5080 return;
5081
5082 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5083 << FDecl << ParamValueKind << ArgValueKind;
5084
5085 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005086 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005087 return;
5088}
5089
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005090//===--- CHECK: Standard memory functions ---------------------------------===//
5091
Nico Weber0e6daef2013-12-26 23:38:39 +00005092/// \brief Takes the expression passed to the size_t parameter of functions
5093/// such as memcmp, strncat, etc and warns if it's a comparison.
5094///
5095/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5096static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5097 IdentifierInfo *FnName,
5098 SourceLocation FnLoc,
5099 SourceLocation RParenLoc) {
5100 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5101 if (!Size)
5102 return false;
5103
5104 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5105 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5106 return false;
5107
Nico Weber0e6daef2013-12-26 23:38:39 +00005108 SourceRange SizeRange = Size->getSourceRange();
5109 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5110 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005111 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005112 << FnName << FixItHint::CreateInsertion(
5113 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005114 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005115 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005116 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005117 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5118 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005119
5120 return true;
5121}
5122
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005123/// \brief Determine whether the given type is or contains a dynamic class type
5124/// (e.g., whether it has a vtable).
5125static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5126 bool &IsContained) {
5127 // Look through array types while ignoring qualifiers.
5128 const Type *Ty = T->getBaseElementTypeUnsafe();
5129 IsContained = false;
5130
5131 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5132 RD = RD ? RD->getDefinition() : nullptr;
5133 if (!RD)
5134 return nullptr;
5135
5136 if (RD->isDynamicClass())
5137 return RD;
5138
5139 // Check all the fields. If any bases were dynamic, the class is dynamic.
5140 // It's impossible for a class to transitively contain itself by value, so
5141 // infinite recursion is impossible.
5142 for (auto *FD : RD->fields()) {
5143 bool SubContained;
5144 if (const CXXRecordDecl *ContainedRD =
5145 getContainedDynamicClass(FD->getType(), SubContained)) {
5146 IsContained = true;
5147 return ContainedRD;
5148 }
5149 }
5150
5151 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005152}
5153
Chandler Carruth889ed862011-06-21 23:04:20 +00005154/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005155/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005156static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005157 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005158 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5159 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5160 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005161
Craig Topperc3ec1492014-05-26 06:22:03 +00005162 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005163}
5164
Chandler Carruth889ed862011-06-21 23:04:20 +00005165/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005166static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005167 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5168 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5169 if (SizeOf->getKind() == clang::UETT_SizeOf)
5170 return SizeOf->getTypeOfArgument();
5171
5172 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005173}
5174
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005175/// \brief Check for dangerous or invalid arguments to memset().
5176///
Chandler Carruthac687262011-06-03 06:23:57 +00005177/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005178/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5179/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005180///
5181/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005182void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005183 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005184 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005185 assert(BId != 0);
5186
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005187 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005188 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005189 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005190 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005191 return;
5192
Anna Zaks22122702012-01-17 00:37:07 +00005193 unsigned LastArg = (BId == Builtin::BImemset ||
5194 BId == Builtin::BIstrndup ? 1 : 2);
5195 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005196 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005197
Nico Weber0e6daef2013-12-26 23:38:39 +00005198 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5199 Call->getLocStart(), Call->getRParenLoc()))
5200 return;
5201
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005202 // We have special checking when the length is a sizeof expression.
5203 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5204 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5205 llvm::FoldingSetNodeID SizeOfArgID;
5206
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005207 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5208 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005209 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005210
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005211 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005212 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005213 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005214 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005215
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005216 // Never warn about void type pointers. This can be used to suppress
5217 // false positives.
5218 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005219 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005220
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005221 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5222 // actually comparing the expressions for equality. Because computing the
5223 // expression IDs can be expensive, we only do this if the diagnostic is
5224 // enabled.
5225 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005226 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5227 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005228 // We only compute IDs for expressions if the warning is enabled, and
5229 // cache the sizeof arg's ID.
5230 if (SizeOfArgID == llvm::FoldingSetNodeID())
5231 SizeOfArg->Profile(SizeOfArgID, Context, true);
5232 llvm::FoldingSetNodeID DestID;
5233 Dest->Profile(DestID, Context, true);
5234 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005235 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5236 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005237 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005238 StringRef ReadableName = FnName->getName();
5239
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005240 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005241 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005242 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005243 if (!PointeeTy->isIncompleteType() &&
5244 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005245 ActionIdx = 2; // If the pointee's size is sizeof(char),
5246 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005247
5248 // If the function is defined as a builtin macro, do not show macro
5249 // expansion.
5250 SourceLocation SL = SizeOfArg->getExprLoc();
5251 SourceRange DSR = Dest->getSourceRange();
5252 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005253 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005254
5255 if (SM.isMacroArgExpansion(SL)) {
5256 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5257 SL = SM.getSpellingLoc(SL);
5258 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5259 SM.getSpellingLoc(DSR.getEnd()));
5260 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5261 SM.getSpellingLoc(SSR.getEnd()));
5262 }
5263
Anna Zaksd08d9152012-05-30 23:14:52 +00005264 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005265 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005266 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005267 << PointeeTy
5268 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005269 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005270 << SSR);
5271 DiagRuntimeBehavior(SL, SizeOfArg,
5272 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5273 << ActionIdx
5274 << SSR);
5275
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005276 break;
5277 }
5278 }
5279
5280 // Also check for cases where the sizeof argument is the exact same
5281 // type as the memory argument, and where it points to a user-defined
5282 // record type.
5283 if (SizeOfArgTy != QualType()) {
5284 if (PointeeTy->isRecordType() &&
5285 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5286 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5287 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5288 << FnName << SizeOfArgTy << ArgIdx
5289 << PointeeTy << Dest->getSourceRange()
5290 << LenExpr->getSourceRange());
5291 break;
5292 }
Nico Weberc5e73862011-06-14 16:14:58 +00005293 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005294 } else if (DestTy->isArrayType()) {
5295 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005296 }
Nico Weberc5e73862011-06-14 16:14:58 +00005297
Nico Weberc44b35e2015-03-21 17:37:46 +00005298 if (PointeeTy == QualType())
5299 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005300
Nico Weberc44b35e2015-03-21 17:37:46 +00005301 // Always complain about dynamic classes.
5302 bool IsContained;
5303 if (const CXXRecordDecl *ContainedRD =
5304 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005305
Nico Weberc44b35e2015-03-21 17:37:46 +00005306 unsigned OperationType = 0;
5307 // "overwritten" if we're warning about the destination for any call
5308 // but memcmp; otherwise a verb appropriate to the call.
5309 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5310 if (BId == Builtin::BImemcpy)
5311 OperationType = 1;
5312 else if(BId == Builtin::BImemmove)
5313 OperationType = 2;
5314 else if (BId == Builtin::BImemcmp)
5315 OperationType = 3;
5316 }
5317
John McCall31168b02011-06-15 23:02:42 +00005318 DiagRuntimeBehavior(
5319 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005320 PDiag(diag::warn_dyn_class_memaccess)
5321 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5322 << FnName << IsContained << ContainedRD << OperationType
5323 << Call->getCallee()->getSourceRange());
5324 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5325 BId != Builtin::BImemset)
5326 DiagRuntimeBehavior(
5327 Dest->getExprLoc(), Dest,
5328 PDiag(diag::warn_arc_object_memaccess)
5329 << ArgIdx << FnName << PointeeTy
5330 << Call->getCallee()->getSourceRange());
5331 else
5332 continue;
5333
5334 DiagRuntimeBehavior(
5335 Dest->getExprLoc(), Dest,
5336 PDiag(diag::note_bad_memaccess_silence)
5337 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5338 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005339 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005340
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005341}
5342
Ted Kremenek6865f772011-08-18 20:55:45 +00005343// A little helper routine: ignore addition and subtraction of integer literals.
5344// This intentionally does not ignore all integer constant expressions because
5345// we don't want to remove sizeof().
5346static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5347 Ex = Ex->IgnoreParenCasts();
5348
5349 for (;;) {
5350 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5351 if (!BO || !BO->isAdditiveOp())
5352 break;
5353
5354 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5355 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5356
5357 if (isa<IntegerLiteral>(RHS))
5358 Ex = LHS;
5359 else if (isa<IntegerLiteral>(LHS))
5360 Ex = RHS;
5361 else
5362 break;
5363 }
5364
5365 return Ex;
5366}
5367
Anna Zaks13b08572012-08-08 21:42:23 +00005368static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5369 ASTContext &Context) {
5370 // Only handle constant-sized or VLAs, but not flexible members.
5371 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5372 // Only issue the FIXIT for arrays of size > 1.
5373 if (CAT->getSize().getSExtValue() <= 1)
5374 return false;
5375 } else if (!Ty->isVariableArrayType()) {
5376 return false;
5377 }
5378 return true;
5379}
5380
Ted Kremenek6865f772011-08-18 20:55:45 +00005381// Warn if the user has made the 'size' argument to strlcpy or strlcat
5382// be the size of the source, instead of the destination.
5383void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5384 IdentifierInfo *FnName) {
5385
5386 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005387 unsigned NumArgs = Call->getNumArgs();
5388 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005389 return;
5390
5391 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5392 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005393 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005394
5395 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5396 Call->getLocStart(), Call->getRParenLoc()))
5397 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005398
5399 // Look for 'strlcpy(dst, x, sizeof(x))'
5400 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5401 CompareWithSrc = Ex;
5402 else {
5403 // Look for 'strlcpy(dst, x, strlen(x))'
5404 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005405 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5406 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005407 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5408 }
5409 }
5410
5411 if (!CompareWithSrc)
5412 return;
5413
5414 // Determine if the argument to sizeof/strlen is equal to the source
5415 // argument. In principle there's all kinds of things you could do
5416 // here, for instance creating an == expression and evaluating it with
5417 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5418 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5419 if (!SrcArgDRE)
5420 return;
5421
5422 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5423 if (!CompareWithSrcDRE ||
5424 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5425 return;
5426
5427 const Expr *OriginalSizeArg = Call->getArg(2);
5428 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5429 << OriginalSizeArg->getSourceRange() << FnName;
5430
5431 // Output a FIXIT hint if the destination is an array (rather than a
5432 // pointer to an array). This could be enhanced to handle some
5433 // pointers if we know the actual size, like if DstArg is 'array+2'
5434 // we could say 'sizeof(array)-2'.
5435 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005436 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005437 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005438
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005439 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005440 llvm::raw_svector_ostream OS(sizeString);
5441 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005442 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005443 OS << ")";
5444
5445 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5446 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5447 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005448}
5449
Anna Zaks314cd092012-02-01 19:08:57 +00005450/// Check if two expressions refer to the same declaration.
5451static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5452 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5453 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5454 return D1->getDecl() == D2->getDecl();
5455 return false;
5456}
5457
5458static const Expr *getStrlenExprArg(const Expr *E) {
5459 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5460 const FunctionDecl *FD = CE->getDirectCallee();
5461 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005462 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005463 return CE->getArg(0)->IgnoreParenCasts();
5464 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005465 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005466}
5467
5468// Warn on anti-patterns as the 'size' argument to strncat.
5469// The correct size argument should look like following:
5470// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5471void Sema::CheckStrncatArguments(const CallExpr *CE,
5472 IdentifierInfo *FnName) {
5473 // Don't crash if the user has the wrong number of arguments.
5474 if (CE->getNumArgs() < 3)
5475 return;
5476 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5477 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5478 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5479
Nico Weber0e6daef2013-12-26 23:38:39 +00005480 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5481 CE->getRParenLoc()))
5482 return;
5483
Anna Zaks314cd092012-02-01 19:08:57 +00005484 // Identify common expressions, which are wrongly used as the size argument
5485 // to strncat and may lead to buffer overflows.
5486 unsigned PatternType = 0;
5487 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5488 // - sizeof(dst)
5489 if (referToTheSameDecl(SizeOfArg, DstArg))
5490 PatternType = 1;
5491 // - sizeof(src)
5492 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5493 PatternType = 2;
5494 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5495 if (BE->getOpcode() == BO_Sub) {
5496 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5497 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5498 // - sizeof(dst) - strlen(dst)
5499 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5500 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5501 PatternType = 1;
5502 // - sizeof(src) - (anything)
5503 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5504 PatternType = 2;
5505 }
5506 }
5507
5508 if (PatternType == 0)
5509 return;
5510
Anna Zaks5069aa32012-02-03 01:27:37 +00005511 // Generate the diagnostic.
5512 SourceLocation SL = LenArg->getLocStart();
5513 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005514 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005515
5516 // If the function is defined as a builtin macro, do not show macro expansion.
5517 if (SM.isMacroArgExpansion(SL)) {
5518 SL = SM.getSpellingLoc(SL);
5519 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5520 SM.getSpellingLoc(SR.getEnd()));
5521 }
5522
Anna Zaks13b08572012-08-08 21:42:23 +00005523 // Check if the destination is an array (rather than a pointer to an array).
5524 QualType DstTy = DstArg->getType();
5525 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5526 Context);
5527 if (!isKnownSizeArray) {
5528 if (PatternType == 1)
5529 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5530 else
5531 Diag(SL, diag::warn_strncat_src_size) << SR;
5532 return;
5533 }
5534
Anna Zaks314cd092012-02-01 19:08:57 +00005535 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005536 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005537 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005538 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005539
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005540 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005541 llvm::raw_svector_ostream OS(sizeString);
5542 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005543 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005544 OS << ") - ";
5545 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005546 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005547 OS << ") - 1";
5548
Anna Zaks5069aa32012-02-03 01:27:37 +00005549 Diag(SL, diag::note_strncat_wrong_size)
5550 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005551}
5552
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005553//===--- CHECK: Return Address of Stack Variable --------------------------===//
5554
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005555static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5556 Decl *ParentDecl);
5557static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5558 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005559
5560/// CheckReturnStackAddr - Check if a return statement returns the address
5561/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005562static void
5563CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5564 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005565
Craig Topperc3ec1492014-05-26 06:22:03 +00005566 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005567 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005568
5569 // Perform checking for returned stack addresses, local blocks,
5570 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005571 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005572 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005573 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005574 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005575 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005576 }
5577
Craig Topperc3ec1492014-05-26 06:22:03 +00005578 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005579 return; // Nothing suspicious was found.
5580
5581 SourceLocation diagLoc;
5582 SourceRange diagRange;
5583 if (refVars.empty()) {
5584 diagLoc = stackE->getLocStart();
5585 diagRange = stackE->getSourceRange();
5586 } else {
5587 // We followed through a reference variable. 'stackE' contains the
5588 // problematic expression but we will warn at the return statement pointing
5589 // at the reference variable. We will later display the "trail" of
5590 // reference variables using notes.
5591 diagLoc = refVars[0]->getLocStart();
5592 diagRange = refVars[0]->getSourceRange();
5593 }
5594
5595 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005596 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005597 : diag::warn_ret_stack_addr)
5598 << DR->getDecl()->getDeclName() << diagRange;
5599 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005600 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005601 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005602 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005603 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005604 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5605 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005606 << diagRange;
5607 }
5608
5609 // Display the "trail" of reference variables that we followed until we
5610 // found the problematic expression using notes.
5611 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5612 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5613 // If this var binds to another reference var, show the range of the next
5614 // var, otherwise the var binds to the problematic expression, in which case
5615 // show the range of the expression.
5616 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5617 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005618 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5619 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005620 }
5621}
5622
5623/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5624/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005625/// to a location on the stack, a local block, an address of a label, or a
5626/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005627/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005628/// encounter a subexpression that (1) clearly does not lead to one of the
5629/// above problematic expressions (2) is something we cannot determine leads to
5630/// a problematic expression based on such local checking.
5631///
5632/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5633/// the expression that they point to. Such variables are added to the
5634/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005635///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005636/// EvalAddr processes expressions that are pointers that are used as
5637/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005638/// At the base case of the recursion is a check for the above problematic
5639/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005640///
5641/// This implementation handles:
5642///
5643/// * pointer-to-pointer casts
5644/// * implicit conversions from array references to pointers
5645/// * taking the address of fields
5646/// * arbitrary interplay between "&" and "*" operators
5647/// * pointer arithmetic from an address of a stack variable
5648/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005649static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5650 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005651 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005652 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005653
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005654 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005655 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005656 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005657 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005658 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005659
Peter Collingbourne91147592011-04-15 00:35:48 +00005660 E = E->IgnoreParens();
5661
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005662 // Our "symbolic interpreter" is just a dispatch off the currently
5663 // viewed AST node. We then recursively traverse the AST by calling
5664 // EvalAddr and EvalVal appropriately.
5665 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005666 case Stmt::DeclRefExprClass: {
5667 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5668
Richard Smith40f08eb2014-01-30 22:05:38 +00005669 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005670 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005671 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005672
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005673 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5674 // If this is a reference variable, follow through to the expression that
5675 // it points to.
5676 if (V->hasLocalStorage() &&
5677 V->getType()->isReferenceType() && V->hasInit()) {
5678 // Add the reference variable to the "trail".
5679 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005680 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005681 }
5682
Craig Topperc3ec1492014-05-26 06:22:03 +00005683 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005684 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005685
Chris Lattner934edb22007-12-28 05:31:15 +00005686 case Stmt::UnaryOperatorClass: {
5687 // The only unary operator that make sense to handle here
5688 // is AddrOf. All others don't make sense as pointers.
5689 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005690
John McCalle3027922010-08-25 11:45:40 +00005691 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005692 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005693 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005694 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005695 }
Mike Stump11289f42009-09-09 15:08:12 +00005696
Chris Lattner934edb22007-12-28 05:31:15 +00005697 case Stmt::BinaryOperatorClass: {
5698 // Handle pointer arithmetic. All other binary operators are not valid
5699 // in this context.
5700 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005701 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005702
John McCalle3027922010-08-25 11:45:40 +00005703 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005704 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005705
Chris Lattner934edb22007-12-28 05:31:15 +00005706 Expr *Base = B->getLHS();
5707
5708 // Determine which argument is the real pointer base. It could be
5709 // the RHS argument instead of the LHS.
5710 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005711
Chris Lattner934edb22007-12-28 05:31:15 +00005712 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005713 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005714 }
Steve Naroff2752a172008-09-10 19:17:48 +00005715
Chris Lattner934edb22007-12-28 05:31:15 +00005716 // For conditional operators we need to see if either the LHS or RHS are
5717 // valid DeclRefExpr*s. If one of them is valid, we return it.
5718 case Stmt::ConditionalOperatorClass: {
5719 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005720
Chris Lattner934edb22007-12-28 05:31:15 +00005721 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005722 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5723 if (Expr *LHSExpr = C->getLHS()) {
5724 // In C++, we can have a throw-expression, which has 'void' type.
5725 if (!LHSExpr->getType()->isVoidType())
5726 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005727 return LHS;
5728 }
Chris Lattner934edb22007-12-28 05:31:15 +00005729
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005730 // In C++, we can have a throw-expression, which has 'void' type.
5731 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005732 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005733
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005734 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005735 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005736
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005737 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005738 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005739 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005740 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005741
5742 case Stmt::AddrLabelExprClass:
5743 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005744
John McCall28fc7092011-11-10 05:35:25 +00005745 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005746 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5747 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005748
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005749 // For casts, we need to handle conversions from arrays to
5750 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005751 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005752 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005753 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005754 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005755 case Stmt::CXXStaticCastExprClass:
5756 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005757 case Stmt::CXXConstCastExprClass:
5758 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005759 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5760 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005761 case CK_LValueToRValue:
5762 case CK_NoOp:
5763 case CK_BaseToDerived:
5764 case CK_DerivedToBase:
5765 case CK_UncheckedDerivedToBase:
5766 case CK_Dynamic:
5767 case CK_CPointerToObjCPointerCast:
5768 case CK_BlockPointerToObjCPointerCast:
5769 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005770 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005771
5772 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005773 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005774
Richard Trieudadefde2014-07-02 04:39:38 +00005775 case CK_BitCast:
5776 if (SubExpr->getType()->isAnyPointerType() ||
5777 SubExpr->getType()->isBlockPointerType() ||
5778 SubExpr->getType()->isObjCQualifiedIdType())
5779 return EvalAddr(SubExpr, refVars, ParentDecl);
5780 else
5781 return nullptr;
5782
Eli Friedman8195ad72012-02-23 23:04:32 +00005783 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005784 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005785 }
Chris Lattner934edb22007-12-28 05:31:15 +00005786 }
Mike Stump11289f42009-09-09 15:08:12 +00005787
Douglas Gregorfe314812011-06-21 17:03:29 +00005788 case Stmt::MaterializeTemporaryExprClass:
5789 if (Expr *Result = EvalAddr(
5790 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005791 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005792 return Result;
5793
5794 return E;
5795
Chris Lattner934edb22007-12-28 05:31:15 +00005796 // Everything else: we simply don't reason about them.
5797 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005798 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005799 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005800}
Mike Stump11289f42009-09-09 15:08:12 +00005801
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005802
5803/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5804/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005805static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5806 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005807do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005808 // We should only be called for evaluating non-pointer expressions, or
5809 // expressions with a pointer type that are not used as references but instead
5810 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005811
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005812 // Our "symbolic interpreter" is just a dispatch off the currently
5813 // viewed AST node. We then recursively traverse the AST by calling
5814 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005815
5816 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005817 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005818 case Stmt::ImplicitCastExprClass: {
5819 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005820 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005821 E = IE->getSubExpr();
5822 continue;
5823 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005825 }
5826
John McCall28fc7092011-11-10 05:35:25 +00005827 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005828 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005829
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005830 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005831 // When we hit a DeclRefExpr we are looking at code that refers to a
5832 // variable's name. If it's not a reference variable we check if it has
5833 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005834 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005835
Richard Smith40f08eb2014-01-30 22:05:38 +00005836 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005837 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005838 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005839
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005840 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5841 // Check if it refers to itself, e.g. "int& i = i;".
5842 if (V == ParentDecl)
5843 return DR;
5844
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005845 if (V->hasLocalStorage()) {
5846 if (!V->getType()->isReferenceType())
5847 return DR;
5848
5849 // Reference variable, follow through to the expression that
5850 // it points to.
5851 if (V->hasInit()) {
5852 // Add the reference variable to the "trail".
5853 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005854 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005855 }
5856 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005857 }
Mike Stump11289f42009-09-09 15:08:12 +00005858
Craig Topperc3ec1492014-05-26 06:22:03 +00005859 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005860 }
Mike Stump11289f42009-09-09 15:08:12 +00005861
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005862 case Stmt::UnaryOperatorClass: {
5863 // The only unary operator that make sense to handle here
5864 // is Deref. All others don't resolve to a "name." This includes
5865 // handling all sorts of rvalues passed to a unary operator.
5866 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005867
John McCalle3027922010-08-25 11:45:40 +00005868 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005869 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005870
Craig Topperc3ec1492014-05-26 06:22:03 +00005871 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005872 }
Mike Stump11289f42009-09-09 15:08:12 +00005873
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005874 case Stmt::ArraySubscriptExprClass: {
5875 // Array subscripts are potential references to data on the stack. We
5876 // retrieve the DeclRefExpr* for the array variable if it indeed
5877 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005878 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005879 }
Mike Stump11289f42009-09-09 15:08:12 +00005880
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005881 case Stmt::OMPArraySectionExprClass: {
5882 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5883 ParentDecl);
5884 }
5885
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005886 case Stmt::ConditionalOperatorClass: {
5887 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005888 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005889 ConditionalOperator *C = cast<ConditionalOperator>(E);
5890
Anders Carlsson801c5c72007-11-30 19:04:31 +00005891 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005892 if (Expr *LHSExpr = C->getLHS()) {
5893 // In C++, we can have a throw-expression, which has 'void' type.
5894 if (!LHSExpr->getType()->isVoidType())
5895 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5896 return LHS;
5897 }
5898
5899 // In C++, we can have a throw-expression, which has 'void' type.
5900 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005901 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005902
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005903 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005904 }
Mike Stump11289f42009-09-09 15:08:12 +00005905
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005906 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005907 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005908 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005909
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005910 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005911 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005912 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005913
5914 // Check whether the member type is itself a reference, in which case
5915 // we're not going to refer to the member, but to what the member refers to.
5916 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005917 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005918
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005919 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005920 }
Mike Stump11289f42009-09-09 15:08:12 +00005921
Douglas Gregorfe314812011-06-21 17:03:29 +00005922 case Stmt::MaterializeTemporaryExprClass:
5923 if (Expr *Result = EvalVal(
5924 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005925 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005926 return Result;
5927
5928 return E;
5929
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005930 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005931 // Check that we don't return or take the address of a reference to a
5932 // temporary. This is only useful in C++.
5933 if (!E->isTypeDependent() && E->isRValue())
5934 return E;
5935
5936 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005937 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005938 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005939} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005940}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005941
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005942void
5943Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5944 SourceLocation ReturnLoc,
5945 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005946 const AttrVec *Attrs,
5947 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005948 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5949
5950 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005951 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5952 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005953 CheckNonNullExpr(*this, RetValExp))
5954 Diag(ReturnLoc, diag::warn_null_ret)
5955 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005956
5957 // C++11 [basic.stc.dynamic.allocation]p4:
5958 // If an allocation function declared with a non-throwing
5959 // exception-specification fails to allocate storage, it shall return
5960 // a null pointer. Any other allocation function that fails to allocate
5961 // storage shall indicate failure only by throwing an exception [...]
5962 if (FD) {
5963 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5964 if (Op == OO_New || Op == OO_Array_New) {
5965 const FunctionProtoType *Proto
5966 = FD->getType()->castAs<FunctionProtoType>();
5967 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5968 CheckNonNullExpr(*this, RetValExp))
5969 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5970 << FD << getLangOpts().CPlusPlus11;
5971 }
5972 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005973}
5974
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005975//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5976
5977/// Check for comparisons of floating point operands using != and ==.
5978/// Issue a warning if these are no self-comparisons, as they are not likely
5979/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005980void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005981 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5982 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005983
5984 // Special case: check for x == x (which is OK).
5985 // Do not emit warnings for such cases.
5986 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5987 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5988 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005989 return;
Mike Stump11289f42009-09-09 15:08:12 +00005990
5991
Ted Kremenekeda40e22007-11-29 00:59:04 +00005992 // Special case: check for comparisons against literals that can be exactly
5993 // represented by APFloat. In such cases, do not emit a warning. This
5994 // is a heuristic: often comparison against such literals are used to
5995 // detect if a value in a variable has not changed. This clearly can
5996 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005997 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5998 if (FLL->isExact())
5999 return;
6000 } else
6001 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6002 if (FLR->isExact())
6003 return;
Mike Stump11289f42009-09-09 15:08:12 +00006004
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006005 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006006 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006007 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006008 return;
Mike Stump11289f42009-09-09 15:08:12 +00006009
David Blaikie1f4ff152012-07-16 20:47:22 +00006010 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006011 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006012 return;
Mike Stump11289f42009-09-09 15:08:12 +00006013
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006014 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006015 Diag(Loc, diag::warn_floatingpoint_eq)
6016 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006017}
John McCallca01b222010-01-04 23:21:16 +00006018
John McCall70aa5392010-01-06 05:24:50 +00006019//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6020//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006021
John McCall70aa5392010-01-06 05:24:50 +00006022namespace {
John McCallca01b222010-01-04 23:21:16 +00006023
John McCall70aa5392010-01-06 05:24:50 +00006024/// Structure recording the 'active' range of an integer-valued
6025/// expression.
6026struct IntRange {
6027 /// The number of bits active in the int.
6028 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006029
John McCall70aa5392010-01-06 05:24:50 +00006030 /// True if the int is known not to have negative values.
6031 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006032
John McCall70aa5392010-01-06 05:24:50 +00006033 IntRange(unsigned Width, bool NonNegative)
6034 : Width(Width), NonNegative(NonNegative)
6035 {}
John McCallca01b222010-01-04 23:21:16 +00006036
John McCall817d4af2010-11-10 23:38:19 +00006037 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006038 static IntRange forBoolType() {
6039 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006040 }
6041
John McCall817d4af2010-11-10 23:38:19 +00006042 /// Returns the range of an opaque value of the given integral type.
6043 static IntRange forValueOfType(ASTContext &C, QualType T) {
6044 return forValueOfCanonicalType(C,
6045 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006046 }
6047
John McCall817d4af2010-11-10 23:38:19 +00006048 /// Returns the range of an opaque value of a canonical integral type.
6049 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006050 assert(T->isCanonicalUnqualified());
6051
6052 if (const VectorType *VT = dyn_cast<VectorType>(T))
6053 T = VT->getElementType().getTypePtr();
6054 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6055 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006056 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6057 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006058
David Majnemer6a426652013-06-07 22:07:20 +00006059 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006060 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006061 EnumDecl *Enum = ET->getDecl();
6062 if (!Enum->isCompleteDefinition())
6063 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006064
David Majnemer6a426652013-06-07 22:07:20 +00006065 unsigned NumPositive = Enum->getNumPositiveBits();
6066 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006067
David Majnemer6a426652013-06-07 22:07:20 +00006068 if (NumNegative == 0)
6069 return IntRange(NumPositive, true/*NonNegative*/);
6070 else
6071 return IntRange(std::max(NumPositive + 1, NumNegative),
6072 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006073 }
John McCall70aa5392010-01-06 05:24:50 +00006074
6075 const BuiltinType *BT = cast<BuiltinType>(T);
6076 assert(BT->isInteger());
6077
6078 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6079 }
6080
John McCall817d4af2010-11-10 23:38:19 +00006081 /// Returns the "target" range of a canonical integral type, i.e.
6082 /// the range of values expressible in the type.
6083 ///
6084 /// This matches forValueOfCanonicalType except that enums have the
6085 /// full range of their type, not the range of their enumerators.
6086 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6087 assert(T->isCanonicalUnqualified());
6088
6089 if (const VectorType *VT = dyn_cast<VectorType>(T))
6090 T = VT->getElementType().getTypePtr();
6091 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6092 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006093 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6094 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006095 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006096 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006097
6098 const BuiltinType *BT = cast<BuiltinType>(T);
6099 assert(BT->isInteger());
6100
6101 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6102 }
6103
6104 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006105 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006106 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006107 L.NonNegative && R.NonNegative);
6108 }
6109
John McCall817d4af2010-11-10 23:38:19 +00006110 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006111 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006112 return IntRange(std::min(L.Width, R.Width),
6113 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006114 }
6115};
6116
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006117static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6118 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006119 if (value.isSigned() && value.isNegative())
6120 return IntRange(value.getMinSignedBits(), false);
6121
6122 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006123 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006124
6125 // isNonNegative() just checks the sign bit without considering
6126 // signedness.
6127 return IntRange(value.getActiveBits(), true);
6128}
6129
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006130static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6131 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006132 if (result.isInt())
6133 return GetValueRange(C, result.getInt(), MaxWidth);
6134
6135 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006136 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6137 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6138 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6139 R = IntRange::join(R, El);
6140 }
John McCall70aa5392010-01-06 05:24:50 +00006141 return R;
6142 }
6143
6144 if (result.isComplexInt()) {
6145 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6146 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6147 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006148 }
6149
6150 // This can happen with lossless casts to intptr_t of "based" lvalues.
6151 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006152 // FIXME: The only reason we need to pass the type in here is to get
6153 // the sign right on this one case. It would be nice if APValue
6154 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006155 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006156 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006157}
John McCall70aa5392010-01-06 05:24:50 +00006158
Eli Friedmane6d33952013-07-08 20:20:06 +00006159static QualType GetExprType(Expr *E) {
6160 QualType Ty = E->getType();
6161 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6162 Ty = AtomicRHS->getValueType();
6163 return Ty;
6164}
6165
John McCall70aa5392010-01-06 05:24:50 +00006166/// Pseudo-evaluate the given integer expression, estimating the
6167/// range of values it might take.
6168///
6169/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006170static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006171 E = E->IgnoreParens();
6172
6173 // Try a full evaluation first.
6174 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006175 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006176 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006177
6178 // I think we only want to look through implicit casts here; if the
6179 // user has an explicit widening cast, we should treat the value as
6180 // being of the new, wider type.
6181 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006182 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006183 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6184
Eli Friedmane6d33952013-07-08 20:20:06 +00006185 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006186
John McCalle3027922010-08-25 11:45:40 +00006187 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006188
John McCall70aa5392010-01-06 05:24:50 +00006189 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006190 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006191 return OutputTypeRange;
6192
6193 IntRange SubRange
6194 = GetExprRange(C, CE->getSubExpr(),
6195 std::min(MaxWidth, OutputTypeRange.Width));
6196
6197 // Bail out if the subexpr's range is as wide as the cast type.
6198 if (SubRange.Width >= OutputTypeRange.Width)
6199 return OutputTypeRange;
6200
6201 // Otherwise, we take the smaller width, and we're non-negative if
6202 // either the output type or the subexpr is.
6203 return IntRange(SubRange.Width,
6204 SubRange.NonNegative || OutputTypeRange.NonNegative);
6205 }
6206
6207 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6208 // If we can fold the condition, just take that operand.
6209 bool CondResult;
6210 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6211 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6212 : CO->getFalseExpr(),
6213 MaxWidth);
6214
6215 // Otherwise, conservatively merge.
6216 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6217 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6218 return IntRange::join(L, R);
6219 }
6220
6221 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6222 switch (BO->getOpcode()) {
6223
6224 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006225 case BO_LAnd:
6226 case BO_LOr:
6227 case BO_LT:
6228 case BO_GT:
6229 case BO_LE:
6230 case BO_GE:
6231 case BO_EQ:
6232 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006233 return IntRange::forBoolType();
6234
John McCallc3688382011-07-13 06:35:24 +00006235 // The type of the assignments is the type of the LHS, so the RHS
6236 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006237 case BO_MulAssign:
6238 case BO_DivAssign:
6239 case BO_RemAssign:
6240 case BO_AddAssign:
6241 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006242 case BO_XorAssign:
6243 case BO_OrAssign:
6244 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006245 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006246
John McCallc3688382011-07-13 06:35:24 +00006247 // Simple assignments just pass through the RHS, which will have
6248 // been coerced to the LHS type.
6249 case BO_Assign:
6250 // TODO: bitfields?
6251 return GetExprRange(C, BO->getRHS(), MaxWidth);
6252
John McCall70aa5392010-01-06 05:24:50 +00006253 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006254 case BO_PtrMemD:
6255 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006256 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006257
John McCall2ce81ad2010-01-06 22:07:33 +00006258 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006259 case BO_And:
6260 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006261 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6262 GetExprRange(C, BO->getRHS(), MaxWidth));
6263
John McCall70aa5392010-01-06 05:24:50 +00006264 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006265 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006266 // ...except that we want to treat '1 << (blah)' as logically
6267 // positive. It's an important idiom.
6268 if (IntegerLiteral *I
6269 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6270 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006271 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006272 return IntRange(R.Width, /*NonNegative*/ true);
6273 }
6274 }
6275 // fallthrough
6276
John McCalle3027922010-08-25 11:45:40 +00006277 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006278 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006279
John McCall2ce81ad2010-01-06 22:07:33 +00006280 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006281 case BO_Shr:
6282 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006283 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6284
6285 // If the shift amount is a positive constant, drop the width by
6286 // that much.
6287 llvm::APSInt shift;
6288 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6289 shift.isNonNegative()) {
6290 unsigned zext = shift.getZExtValue();
6291 if (zext >= L.Width)
6292 L.Width = (L.NonNegative ? 0 : 1);
6293 else
6294 L.Width -= zext;
6295 }
6296
6297 return L;
6298 }
6299
6300 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006301 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006302 return GetExprRange(C, BO->getRHS(), MaxWidth);
6303
John McCall2ce81ad2010-01-06 22:07:33 +00006304 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006305 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006306 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006307 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006308 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006309
John McCall51431812011-07-14 22:39:48 +00006310 // The width of a division result is mostly determined by the size
6311 // of the LHS.
6312 case BO_Div: {
6313 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006314 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006315 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6316
6317 // If the divisor is constant, use that.
6318 llvm::APSInt divisor;
6319 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6320 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6321 if (log2 >= L.Width)
6322 L.Width = (L.NonNegative ? 0 : 1);
6323 else
6324 L.Width = std::min(L.Width - log2, MaxWidth);
6325 return L;
6326 }
6327
6328 // Otherwise, just use the LHS's width.
6329 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6330 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6331 }
6332
6333 // The result of a remainder can't be larger than the result of
6334 // either side.
6335 case BO_Rem: {
6336 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006337 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006338 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6339 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6340
6341 IntRange meet = IntRange::meet(L, R);
6342 meet.Width = std::min(meet.Width, MaxWidth);
6343 return meet;
6344 }
6345
6346 // The default behavior is okay for these.
6347 case BO_Mul:
6348 case BO_Add:
6349 case BO_Xor:
6350 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006351 break;
6352 }
6353
John McCall51431812011-07-14 22:39:48 +00006354 // The default case is to treat the operation as if it were closed
6355 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006356 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6357 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6358 return IntRange::join(L, R);
6359 }
6360
6361 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6362 switch (UO->getOpcode()) {
6363 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006364 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006365 return IntRange::forBoolType();
6366
6367 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006368 case UO_Deref:
6369 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006370 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006371
6372 default:
6373 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6374 }
6375 }
6376
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006377 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6378 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6379
John McCalld25db7e2013-05-06 21:39:12 +00006380 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006381 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006382 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006383
Eli Friedmane6d33952013-07-08 20:20:06 +00006384 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006385}
John McCall263a48b2010-01-04 23:31:57 +00006386
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006387static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006388 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006389}
6390
John McCall263a48b2010-01-04 23:31:57 +00006391/// Checks whether the given value, which currently has the given
6392/// source semantics, has the same value when coerced through the
6393/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006394static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6395 const llvm::fltSemantics &Src,
6396 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006397 llvm::APFloat truncated = value;
6398
6399 bool ignored;
6400 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6401 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6402
6403 return truncated.bitwiseIsEqual(value);
6404}
6405
6406/// Checks whether the given value, which currently has the given
6407/// source semantics, has the same value when coerced through the
6408/// target semantics.
6409///
6410/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006411static bool IsSameFloatAfterCast(const APValue &value,
6412 const llvm::fltSemantics &Src,
6413 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006414 if (value.isFloat())
6415 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6416
6417 if (value.isVector()) {
6418 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6419 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6420 return false;
6421 return true;
6422 }
6423
6424 assert(value.isComplexFloat());
6425 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6426 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6427}
6428
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006429static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006430
Ted Kremenek6274be42010-09-23 21:43:44 +00006431static bool IsZero(Sema &S, Expr *E) {
6432 // Suppress cases where we are comparing against an enum constant.
6433 if (const DeclRefExpr *DR =
6434 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6435 if (isa<EnumConstantDecl>(DR->getDecl()))
6436 return false;
6437
6438 // Suppress cases where the '0' value is expanded from a macro.
6439 if (E->getLocStart().isMacroID())
6440 return false;
6441
John McCallcc7e5bf2010-05-06 08:58:33 +00006442 llvm::APSInt Value;
6443 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6444}
6445
John McCall2551c1b2010-10-06 00:25:24 +00006446static bool HasEnumType(Expr *E) {
6447 // Strip off implicit integral promotions.
6448 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006449 if (ICE->getCastKind() != CK_IntegralCast &&
6450 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006451 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006452 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006453 }
6454
6455 return E->getType()->isEnumeralType();
6456}
6457
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006458static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006459 // Disable warning in template instantiations.
6460 if (!S.ActiveTemplateInstantiations.empty())
6461 return;
6462
John McCalle3027922010-08-25 11:45:40 +00006463 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006464 if (E->isValueDependent())
6465 return;
6466
John McCalle3027922010-08-25 11:45:40 +00006467 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006468 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006469 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006470 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006471 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006472 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006473 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006474 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006475 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006476 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006477 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006478 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006479 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006480 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006481 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006482 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6483 }
6484}
6485
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006486static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006487 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006488 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006489 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006490 // Disable warning in template instantiations.
6491 if (!S.ActiveTemplateInstantiations.empty())
6492 return;
6493
Richard Trieu0f097742014-04-04 04:13:47 +00006494 // TODO: Investigate using GetExprRange() to get tighter bounds
6495 // on the bit ranges.
6496 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006497 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006498 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006499 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6500 unsigned OtherWidth = OtherRange.Width;
6501
6502 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6503
Richard Trieu560910c2012-11-14 22:50:24 +00006504 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006505 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006506 return;
6507
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006508 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006509 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006510
Richard Trieu0f097742014-04-04 04:13:47 +00006511 // Used for diagnostic printout.
6512 enum {
6513 LiteralConstant = 0,
6514 CXXBoolLiteralTrue,
6515 CXXBoolLiteralFalse
6516 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006517
Richard Trieu0f097742014-04-04 04:13:47 +00006518 if (!OtherIsBooleanType) {
6519 QualType ConstantT = Constant->getType();
6520 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006521
Richard Trieu0f097742014-04-04 04:13:47 +00006522 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6523 return;
6524 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6525 "comparison with non-integer type");
6526
6527 bool ConstantSigned = ConstantT->isSignedIntegerType();
6528 bool CommonSigned = CommonT->isSignedIntegerType();
6529
6530 bool EqualityOnly = false;
6531
6532 if (CommonSigned) {
6533 // The common type is signed, therefore no signed to unsigned conversion.
6534 if (!OtherRange.NonNegative) {
6535 // Check that the constant is representable in type OtherT.
6536 if (ConstantSigned) {
6537 if (OtherWidth >= Value.getMinSignedBits())
6538 return;
6539 } else { // !ConstantSigned
6540 if (OtherWidth >= Value.getActiveBits() + 1)
6541 return;
6542 }
6543 } else { // !OtherSigned
6544 // Check that the constant is representable in type OtherT.
6545 // Negative values are out of range.
6546 if (ConstantSigned) {
6547 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6548 return;
6549 } else { // !ConstantSigned
6550 if (OtherWidth >= Value.getActiveBits())
6551 return;
6552 }
Richard Trieu560910c2012-11-14 22:50:24 +00006553 }
Richard Trieu0f097742014-04-04 04:13:47 +00006554 } else { // !CommonSigned
6555 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006556 if (OtherWidth >= Value.getActiveBits())
6557 return;
Craig Toppercf360162014-06-18 05:13:11 +00006558 } else { // OtherSigned
6559 assert(!ConstantSigned &&
6560 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006561 // Check to see if the constant is representable in OtherT.
6562 if (OtherWidth > Value.getActiveBits())
6563 return;
6564 // Check to see if the constant is equivalent to a negative value
6565 // cast to CommonT.
6566 if (S.Context.getIntWidth(ConstantT) ==
6567 S.Context.getIntWidth(CommonT) &&
6568 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6569 return;
6570 // The constant value rests between values that OtherT can represent
6571 // after conversion. Relational comparison still works, but equality
6572 // comparisons will be tautological.
6573 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006574 }
6575 }
Richard Trieu0f097742014-04-04 04:13:47 +00006576
6577 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6578
6579 if (op == BO_EQ || op == BO_NE) {
6580 IsTrue = op == BO_NE;
6581 } else if (EqualityOnly) {
6582 return;
6583 } else if (RhsConstant) {
6584 if (op == BO_GT || op == BO_GE)
6585 IsTrue = !PositiveConstant;
6586 else // op == BO_LT || op == BO_LE
6587 IsTrue = PositiveConstant;
6588 } else {
6589 if (op == BO_LT || op == BO_LE)
6590 IsTrue = !PositiveConstant;
6591 else // op == BO_GT || op == BO_GE
6592 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006593 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006594 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006595 // Other isKnownToHaveBooleanValue
6596 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6597 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6598 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6599
6600 static const struct LinkedConditions {
6601 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6602 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6603 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6604 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6605 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6606 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6607
6608 } TruthTable = {
6609 // Constant on LHS. | Constant on RHS. |
6610 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6611 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6612 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6613 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6614 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6615 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6616 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6617 };
6618
6619 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6620
6621 enum ConstantValue ConstVal = Zero;
6622 if (Value.isUnsigned() || Value.isNonNegative()) {
6623 if (Value == 0) {
6624 LiteralOrBoolConstant =
6625 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6626 ConstVal = Zero;
6627 } else if (Value == 1) {
6628 LiteralOrBoolConstant =
6629 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6630 ConstVal = One;
6631 } else {
6632 LiteralOrBoolConstant = LiteralConstant;
6633 ConstVal = GT_One;
6634 }
6635 } else {
6636 ConstVal = LT_Zero;
6637 }
6638
6639 CompareBoolWithConstantResult CmpRes;
6640
6641 switch (op) {
6642 case BO_LT:
6643 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6644 break;
6645 case BO_GT:
6646 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6647 break;
6648 case BO_LE:
6649 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6650 break;
6651 case BO_GE:
6652 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6653 break;
6654 case BO_EQ:
6655 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6656 break;
6657 case BO_NE:
6658 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6659 break;
6660 default:
6661 CmpRes = Unkwn;
6662 break;
6663 }
6664
6665 if (CmpRes == AFals) {
6666 IsTrue = false;
6667 } else if (CmpRes == ATrue) {
6668 IsTrue = true;
6669 } else {
6670 return;
6671 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006672 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006673
6674 // If this is a comparison to an enum constant, include that
6675 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006676 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006677 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6678 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6679
6680 SmallString<64> PrettySourceValue;
6681 llvm::raw_svector_ostream OS(PrettySourceValue);
6682 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006683 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006684 else
6685 OS << Value;
6686
Richard Trieu0f097742014-04-04 04:13:47 +00006687 S.DiagRuntimeBehavior(
6688 E->getOperatorLoc(), E,
6689 S.PDiag(diag::warn_out_of_range_compare)
6690 << OS.str() << LiteralOrBoolConstant
6691 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6692 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006693}
6694
John McCallcc7e5bf2010-05-06 08:58:33 +00006695/// Analyze the operands of the given comparison. Implements the
6696/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006697static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006698 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6699 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006700}
John McCall263a48b2010-01-04 23:31:57 +00006701
John McCallca01b222010-01-04 23:21:16 +00006702/// \brief Implements -Wsign-compare.
6703///
Richard Trieu82402a02011-09-15 21:56:47 +00006704/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006705static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006706 // The type the comparison is being performed in.
6707 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006708
6709 // Only analyze comparison operators where both sides have been converted to
6710 // the same type.
6711 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6712 return AnalyzeImpConvsInComparison(S, E);
6713
6714 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006715 if (E->isValueDependent())
6716 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006717
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006718 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6719 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006720
6721 bool IsComparisonConstant = false;
6722
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006723 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006724 // of 'true' or 'false'.
6725 if (T->isIntegralType(S.Context)) {
6726 llvm::APSInt RHSValue;
6727 bool IsRHSIntegralLiteral =
6728 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6729 llvm::APSInt LHSValue;
6730 bool IsLHSIntegralLiteral =
6731 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6732 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6733 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6734 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6735 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6736 else
6737 IsComparisonConstant =
6738 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006739 } else if (!T->hasUnsignedIntegerRepresentation())
6740 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006741
John McCallcc7e5bf2010-05-06 08:58:33 +00006742 // We don't do anything special if this isn't an unsigned integral
6743 // comparison: we're only interested in integral comparisons, and
6744 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006745 //
6746 // We also don't care about value-dependent expressions or expressions
6747 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006748 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006749 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006750
John McCallcc7e5bf2010-05-06 08:58:33 +00006751 // Check to see if one of the (unmodified) operands is of different
6752 // signedness.
6753 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006754 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6755 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006756 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006757 signedOperand = LHS;
6758 unsignedOperand = RHS;
6759 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6760 signedOperand = RHS;
6761 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006762 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006763 CheckTrivialUnsignedComparison(S, E);
6764 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006765 }
6766
John McCallcc7e5bf2010-05-06 08:58:33 +00006767 // Otherwise, calculate the effective range of the signed operand.
6768 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006769
John McCallcc7e5bf2010-05-06 08:58:33 +00006770 // Go ahead and analyze implicit conversions in the operands. Note
6771 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006772 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6773 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006774
John McCallcc7e5bf2010-05-06 08:58:33 +00006775 // If the signed range is non-negative, -Wsign-compare won't fire,
6776 // but we should still check for comparisons which are always true
6777 // or false.
6778 if (signedRange.NonNegative)
6779 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006780
6781 // For (in)equality comparisons, if the unsigned operand is a
6782 // constant which cannot collide with a overflowed signed operand,
6783 // then reinterpreting the signed operand as unsigned will not
6784 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006785 if (E->isEqualityOp()) {
6786 unsigned comparisonWidth = S.Context.getIntWidth(T);
6787 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006788
John McCallcc7e5bf2010-05-06 08:58:33 +00006789 // We should never be unable to prove that the unsigned operand is
6790 // non-negative.
6791 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6792
6793 if (unsignedRange.Width < comparisonWidth)
6794 return;
6795 }
6796
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006797 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6798 S.PDiag(diag::warn_mixed_sign_comparison)
6799 << LHS->getType() << RHS->getType()
6800 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006801}
6802
John McCall1f425642010-11-11 03:21:53 +00006803/// Analyzes an attempt to assign the given value to a bitfield.
6804///
6805/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006806static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6807 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006808 assert(Bitfield->isBitField());
6809 if (Bitfield->isInvalidDecl())
6810 return false;
6811
John McCalldeebbcf2010-11-11 05:33:51 +00006812 // White-list bool bitfields.
6813 if (Bitfield->getType()->isBooleanType())
6814 return false;
6815
Douglas Gregor789adec2011-02-04 13:09:01 +00006816 // Ignore value- or type-dependent expressions.
6817 if (Bitfield->getBitWidth()->isValueDependent() ||
6818 Bitfield->getBitWidth()->isTypeDependent() ||
6819 Init->isValueDependent() ||
6820 Init->isTypeDependent())
6821 return false;
6822
John McCall1f425642010-11-11 03:21:53 +00006823 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6824
Richard Smith5fab0c92011-12-28 19:48:30 +00006825 llvm::APSInt Value;
6826 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006827 return false;
6828
John McCall1f425642010-11-11 03:21:53 +00006829 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006830 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006831
6832 if (OriginalWidth <= FieldWidth)
6833 return false;
6834
Eli Friedmanc267a322012-01-26 23:11:39 +00006835 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006836 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006837 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006838
Eli Friedmanc267a322012-01-26 23:11:39 +00006839 // Check whether the stored value is equal to the original value.
6840 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006841 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006842 return false;
6843
Eli Friedmanc267a322012-01-26 23:11:39 +00006844 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006845 // therefore don't strictly fit into a signed bitfield of width 1.
6846 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006847 return false;
6848
John McCall1f425642010-11-11 03:21:53 +00006849 std::string PrettyValue = Value.toString(10);
6850 std::string PrettyTrunc = TruncatedValue.toString(10);
6851
6852 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6853 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6854 << Init->getSourceRange();
6855
6856 return true;
6857}
6858
John McCalld2a53122010-11-09 23:24:47 +00006859/// Analyze the given simple or compound assignment for warning-worthy
6860/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006861static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006862 // Just recurse on the LHS.
6863 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6864
6865 // We want to recurse on the RHS as normal unless we're assigning to
6866 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006867 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006868 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006869 E->getOperatorLoc())) {
6870 // Recurse, ignoring any implicit conversions on the RHS.
6871 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6872 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006873 }
6874 }
6875
6876 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6877}
6878
John McCall263a48b2010-01-04 23:31:57 +00006879/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006880static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006881 SourceLocation CContext, unsigned diag,
6882 bool pruneControlFlow = false) {
6883 if (pruneControlFlow) {
6884 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6885 S.PDiag(diag)
6886 << SourceType << T << E->getSourceRange()
6887 << SourceRange(CContext));
6888 return;
6889 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006890 S.Diag(E->getExprLoc(), diag)
6891 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6892}
6893
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006894/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006895static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006896 SourceLocation CContext, unsigned diag,
6897 bool pruneControlFlow = false) {
6898 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006899}
6900
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006901/// Diagnose an implicit cast from a literal expression. Does not warn when the
6902/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006903void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6904 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006905 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006906 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006907 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006908 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6909 T->hasUnsignedIntegerRepresentation());
6910 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006911 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006912 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006913 return;
6914
Eli Friedman07185912013-08-29 23:44:43 +00006915 // FIXME: Force the precision of the source value down so we don't print
6916 // digits which are usually useless (we don't really care here if we
6917 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6918 // would automatically print the shortest representation, but it's a bit
6919 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006920 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006921 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6922 precision = (precision * 59 + 195) / 196;
6923 Value.toString(PrettySourceValue, precision);
6924
David Blaikie9b88cc02012-05-15 17:18:27 +00006925 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006926 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6927 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6928 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006929 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006930
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006931 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006932 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6933 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006934}
6935
John McCall18a2c2c2010-11-09 22:22:12 +00006936std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6937 if (!Range.Width) return "0";
6938
6939 llvm::APSInt ValueInRange = Value;
6940 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006941 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006942 return ValueInRange.toString(10);
6943}
6944
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006945static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6946 if (!isa<ImplicitCastExpr>(Ex))
6947 return false;
6948
6949 Expr *InnerE = Ex->IgnoreParenImpCasts();
6950 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6951 const Type *Source =
6952 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6953 if (Target->isDependentType())
6954 return false;
6955
6956 const BuiltinType *FloatCandidateBT =
6957 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6958 const Type *BoolCandidateType = ToBool ? Target : Source;
6959
6960 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6961 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6962}
6963
6964void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6965 SourceLocation CC) {
6966 unsigned NumArgs = TheCall->getNumArgs();
6967 for (unsigned i = 0; i < NumArgs; ++i) {
6968 Expr *CurrA = TheCall->getArg(i);
6969 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6970 continue;
6971
6972 bool IsSwapped = ((i > 0) &&
6973 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6974 IsSwapped |= ((i < (NumArgs - 1)) &&
6975 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6976 if (IsSwapped) {
6977 // Warn on this floating-point to bool conversion.
6978 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6979 CurrA->getType(), CC,
6980 diag::warn_impcast_floating_point_to_bool);
6981 }
6982 }
6983}
6984
Richard Trieu5b993502014-10-15 03:42:06 +00006985static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6986 SourceLocation CC) {
6987 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6988 E->getExprLoc()))
6989 return;
6990
6991 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6992 const Expr::NullPointerConstantKind NullKind =
6993 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6994 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6995 return;
6996
6997 // Return if target type is a safe conversion.
6998 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6999 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7000 return;
7001
7002 SourceLocation Loc = E->getSourceRange().getBegin();
7003
7004 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7005 if (NullKind == Expr::NPCK_GNUNull) {
7006 if (Loc.isMacroID())
7007 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7008 }
7009
7010 // Only warn if the null and context location are in the same macro expansion.
7011 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7012 return;
7013
7014 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7015 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7016 << FixItHint::CreateReplacement(Loc,
7017 S.getFixItZeroLiteralForType(T, Loc));
7018}
7019
Douglas Gregor5054cb02015-07-07 03:58:22 +00007020static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7021 ObjCArrayLiteral *ArrayLiteral);
7022static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7023 ObjCDictionaryLiteral *DictionaryLiteral);
7024
7025/// Check a single element within a collection literal against the
7026/// target element type.
7027static void checkObjCCollectionLiteralElement(Sema &S,
7028 QualType TargetElementType,
7029 Expr *Element,
7030 unsigned ElementKind) {
7031 // Skip a bitcast to 'id' or qualified 'id'.
7032 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7033 if (ICE->getCastKind() == CK_BitCast &&
7034 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7035 Element = ICE->getSubExpr();
7036 }
7037
7038 QualType ElementType = Element->getType();
7039 ExprResult ElementResult(Element);
7040 if (ElementType->getAs<ObjCObjectPointerType>() &&
7041 S.CheckSingleAssignmentConstraints(TargetElementType,
7042 ElementResult,
7043 false, false)
7044 != Sema::Compatible) {
7045 S.Diag(Element->getLocStart(),
7046 diag::warn_objc_collection_literal_element)
7047 << ElementType << ElementKind << TargetElementType
7048 << Element->getSourceRange();
7049 }
7050
7051 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7052 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7053 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7054 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7055}
7056
7057/// Check an Objective-C array literal being converted to the given
7058/// target type.
7059static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7060 ObjCArrayLiteral *ArrayLiteral) {
7061 if (!S.NSArrayDecl)
7062 return;
7063
7064 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7065 if (!TargetObjCPtr)
7066 return;
7067
7068 if (TargetObjCPtr->isUnspecialized() ||
7069 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7070 != S.NSArrayDecl->getCanonicalDecl())
7071 return;
7072
7073 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7074 if (TypeArgs.size() != 1)
7075 return;
7076
7077 QualType TargetElementType = TypeArgs[0];
7078 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7079 checkObjCCollectionLiteralElement(S, TargetElementType,
7080 ArrayLiteral->getElement(I),
7081 0);
7082 }
7083}
7084
7085/// Check an Objective-C dictionary literal being converted to the given
7086/// target type.
7087static void checkObjCDictionaryLiteral(
7088 Sema &S, QualType TargetType,
7089 ObjCDictionaryLiteral *DictionaryLiteral) {
7090 if (!S.NSDictionaryDecl)
7091 return;
7092
7093 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7094 if (!TargetObjCPtr)
7095 return;
7096
7097 if (TargetObjCPtr->isUnspecialized() ||
7098 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7099 != S.NSDictionaryDecl->getCanonicalDecl())
7100 return;
7101
7102 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7103 if (TypeArgs.size() != 2)
7104 return;
7105
7106 QualType TargetKeyType = TypeArgs[0];
7107 QualType TargetObjectType = TypeArgs[1];
7108 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7109 auto Element = DictionaryLiteral->getKeyValueElement(I);
7110 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7111 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7112 }
7113}
7114
John McCallcc7e5bf2010-05-06 08:58:33 +00007115void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007116 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007117 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007118
John McCallcc7e5bf2010-05-06 08:58:33 +00007119 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7120 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7121 if (Source == Target) return;
7122 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007123
Chandler Carruthc22845a2011-07-26 05:40:03 +00007124 // If the conversion context location is invalid don't complain. We also
7125 // don't want to emit a warning if the issue occurs from the expansion of
7126 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7127 // delay this check as long as possible. Once we detect we are in that
7128 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007129 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007130 return;
7131
Richard Trieu021baa32011-09-23 20:10:00 +00007132 // Diagnose implicit casts to bool.
7133 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7134 if (isa<StringLiteral>(E))
7135 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007136 // and expressions, for instance, assert(0 && "error here"), are
7137 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007138 return DiagnoseImpCast(S, E, T, CC,
7139 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007140 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7141 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7142 // This covers the literal expressions that evaluate to Objective-C
7143 // objects.
7144 return DiagnoseImpCast(S, E, T, CC,
7145 diag::warn_impcast_objective_c_literal_to_bool);
7146 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007147 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7148 // Warn on pointer to bool conversion that is always true.
7149 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7150 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007151 }
Richard Trieu021baa32011-09-23 20:10:00 +00007152 }
John McCall263a48b2010-01-04 23:31:57 +00007153
Douglas Gregor5054cb02015-07-07 03:58:22 +00007154 // Check implicit casts from Objective-C collection literals to specialized
7155 // collection types, e.g., NSArray<NSString *> *.
7156 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7157 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7158 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7159 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7160
John McCall263a48b2010-01-04 23:31:57 +00007161 // Strip vector types.
7162 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007163 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007164 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007165 return;
John McCallacf0ee52010-10-08 02:01:28 +00007166 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007167 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007168
7169 // If the vector cast is cast between two vectors of the same size, it is
7170 // a bitcast, not a conversion.
7171 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7172 return;
John McCall263a48b2010-01-04 23:31:57 +00007173
7174 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7175 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7176 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007177 if (auto VecTy = dyn_cast<VectorType>(Target))
7178 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007179
7180 // Strip complex types.
7181 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007182 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007183 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007184 return;
7185
John McCallacf0ee52010-10-08 02:01:28 +00007186 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007187 }
John McCall263a48b2010-01-04 23:31:57 +00007188
7189 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7190 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7191 }
7192
7193 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7194 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7195
7196 // If the source is floating point...
7197 if (SourceBT && SourceBT->isFloatingPoint()) {
7198 // ...and the target is floating point...
7199 if (TargetBT && TargetBT->isFloatingPoint()) {
7200 // ...then warn if we're dropping FP rank.
7201
7202 // Builtin FP kinds are ordered by increasing FP rank.
7203 if (SourceBT->getKind() > TargetBT->getKind()) {
7204 // Don't warn about float constants that are precisely
7205 // representable in the target type.
7206 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007207 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007208 // Value might be a float, a float vector, or a float complex.
7209 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007210 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7211 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007212 return;
7213 }
7214
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007215 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007216 return;
7217
John McCallacf0ee52010-10-08 02:01:28 +00007218 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00007219 }
7220 return;
7221 }
7222
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007223 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007224 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007225 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007226 return;
7227
Chandler Carruth22c7a792011-02-17 11:05:49 +00007228 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007229 // We also want to warn on, e.g., "int i = -1.234"
7230 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7231 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7232 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7233
Chandler Carruth016ef402011-04-10 08:36:24 +00007234 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7235 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007236 } else {
7237 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7238 }
7239 }
John McCall263a48b2010-01-04 23:31:57 +00007240
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007241 // If the target is bool, warn if expr is a function or method call.
7242 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7243 isa<CallExpr>(E)) {
7244 // Check last argument of function call to see if it is an
7245 // implicit cast from a type matching the type the result
7246 // is being cast to.
7247 CallExpr *CEx = cast<CallExpr>(E);
7248 unsigned NumArgs = CEx->getNumArgs();
7249 if (NumArgs > 0) {
7250 Expr *LastA = CEx->getArg(NumArgs - 1);
7251 Expr *InnerE = LastA->IgnoreParenImpCasts();
7252 const Type *InnerType =
7253 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7254 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7255 // Warn on this floating-point to bool conversion
7256 DiagnoseImpCast(S, E, T, CC,
7257 diag::warn_impcast_floating_point_to_bool);
7258 }
7259 }
7260 }
John McCall263a48b2010-01-04 23:31:57 +00007261 return;
7262 }
7263
Richard Trieu5b993502014-10-15 03:42:06 +00007264 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007265
David Blaikie9366d2b2012-06-19 21:19:06 +00007266 if (!Source->isIntegerType() || !Target->isIntegerType())
7267 return;
7268
David Blaikie7555b6a2012-05-15 16:56:36 +00007269 // TODO: remove this early return once the false positives for constant->bool
7270 // in templates, macros, etc, are reduced or removed.
7271 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7272 return;
7273
John McCallcc7e5bf2010-05-06 08:58:33 +00007274 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007275 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007276
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007277 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007278 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007279 // TODO: this should happen for bitfield stores, too.
7280 llvm::APSInt Value(32);
7281 if (E->isIntegerConstantExpr(Value, S.Context)) {
7282 if (S.SourceMgr.isInSystemMacro(CC))
7283 return;
7284
John McCall18a2c2c2010-11-09 22:22:12 +00007285 std::string PrettySourceValue = Value.toString(10);
7286 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007287
Ted Kremenek33ba9952011-10-22 02:37:33 +00007288 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7289 S.PDiag(diag::warn_impcast_integer_precision_constant)
7290 << PrettySourceValue << PrettyTargetValue
7291 << E->getType() << T << E->getSourceRange()
7292 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007293 return;
7294 }
7295
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007296 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7297 if (S.SourceMgr.isInSystemMacro(CC))
7298 return;
7299
David Blaikie9455da02012-04-12 22:40:54 +00007300 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007301 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7302 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007303 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007304 }
7305
7306 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7307 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7308 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007309
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007310 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007311 return;
7312
John McCallcc7e5bf2010-05-06 08:58:33 +00007313 unsigned DiagID = diag::warn_impcast_integer_sign;
7314
7315 // Traditionally, gcc has warned about this under -Wsign-compare.
7316 // We also want to warn about it in -Wconversion.
7317 // So if -Wconversion is off, use a completely identical diagnostic
7318 // in the sign-compare group.
7319 // The conditional-checking code will
7320 if (ICContext) {
7321 DiagID = diag::warn_impcast_integer_sign_conditional;
7322 *ICContext = true;
7323 }
7324
John McCallacf0ee52010-10-08 02:01:28 +00007325 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007326 }
7327
Douglas Gregora78f1932011-02-22 02:45:07 +00007328 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007329 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7330 // type, to give us better diagnostics.
7331 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007332 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007333 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7334 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7335 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7336 SourceType = S.Context.getTypeDeclType(Enum);
7337 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7338 }
7339 }
7340
Douglas Gregora78f1932011-02-22 02:45:07 +00007341 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7342 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007343 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7344 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007345 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007346 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007347 return;
7348
Douglas Gregor364f7db2011-03-12 00:14:31 +00007349 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007350 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007351 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007352
John McCall263a48b2010-01-04 23:31:57 +00007353 return;
7354}
7355
David Blaikie18e9ac72012-05-15 21:57:38 +00007356void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7357 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007358
7359void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007360 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007361 E = E->IgnoreParenImpCasts();
7362
7363 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007364 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007365
John McCallacf0ee52010-10-08 02:01:28 +00007366 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007367 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007368 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007369 return;
7370}
7371
David Blaikie18e9ac72012-05-15 21:57:38 +00007372void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7373 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007374 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007375
7376 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007377 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7378 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007379
7380 // If -Wconversion would have warned about either of the candidates
7381 // for a signedness conversion to the context type...
7382 if (!Suspicious) return;
7383
7384 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007385 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007386 return;
7387
John McCallcc7e5bf2010-05-06 08:58:33 +00007388 // ...then check whether it would have warned about either of the
7389 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007390 if (E->getType() == T) return;
7391
7392 Suspicious = false;
7393 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7394 E->getType(), CC, &Suspicious);
7395 if (!Suspicious)
7396 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007397 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007398}
7399
Richard Trieu65724892014-11-15 06:37:39 +00007400/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7401/// Input argument E is a logical expression.
7402static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7403 if (S.getLangOpts().Bool)
7404 return;
7405 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7406}
7407
John McCallcc7e5bf2010-05-06 08:58:33 +00007408/// AnalyzeImplicitConversions - Find and report any interesting
7409/// implicit conversions in the given expression. There are a couple
7410/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007411void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007412 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007413 Expr *E = OrigE->IgnoreParenImpCasts();
7414
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007415 if (E->isTypeDependent() || E->isValueDependent())
7416 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007417
John McCallcc7e5bf2010-05-06 08:58:33 +00007418 // For conditional operators, we analyze the arguments as if they
7419 // were being fed directly into the output.
7420 if (isa<ConditionalOperator>(E)) {
7421 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007422 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007423 return;
7424 }
7425
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007426 // Check implicit argument conversions for function calls.
7427 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7428 CheckImplicitArgumentConversions(S, Call, CC);
7429
John McCallcc7e5bf2010-05-06 08:58:33 +00007430 // Go ahead and check any implicit conversions we might have skipped.
7431 // The non-canonical typecheck is just an optimization;
7432 // CheckImplicitConversion will filter out dead implicit conversions.
7433 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007434 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007435
7436 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007437
7438 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007439 if (POE->getResultExpr())
7440 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007441 }
7442
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007443 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7444 if (OVE->getSourceExpr())
7445 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7446 return;
7447 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007448
John McCallcc7e5bf2010-05-06 08:58:33 +00007449 // Skip past explicit casts.
7450 if (isa<ExplicitCastExpr>(E)) {
7451 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007452 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007453 }
7454
John McCalld2a53122010-11-09 23:24:47 +00007455 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7456 // Do a somewhat different check with comparison operators.
7457 if (BO->isComparisonOp())
7458 return AnalyzeComparison(S, BO);
7459
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007460 // And with simple assignments.
7461 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007462 return AnalyzeAssignment(S, BO);
7463 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007464
7465 // These break the otherwise-useful invariant below. Fortunately,
7466 // we don't really need to recurse into them, because any internal
7467 // expressions should have been analyzed already when they were
7468 // built into statements.
7469 if (isa<StmtExpr>(E)) return;
7470
7471 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007472 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007473
7474 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007475 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007476 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007477 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007478 for (Stmt *SubStmt : E->children()) {
7479 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007480 if (!ChildExpr)
7481 continue;
7482
Richard Trieu955231d2014-01-25 01:10:35 +00007483 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007484 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007485 // Ignore checking string literals that are in logical and operators.
7486 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007487 continue;
7488 AnalyzeImplicitConversions(S, ChildExpr, CC);
7489 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007490
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007491 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007492 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7493 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007494 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007495
7496 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7497 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007498 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007499 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007500
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007501 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7502 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007503 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007504}
7505
7506} // end anonymous namespace
7507
Richard Trieu3bb8b562014-02-26 02:36:06 +00007508enum {
7509 AddressOf,
7510 FunctionPointer,
7511 ArrayPointer
7512};
7513
Richard Trieuc1888e02014-06-28 23:25:37 +00007514// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7515// Returns true when emitting a warning about taking the address of a reference.
7516static bool CheckForReference(Sema &SemaRef, const Expr *E,
7517 PartialDiagnostic PD) {
7518 E = E->IgnoreParenImpCasts();
7519
7520 const FunctionDecl *FD = nullptr;
7521
7522 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7523 if (!DRE->getDecl()->getType()->isReferenceType())
7524 return false;
7525 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7526 if (!M->getMemberDecl()->getType()->isReferenceType())
7527 return false;
7528 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007529 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007530 return false;
7531 FD = Call->getDirectCallee();
7532 } else {
7533 return false;
7534 }
7535
7536 SemaRef.Diag(E->getExprLoc(), PD);
7537
7538 // If possible, point to location of function.
7539 if (FD) {
7540 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7541 }
7542
7543 return true;
7544}
7545
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007546// Returns true if the SourceLocation is expanded from any macro body.
7547// Returns false if the SourceLocation is invalid, is from not in a macro
7548// expansion, or is from expanded from a top-level macro argument.
7549static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7550 if (Loc.isInvalid())
7551 return false;
7552
7553 while (Loc.isMacroID()) {
7554 if (SM.isMacroBodyExpansion(Loc))
7555 return true;
7556 Loc = SM.getImmediateMacroCallerLoc(Loc);
7557 }
7558
7559 return false;
7560}
7561
Richard Trieu3bb8b562014-02-26 02:36:06 +00007562/// \brief Diagnose pointers that are always non-null.
7563/// \param E the expression containing the pointer
7564/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7565/// compared to a null pointer
7566/// \param IsEqual True when the comparison is equal to a null pointer
7567/// \param Range Extra SourceRange to highlight in the diagnostic
7568void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7569 Expr::NullPointerConstantKind NullKind,
7570 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007571 if (!E)
7572 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007573
7574 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007575 if (E->getExprLoc().isMacroID()) {
7576 const SourceManager &SM = getSourceManager();
7577 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7578 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007579 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007580 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007581 E = E->IgnoreImpCasts();
7582
7583 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7584
Richard Trieuf7432752014-06-06 21:39:26 +00007585 if (isa<CXXThisExpr>(E)) {
7586 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7587 : diag::warn_this_bool_conversion;
7588 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7589 return;
7590 }
7591
Richard Trieu3bb8b562014-02-26 02:36:06 +00007592 bool IsAddressOf = false;
7593
7594 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7595 if (UO->getOpcode() != UO_AddrOf)
7596 return;
7597 IsAddressOf = true;
7598 E = UO->getSubExpr();
7599 }
7600
Richard Trieuc1888e02014-06-28 23:25:37 +00007601 if (IsAddressOf) {
7602 unsigned DiagID = IsCompare
7603 ? diag::warn_address_of_reference_null_compare
7604 : diag::warn_address_of_reference_bool_conversion;
7605 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7606 << IsEqual;
7607 if (CheckForReference(*this, E, PD)) {
7608 return;
7609 }
7610 }
7611
Richard Trieu3bb8b562014-02-26 02:36:06 +00007612 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007613 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007614 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7615 D = R->getDecl();
7616 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7617 D = M->getMemberDecl();
7618 }
7619
7620 // Weak Decls can be null.
7621 if (!D || D->isWeak())
7622 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007623
7624 // Check for parameter decl with nonnull attribute
7625 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7626 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7627 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7628 unsigned NumArgs = FD->getNumParams();
7629 llvm::SmallBitVector AttrNonNull(NumArgs);
7630 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7631 if (!NonNull->args_size()) {
7632 AttrNonNull.set(0, NumArgs);
7633 break;
7634 }
7635 for (unsigned Val : NonNull->args()) {
7636 if (Val >= NumArgs)
7637 continue;
7638 AttrNonNull.set(Val);
7639 }
7640 }
7641 if (!AttrNonNull.empty())
7642 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007643 if (FD->getParamDecl(i) == PV &&
7644 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007645 std::string Str;
7646 llvm::raw_string_ostream S(Str);
7647 E->printPretty(S, nullptr, getPrintingPolicy());
7648 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7649 : diag::warn_cast_nonnull_to_bool;
7650 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7651 << Range << IsEqual;
7652 return;
7653 }
7654 }
7655 }
7656
Richard Trieu3bb8b562014-02-26 02:36:06 +00007657 QualType T = D->getType();
7658 const bool IsArray = T->isArrayType();
7659 const bool IsFunction = T->isFunctionType();
7660
Richard Trieuc1888e02014-06-28 23:25:37 +00007661 // Address of function is used to silence the function warning.
7662 if (IsAddressOf && IsFunction) {
7663 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007664 }
7665
7666 // Found nothing.
7667 if (!IsAddressOf && !IsFunction && !IsArray)
7668 return;
7669
7670 // Pretty print the expression for the diagnostic.
7671 std::string Str;
7672 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007673 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007674
7675 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7676 : diag::warn_impcast_pointer_to_bool;
7677 unsigned DiagType;
7678 if (IsAddressOf)
7679 DiagType = AddressOf;
7680 else if (IsFunction)
7681 DiagType = FunctionPointer;
7682 else if (IsArray)
7683 DiagType = ArrayPointer;
7684 else
7685 llvm_unreachable("Could not determine diagnostic.");
7686 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7687 << Range << IsEqual;
7688
7689 if (!IsFunction)
7690 return;
7691
7692 // Suggest '&' to silence the function warning.
7693 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7694 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7695
7696 // Check to see if '()' fixit should be emitted.
7697 QualType ReturnType;
7698 UnresolvedSet<4> NonTemplateOverloads;
7699 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7700 if (ReturnType.isNull())
7701 return;
7702
7703 if (IsCompare) {
7704 // There are two cases here. If there is null constant, the only suggest
7705 // for a pointer return type. If the null is 0, then suggest if the return
7706 // type is a pointer or an integer type.
7707 if (!ReturnType->isPointerType()) {
7708 if (NullKind == Expr::NPCK_ZeroExpression ||
7709 NullKind == Expr::NPCK_ZeroLiteral) {
7710 if (!ReturnType->isIntegerType())
7711 return;
7712 } else {
7713 return;
7714 }
7715 }
7716 } else { // !IsCompare
7717 // For function to bool, only suggest if the function pointer has bool
7718 // return type.
7719 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7720 return;
7721 }
7722 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007723 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007724}
7725
7726
John McCallcc7e5bf2010-05-06 08:58:33 +00007727/// Diagnoses "dangerous" implicit conversions within the given
7728/// expression (which is a full expression). Implements -Wconversion
7729/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007730///
7731/// \param CC the "context" location of the implicit conversion, i.e.
7732/// the most location of the syntactic entity requiring the implicit
7733/// conversion
7734void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007735 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007736 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007737 return;
7738
7739 // Don't diagnose for value- or type-dependent expressions.
7740 if (E->isTypeDependent() || E->isValueDependent())
7741 return;
7742
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007743 // Check for array bounds violations in cases where the check isn't triggered
7744 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7745 // ArraySubscriptExpr is on the RHS of a variable initialization.
7746 CheckArrayAccess(E);
7747
John McCallacf0ee52010-10-08 02:01:28 +00007748 // This is not the right CC for (e.g.) a variable initialization.
7749 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007750}
7751
Richard Trieu65724892014-11-15 06:37:39 +00007752/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7753/// Input argument E is a logical expression.
7754void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7755 ::CheckBoolLikeConversion(*this, E, CC);
7756}
7757
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007758/// Diagnose when expression is an integer constant expression and its evaluation
7759/// results in integer overflow
7760void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007761 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7762 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007763}
7764
Richard Smithc406cb72013-01-17 01:17:56 +00007765namespace {
7766/// \brief Visitor for expressions which looks for unsequenced operations on the
7767/// same object.
7768class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007769 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7770
Richard Smithc406cb72013-01-17 01:17:56 +00007771 /// \brief A tree of sequenced regions within an expression. Two regions are
7772 /// unsequenced if one is an ancestor or a descendent of the other. When we
7773 /// finish processing an expression with sequencing, such as a comma
7774 /// expression, we fold its tree nodes into its parent, since they are
7775 /// unsequenced with respect to nodes we will visit later.
7776 class SequenceTree {
7777 struct Value {
7778 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7779 unsigned Parent : 31;
7780 bool Merged : 1;
7781 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007782 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007783
7784 public:
7785 /// \brief A region within an expression which may be sequenced with respect
7786 /// to some other region.
7787 class Seq {
7788 explicit Seq(unsigned N) : Index(N) {}
7789 unsigned Index;
7790 friend class SequenceTree;
7791 public:
7792 Seq() : Index(0) {}
7793 };
7794
7795 SequenceTree() { Values.push_back(Value(0)); }
7796 Seq root() const { return Seq(0); }
7797
7798 /// \brief Create a new sequence of operations, which is an unsequenced
7799 /// subset of \p Parent. This sequence of operations is sequenced with
7800 /// respect to other children of \p Parent.
7801 Seq allocate(Seq Parent) {
7802 Values.push_back(Value(Parent.Index));
7803 return Seq(Values.size() - 1);
7804 }
7805
7806 /// \brief Merge a sequence of operations into its parent.
7807 void merge(Seq S) {
7808 Values[S.Index].Merged = true;
7809 }
7810
7811 /// \brief Determine whether two operations are unsequenced. This operation
7812 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7813 /// should have been merged into its parent as appropriate.
7814 bool isUnsequenced(Seq Cur, Seq Old) {
7815 unsigned C = representative(Cur.Index);
7816 unsigned Target = representative(Old.Index);
7817 while (C >= Target) {
7818 if (C == Target)
7819 return true;
7820 C = Values[C].Parent;
7821 }
7822 return false;
7823 }
7824
7825 private:
7826 /// \brief Pick a representative for a sequence.
7827 unsigned representative(unsigned K) {
7828 if (Values[K].Merged)
7829 // Perform path compression as we go.
7830 return Values[K].Parent = representative(Values[K].Parent);
7831 return K;
7832 }
7833 };
7834
7835 /// An object for which we can track unsequenced uses.
7836 typedef NamedDecl *Object;
7837
7838 /// Different flavors of object usage which we track. We only track the
7839 /// least-sequenced usage of each kind.
7840 enum UsageKind {
7841 /// A read of an object. Multiple unsequenced reads are OK.
7842 UK_Use,
7843 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007844 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007845 UK_ModAsValue,
7846 /// A modification of an object which is not sequenced before the value
7847 /// computation of the expression, such as n++.
7848 UK_ModAsSideEffect,
7849
7850 UK_Count = UK_ModAsSideEffect + 1
7851 };
7852
7853 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007854 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007855 Expr *Use;
7856 SequenceTree::Seq Seq;
7857 };
7858
7859 struct UsageInfo {
7860 UsageInfo() : Diagnosed(false) {}
7861 Usage Uses[UK_Count];
7862 /// Have we issued a diagnostic for this variable already?
7863 bool Diagnosed;
7864 };
7865 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7866
7867 Sema &SemaRef;
7868 /// Sequenced regions within the expression.
7869 SequenceTree Tree;
7870 /// Declaration modifications and references which we have seen.
7871 UsageInfoMap UsageMap;
7872 /// The region we are currently within.
7873 SequenceTree::Seq Region;
7874 /// Filled in with declarations which were modified as a side-effect
7875 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007876 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007877 /// Expressions to check later. We defer checking these to reduce
7878 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007879 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007880
7881 /// RAII object wrapping the visitation of a sequenced subexpression of an
7882 /// expression. At the end of this process, the side-effects of the evaluation
7883 /// become sequenced with respect to the value computation of the result, so
7884 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7885 /// UK_ModAsValue.
7886 struct SequencedSubexpression {
7887 SequencedSubexpression(SequenceChecker &Self)
7888 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7889 Self.ModAsSideEffect = &ModAsSideEffect;
7890 }
7891 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007892 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7893 MI != ME; ++MI) {
7894 UsageInfo &U = Self.UsageMap[MI->first];
7895 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7896 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7897 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007898 }
7899 Self.ModAsSideEffect = OldModAsSideEffect;
7900 }
7901
7902 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007903 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7904 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007905 };
7906
Richard Smith40238f02013-06-20 22:21:56 +00007907 /// RAII object wrapping the visitation of a subexpression which we might
7908 /// choose to evaluate as a constant. If any subexpression is evaluated and
7909 /// found to be non-constant, this allows us to suppress the evaluation of
7910 /// the outer expression.
7911 class EvaluationTracker {
7912 public:
7913 EvaluationTracker(SequenceChecker &Self)
7914 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7915 Self.EvalTracker = this;
7916 }
7917 ~EvaluationTracker() {
7918 Self.EvalTracker = Prev;
7919 if (Prev)
7920 Prev->EvalOK &= EvalOK;
7921 }
7922
7923 bool evaluate(const Expr *E, bool &Result) {
7924 if (!EvalOK || E->isValueDependent())
7925 return false;
7926 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7927 return EvalOK;
7928 }
7929
7930 private:
7931 SequenceChecker &Self;
7932 EvaluationTracker *Prev;
7933 bool EvalOK;
7934 } *EvalTracker;
7935
Richard Smithc406cb72013-01-17 01:17:56 +00007936 /// \brief Find the object which is produced by the specified expression,
7937 /// if any.
7938 Object getObject(Expr *E, bool Mod) const {
7939 E = E->IgnoreParenCasts();
7940 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7941 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7942 return getObject(UO->getSubExpr(), Mod);
7943 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7944 if (BO->getOpcode() == BO_Comma)
7945 return getObject(BO->getRHS(), Mod);
7946 if (Mod && BO->isAssignmentOp())
7947 return getObject(BO->getLHS(), Mod);
7948 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7949 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7950 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7951 return ME->getMemberDecl();
7952 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7953 // FIXME: If this is a reference, map through to its value.
7954 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007955 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007956 }
7957
7958 /// \brief Note that an object was modified or used by an expression.
7959 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7960 Usage &U = UI.Uses[UK];
7961 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7962 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7963 ModAsSideEffect->push_back(std::make_pair(O, U));
7964 U.Use = Ref;
7965 U.Seq = Region;
7966 }
7967 }
7968 /// \brief Check whether a modification or use conflicts with a prior usage.
7969 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7970 bool IsModMod) {
7971 if (UI.Diagnosed)
7972 return;
7973
7974 const Usage &U = UI.Uses[OtherKind];
7975 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7976 return;
7977
7978 Expr *Mod = U.Use;
7979 Expr *ModOrUse = Ref;
7980 if (OtherKind == UK_Use)
7981 std::swap(Mod, ModOrUse);
7982
7983 SemaRef.Diag(Mod->getExprLoc(),
7984 IsModMod ? diag::warn_unsequenced_mod_mod
7985 : diag::warn_unsequenced_mod_use)
7986 << O << SourceRange(ModOrUse->getExprLoc());
7987 UI.Diagnosed = true;
7988 }
7989
7990 void notePreUse(Object O, Expr *Use) {
7991 UsageInfo &U = UsageMap[O];
7992 // Uses conflict with other modifications.
7993 checkUsage(O, U, Use, UK_ModAsValue, false);
7994 }
7995 void notePostUse(Object O, Expr *Use) {
7996 UsageInfo &U = UsageMap[O];
7997 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7998 addUsage(U, O, Use, UK_Use);
7999 }
8000
8001 void notePreMod(Object O, Expr *Mod) {
8002 UsageInfo &U = UsageMap[O];
8003 // Modifications conflict with other modifications and with uses.
8004 checkUsage(O, U, Mod, UK_ModAsValue, true);
8005 checkUsage(O, U, Mod, UK_Use, false);
8006 }
8007 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8008 UsageInfo &U = UsageMap[O];
8009 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8010 addUsage(U, O, Use, UK);
8011 }
8012
8013public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008014 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008015 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8016 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008017 Visit(E);
8018 }
8019
8020 void VisitStmt(Stmt *S) {
8021 // Skip all statements which aren't expressions for now.
8022 }
8023
8024 void VisitExpr(Expr *E) {
8025 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008026 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008027 }
8028
8029 void VisitCastExpr(CastExpr *E) {
8030 Object O = Object();
8031 if (E->getCastKind() == CK_LValueToRValue)
8032 O = getObject(E->getSubExpr(), false);
8033
8034 if (O)
8035 notePreUse(O, E);
8036 VisitExpr(E);
8037 if (O)
8038 notePostUse(O, E);
8039 }
8040
8041 void VisitBinComma(BinaryOperator *BO) {
8042 // C++11 [expr.comma]p1:
8043 // Every value computation and side effect associated with the left
8044 // expression is sequenced before every value computation and side
8045 // effect associated with the right expression.
8046 SequenceTree::Seq LHS = Tree.allocate(Region);
8047 SequenceTree::Seq RHS = Tree.allocate(Region);
8048 SequenceTree::Seq OldRegion = Region;
8049
8050 {
8051 SequencedSubexpression SeqLHS(*this);
8052 Region = LHS;
8053 Visit(BO->getLHS());
8054 }
8055
8056 Region = RHS;
8057 Visit(BO->getRHS());
8058
8059 Region = OldRegion;
8060
8061 // Forget that LHS and RHS are sequenced. They are both unsequenced
8062 // with respect to other stuff.
8063 Tree.merge(LHS);
8064 Tree.merge(RHS);
8065 }
8066
8067 void VisitBinAssign(BinaryOperator *BO) {
8068 // The modification is sequenced after the value computation of the LHS
8069 // and RHS, so check it before inspecting the operands and update the
8070 // map afterwards.
8071 Object O = getObject(BO->getLHS(), true);
8072 if (!O)
8073 return VisitExpr(BO);
8074
8075 notePreMod(O, BO);
8076
8077 // C++11 [expr.ass]p7:
8078 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8079 // only once.
8080 //
8081 // Therefore, for a compound assignment operator, O is considered used
8082 // everywhere except within the evaluation of E1 itself.
8083 if (isa<CompoundAssignOperator>(BO))
8084 notePreUse(O, BO);
8085
8086 Visit(BO->getLHS());
8087
8088 if (isa<CompoundAssignOperator>(BO))
8089 notePostUse(O, BO);
8090
8091 Visit(BO->getRHS());
8092
Richard Smith83e37bee2013-06-26 23:16:51 +00008093 // C++11 [expr.ass]p1:
8094 // the assignment is sequenced [...] before the value computation of the
8095 // assignment expression.
8096 // C11 6.5.16/3 has no such rule.
8097 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8098 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008099 }
8100 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8101 VisitBinAssign(CAO);
8102 }
8103
8104 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8105 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8106 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8107 Object O = getObject(UO->getSubExpr(), true);
8108 if (!O)
8109 return VisitExpr(UO);
8110
8111 notePreMod(O, UO);
8112 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008113 // C++11 [expr.pre.incr]p1:
8114 // the expression ++x is equivalent to x+=1
8115 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8116 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008117 }
8118
8119 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8120 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8121 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8122 Object O = getObject(UO->getSubExpr(), true);
8123 if (!O)
8124 return VisitExpr(UO);
8125
8126 notePreMod(O, UO);
8127 Visit(UO->getSubExpr());
8128 notePostMod(O, UO, UK_ModAsSideEffect);
8129 }
8130
8131 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8132 void VisitBinLOr(BinaryOperator *BO) {
8133 // The side-effects of the LHS of an '&&' are sequenced before the
8134 // value computation of the RHS, and hence before the value computation
8135 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8136 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008137 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008138 {
8139 SequencedSubexpression Sequenced(*this);
8140 Visit(BO->getLHS());
8141 }
8142
8143 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008144 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008145 if (!Result)
8146 Visit(BO->getRHS());
8147 } else {
8148 // Check for unsequenced operations in the RHS, treating it as an
8149 // entirely separate evaluation.
8150 //
8151 // FIXME: If there are operations in the RHS which are unsequenced
8152 // with respect to operations outside the RHS, and those operations
8153 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008154 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008155 }
Richard Smithc406cb72013-01-17 01:17:56 +00008156 }
8157 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008158 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008159 {
8160 SequencedSubexpression Sequenced(*this);
8161 Visit(BO->getLHS());
8162 }
8163
8164 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008165 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008166 if (Result)
8167 Visit(BO->getRHS());
8168 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008169 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008170 }
Richard Smithc406cb72013-01-17 01:17:56 +00008171 }
8172
8173 // Only visit the condition, unless we can be sure which subexpression will
8174 // be chosen.
8175 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008176 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008177 {
8178 SequencedSubexpression Sequenced(*this);
8179 Visit(CO->getCond());
8180 }
Richard Smithc406cb72013-01-17 01:17:56 +00008181
8182 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008183 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008184 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008185 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008186 WorkList.push_back(CO->getTrueExpr());
8187 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008188 }
Richard Smithc406cb72013-01-17 01:17:56 +00008189 }
8190
Richard Smithe3dbfe02013-06-30 10:40:20 +00008191 void VisitCallExpr(CallExpr *CE) {
8192 // C++11 [intro.execution]p15:
8193 // When calling a function [...], every value computation and side effect
8194 // associated with any argument expression, or with the postfix expression
8195 // designating the called function, is sequenced before execution of every
8196 // expression or statement in the body of the function [and thus before
8197 // the value computation of its result].
8198 SequencedSubexpression Sequenced(*this);
8199 Base::VisitCallExpr(CE);
8200
8201 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8202 }
8203
Richard Smithc406cb72013-01-17 01:17:56 +00008204 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008205 // This is a call, so all subexpressions are sequenced before the result.
8206 SequencedSubexpression Sequenced(*this);
8207
Richard Smithc406cb72013-01-17 01:17:56 +00008208 if (!CCE->isListInitialization())
8209 return VisitExpr(CCE);
8210
8211 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008212 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008213 SequenceTree::Seq Parent = Region;
8214 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8215 E = CCE->arg_end();
8216 I != E; ++I) {
8217 Region = Tree.allocate(Parent);
8218 Elts.push_back(Region);
8219 Visit(*I);
8220 }
8221
8222 // Forget that the initializers are sequenced.
8223 Region = Parent;
8224 for (unsigned I = 0; I < Elts.size(); ++I)
8225 Tree.merge(Elts[I]);
8226 }
8227
8228 void VisitInitListExpr(InitListExpr *ILE) {
8229 if (!SemaRef.getLangOpts().CPlusPlus11)
8230 return VisitExpr(ILE);
8231
8232 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008233 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008234 SequenceTree::Seq Parent = Region;
8235 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8236 Expr *E = ILE->getInit(I);
8237 if (!E) continue;
8238 Region = Tree.allocate(Parent);
8239 Elts.push_back(Region);
8240 Visit(E);
8241 }
8242
8243 // Forget that the initializers are sequenced.
8244 Region = Parent;
8245 for (unsigned I = 0; I < Elts.size(); ++I)
8246 Tree.merge(Elts[I]);
8247 }
8248};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008249}
Richard Smithc406cb72013-01-17 01:17:56 +00008250
8251void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008252 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008253 WorkList.push_back(E);
8254 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008255 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008256 SequenceChecker(*this, Item, WorkList);
8257 }
Richard Smithc406cb72013-01-17 01:17:56 +00008258}
8259
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008260void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8261 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008262 CheckImplicitConversions(E, CheckLoc);
8263 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008264 if (!IsConstexpr && !E->isValueDependent())
8265 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008266}
8267
John McCall1f425642010-11-11 03:21:53 +00008268void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8269 FieldDecl *BitField,
8270 Expr *Init) {
8271 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8272}
8273
David Majnemer61a5bbf2015-04-07 22:08:51 +00008274static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8275 SourceLocation Loc) {
8276 if (!PType->isVariablyModifiedType())
8277 return;
8278 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8279 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8280 return;
8281 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008282 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8283 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8284 return;
8285 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008286 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8287 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8288 return;
8289 }
8290
8291 const ArrayType *AT = S.Context.getAsArrayType(PType);
8292 if (!AT)
8293 return;
8294
8295 if (AT->getSizeModifier() != ArrayType::Star) {
8296 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8297 return;
8298 }
8299
8300 S.Diag(Loc, diag::err_array_star_in_function_definition);
8301}
8302
Mike Stump0c2ec772010-01-21 03:59:47 +00008303/// CheckParmsForFunctionDef - Check that the parameters of the given
8304/// function are appropriate for the definition of a function. This
8305/// takes care of any checks that cannot be performed on the
8306/// declaration itself, e.g., that the types of each of the function
8307/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008308bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8309 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008310 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008311 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008312 for (; P != PEnd; ++P) {
8313 ParmVarDecl *Param = *P;
8314
Mike Stump0c2ec772010-01-21 03:59:47 +00008315 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8316 // function declarator that is part of a function definition of
8317 // that function shall not have incomplete type.
8318 //
8319 // This is also C++ [dcl.fct]p6.
8320 if (!Param->isInvalidDecl() &&
8321 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008322 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008323 Param->setInvalidDecl();
8324 HasInvalidParm = true;
8325 }
8326
8327 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8328 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008329 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008330 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008331 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008332 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008333 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008334
8335 // C99 6.7.5.3p12:
8336 // If the function declarator is not part of a definition of that
8337 // function, parameters may have incomplete type and may use the [*]
8338 // notation in their sequences of declarator specifiers to specify
8339 // variable length array types.
8340 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008341 // FIXME: This diagnostic should point the '[*]' if source-location
8342 // information is added for it.
8343 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008344
8345 // MSVC destroys objects passed by value in the callee. Therefore a
8346 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008347 // object's destructor. However, we don't perform any direct access check
8348 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008349 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8350 .getCXXABI()
8351 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008352 if (!Param->isInvalidDecl()) {
8353 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8354 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8355 if (!ClassDecl->isInvalidDecl() &&
8356 !ClassDecl->hasIrrelevantDestructor() &&
8357 !ClassDecl->isDependentContext()) {
8358 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8359 MarkFunctionReferenced(Param->getLocation(), Destructor);
8360 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8361 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008362 }
8363 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008364 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008365 }
8366
8367 return HasInvalidParm;
8368}
John McCall2b5c1b22010-08-12 21:44:57 +00008369
8370/// CheckCastAlign - Implements -Wcast-align, which warns when a
8371/// pointer cast increases the alignment requirements.
8372void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8373 // This is actually a lot of work to potentially be doing on every
8374 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008375 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008376 return;
8377
8378 // Ignore dependent types.
8379 if (T->isDependentType() || Op->getType()->isDependentType())
8380 return;
8381
8382 // Require that the destination be a pointer type.
8383 const PointerType *DestPtr = T->getAs<PointerType>();
8384 if (!DestPtr) return;
8385
8386 // If the destination has alignment 1, we're done.
8387 QualType DestPointee = DestPtr->getPointeeType();
8388 if (DestPointee->isIncompleteType()) return;
8389 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8390 if (DestAlign.isOne()) return;
8391
8392 // Require that the source be a pointer type.
8393 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8394 if (!SrcPtr) return;
8395 QualType SrcPointee = SrcPtr->getPointeeType();
8396
8397 // Whitelist casts from cv void*. We already implicitly
8398 // whitelisted casts to cv void*, since they have alignment 1.
8399 // Also whitelist casts involving incomplete types, which implicitly
8400 // includes 'void'.
8401 if (SrcPointee->isIncompleteType()) return;
8402
8403 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8404 if (SrcAlign >= DestAlign) return;
8405
8406 Diag(TRange.getBegin(), diag::warn_cast_align)
8407 << Op->getType() << T
8408 << static_cast<unsigned>(SrcAlign.getQuantity())
8409 << static_cast<unsigned>(DestAlign.getQuantity())
8410 << TRange << Op->getSourceRange();
8411}
8412
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008413static const Type* getElementType(const Expr *BaseExpr) {
8414 const Type* EltType = BaseExpr->getType().getTypePtr();
8415 if (EltType->isAnyPointerType())
8416 return EltType->getPointeeType().getTypePtr();
8417 else if (EltType->isArrayType())
8418 return EltType->getBaseElementTypeUnsafe();
8419 return EltType;
8420}
8421
Chandler Carruth28389f02011-08-05 09:10:50 +00008422/// \brief Check whether this array fits the idiom of a size-one tail padded
8423/// array member of a struct.
8424///
8425/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8426/// commonly used to emulate flexible arrays in C89 code.
8427static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8428 const NamedDecl *ND) {
8429 if (Size != 1 || !ND) return false;
8430
8431 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8432 if (!FD) return false;
8433
8434 // Don't consider sizes resulting from macro expansions or template argument
8435 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008436
8437 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008438 while (TInfo) {
8439 TypeLoc TL = TInfo->getTypeLoc();
8440 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008441 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8442 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008443 TInfo = TDL->getTypeSourceInfo();
8444 continue;
8445 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008446 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8447 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008448 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8449 return false;
8450 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008451 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008452 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008453
8454 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008455 if (!RD) return false;
8456 if (RD->isUnion()) return false;
8457 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8458 if (!CRD->isStandardLayout()) return false;
8459 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008460
Benjamin Kramer8c543672011-08-06 03:04:42 +00008461 // See if this is the last field decl in the record.
8462 const Decl *D = FD;
8463 while ((D = D->getNextDeclInContext()))
8464 if (isa<FieldDecl>(D))
8465 return false;
8466 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008467}
8468
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008469void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008470 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008471 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008472 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008473 if (IndexExpr->isValueDependent())
8474 return;
8475
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008476 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008477 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008478 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008479 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008480 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008481 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008482
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008483 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008484 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008485 return;
Richard Smith13f67182011-12-16 19:31:14 +00008486 if (IndexNegated)
8487 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008488
Craig Topperc3ec1492014-05-26 06:22:03 +00008489 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008490 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8491 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008492 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008493 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008494
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008495 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008496 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008497 if (!size.isStrictlyPositive())
8498 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008499
8500 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008501 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008502 // Make sure we're comparing apples to apples when comparing index to size
8503 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8504 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008505 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008506 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008507 if (ptrarith_typesize != array_typesize) {
8508 // There's a cast to a different size type involved
8509 uint64_t ratio = array_typesize / ptrarith_typesize;
8510 // TODO: Be smarter about handling cases where array_typesize is not a
8511 // multiple of ptrarith_typesize
8512 if (ptrarith_typesize * ratio == array_typesize)
8513 size *= llvm::APInt(size.getBitWidth(), ratio);
8514 }
8515 }
8516
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008517 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008518 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008519 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008520 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008521
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008522 // For array subscripting the index must be less than size, but for pointer
8523 // arithmetic also allow the index (offset) to be equal to size since
8524 // computing the next address after the end of the array is legal and
8525 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008526 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008527 return;
8528
8529 // Also don't warn for arrays of size 1 which are members of some
8530 // structure. These are often used to approximate flexible arrays in C89
8531 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008532 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008533 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008534
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008535 // Suppress the warning if the subscript expression (as identified by the
8536 // ']' location) and the index expression are both from macro expansions
8537 // within a system header.
8538 if (ASE) {
8539 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8540 ASE->getRBracketLoc());
8541 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8542 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8543 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008544 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008545 return;
8546 }
8547 }
8548
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008549 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008550 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008551 DiagID = diag::warn_array_index_exceeds_bounds;
8552
8553 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8554 PDiag(DiagID) << index.toString(10, true)
8555 << size.toString(10, true)
8556 << (unsigned)size.getLimitedValue(~0U)
8557 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008558 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008559 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008560 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008561 DiagID = diag::warn_ptr_arith_precedes_bounds;
8562 if (index.isNegative()) index = -index;
8563 }
8564
8565 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8566 PDiag(DiagID) << index.toString(10, true)
8567 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008568 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008569
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008570 if (!ND) {
8571 // Try harder to find a NamedDecl to point at in the note.
8572 while (const ArraySubscriptExpr *ASE =
8573 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8574 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8575 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8576 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8577 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8578 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8579 }
8580
Chandler Carruth1af88f12011-02-17 21:10:52 +00008581 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008582 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8583 PDiag(diag::note_array_index_out_of_bounds)
8584 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008585}
8586
Ted Kremenekdf26df72011-03-01 18:41:00 +00008587void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008588 int AllowOnePastEnd = 0;
8589 while (expr) {
8590 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008591 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008592 case Stmt::ArraySubscriptExprClass: {
8593 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008594 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008595 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008596 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008597 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008598 case Stmt::OMPArraySectionExprClass: {
8599 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8600 if (ASE->getLowerBound())
8601 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8602 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8603 return;
8604 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008605 case Stmt::UnaryOperatorClass: {
8606 // Only unwrap the * and & unary operators
8607 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8608 expr = UO->getSubExpr();
8609 switch (UO->getOpcode()) {
8610 case UO_AddrOf:
8611 AllowOnePastEnd++;
8612 break;
8613 case UO_Deref:
8614 AllowOnePastEnd--;
8615 break;
8616 default:
8617 return;
8618 }
8619 break;
8620 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008621 case Stmt::ConditionalOperatorClass: {
8622 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8623 if (const Expr *lhs = cond->getLHS())
8624 CheckArrayAccess(lhs);
8625 if (const Expr *rhs = cond->getRHS())
8626 CheckArrayAccess(rhs);
8627 return;
8628 }
8629 default:
8630 return;
8631 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008632 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008633}
John McCall31168b02011-06-15 23:02:42 +00008634
8635//===--- CHECK: Objective-C retain cycles ----------------------------------//
8636
8637namespace {
8638 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008639 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008640 VarDecl *Variable;
8641 SourceRange Range;
8642 SourceLocation Loc;
8643 bool Indirect;
8644
8645 void setLocsFrom(Expr *e) {
8646 Loc = e->getExprLoc();
8647 Range = e->getSourceRange();
8648 }
8649 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008650}
John McCall31168b02011-06-15 23:02:42 +00008651
8652/// Consider whether capturing the given variable can possibly lead to
8653/// a retain cycle.
8654static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008655 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008656 // lifetime. In MRR, it's captured strongly if the variable is
8657 // __block and has an appropriate type.
8658 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8659 return false;
8660
8661 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008662 if (ref)
8663 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008664 return true;
8665}
8666
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008667static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008668 while (true) {
8669 e = e->IgnoreParens();
8670 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8671 switch (cast->getCastKind()) {
8672 case CK_BitCast:
8673 case CK_LValueBitCast:
8674 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008675 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008676 e = cast->getSubExpr();
8677 continue;
8678
John McCall31168b02011-06-15 23:02:42 +00008679 default:
8680 return false;
8681 }
8682 }
8683
8684 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8685 ObjCIvarDecl *ivar = ref->getDecl();
8686 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8687 return false;
8688
8689 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008690 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008691 return false;
8692
8693 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8694 owner.Indirect = true;
8695 return true;
8696 }
8697
8698 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8699 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8700 if (!var) return false;
8701 return considerVariable(var, ref, owner);
8702 }
8703
John McCall31168b02011-06-15 23:02:42 +00008704 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8705 if (member->isArrow()) return false;
8706
8707 // Don't count this as an indirect ownership.
8708 e = member->getBase();
8709 continue;
8710 }
8711
John McCallfe96e0b2011-11-06 09:01:30 +00008712 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8713 // Only pay attention to pseudo-objects on property references.
8714 ObjCPropertyRefExpr *pre
8715 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8716 ->IgnoreParens());
8717 if (!pre) return false;
8718 if (pre->isImplicitProperty()) return false;
8719 ObjCPropertyDecl *property = pre->getExplicitProperty();
8720 if (!property->isRetaining() &&
8721 !(property->getPropertyIvarDecl() &&
8722 property->getPropertyIvarDecl()->getType()
8723 .getObjCLifetime() == Qualifiers::OCL_Strong))
8724 return false;
8725
8726 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008727 if (pre->isSuperReceiver()) {
8728 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8729 if (!owner.Variable)
8730 return false;
8731 owner.Loc = pre->getLocation();
8732 owner.Range = pre->getSourceRange();
8733 return true;
8734 }
John McCallfe96e0b2011-11-06 09:01:30 +00008735 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8736 ->getSourceExpr());
8737 continue;
8738 }
8739
John McCall31168b02011-06-15 23:02:42 +00008740 // Array ivars?
8741
8742 return false;
8743 }
8744}
8745
8746namespace {
8747 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8748 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8749 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008750 Context(Context), Variable(variable), Capturer(nullptr),
8751 VarWillBeReased(false) {}
8752 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008753 VarDecl *Variable;
8754 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008755 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008756
8757 void VisitDeclRefExpr(DeclRefExpr *ref) {
8758 if (ref->getDecl() == Variable && !Capturer)
8759 Capturer = ref;
8760 }
8761
John McCall31168b02011-06-15 23:02:42 +00008762 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8763 if (Capturer) return;
8764 Visit(ref->getBase());
8765 if (Capturer && ref->isFreeIvar())
8766 Capturer = ref;
8767 }
8768
8769 void VisitBlockExpr(BlockExpr *block) {
8770 // Look inside nested blocks
8771 if (block->getBlockDecl()->capturesVariable(Variable))
8772 Visit(block->getBlockDecl()->getBody());
8773 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008774
8775 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8776 if (Capturer) return;
8777 if (OVE->getSourceExpr())
8778 Visit(OVE->getSourceExpr());
8779 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008780 void VisitBinaryOperator(BinaryOperator *BinOp) {
8781 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8782 return;
8783 Expr *LHS = BinOp->getLHS();
8784 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8785 if (DRE->getDecl() != Variable)
8786 return;
8787 if (Expr *RHS = BinOp->getRHS()) {
8788 RHS = RHS->IgnoreParenCasts();
8789 llvm::APSInt Value;
8790 VarWillBeReased =
8791 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8792 }
8793 }
8794 }
John McCall31168b02011-06-15 23:02:42 +00008795 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008796}
John McCall31168b02011-06-15 23:02:42 +00008797
8798/// Check whether the given argument is a block which captures a
8799/// variable.
8800static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8801 assert(owner.Variable && owner.Loc.isValid());
8802
8803 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008804
8805 // Look through [^{...} copy] and Block_copy(^{...}).
8806 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8807 Selector Cmd = ME->getSelector();
8808 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8809 e = ME->getInstanceReceiver();
8810 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008811 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008812 e = e->IgnoreParenCasts();
8813 }
8814 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8815 if (CE->getNumArgs() == 1) {
8816 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008817 if (Fn) {
8818 const IdentifierInfo *FnI = Fn->getIdentifier();
8819 if (FnI && FnI->isStr("_Block_copy")) {
8820 e = CE->getArg(0)->IgnoreParenCasts();
8821 }
8822 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008823 }
8824 }
8825
John McCall31168b02011-06-15 23:02:42 +00008826 BlockExpr *block = dyn_cast<BlockExpr>(e);
8827 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008828 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008829
8830 FindCaptureVisitor visitor(S.Context, owner.Variable);
8831 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008832 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008833}
8834
8835static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8836 RetainCycleOwner &owner) {
8837 assert(capturer);
8838 assert(owner.Variable && owner.Loc.isValid());
8839
8840 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8841 << owner.Variable << capturer->getSourceRange();
8842 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8843 << owner.Indirect << owner.Range;
8844}
8845
8846/// Check for a keyword selector that starts with the word 'add' or
8847/// 'set'.
8848static bool isSetterLikeSelector(Selector sel) {
8849 if (sel.isUnarySelector()) return false;
8850
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008851 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008852 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008853 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008854 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008855 else if (str.startswith("add")) {
8856 // Specially whitelist 'addOperationWithBlock:'.
8857 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8858 return false;
8859 str = str.substr(3);
8860 }
John McCall31168b02011-06-15 23:02:42 +00008861 else
8862 return false;
8863
8864 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008865 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008866}
8867
Benjamin Kramer3a743452015-03-09 15:03:32 +00008868static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8869 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008870 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8871 Message->getReceiverInterface(),
8872 NSAPI::ClassId_NSMutableArray);
8873 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008874 return None;
8875 }
8876
8877 Selector Sel = Message->getSelector();
8878
8879 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8880 S.NSAPIObj->getNSArrayMethodKind(Sel);
8881 if (!MKOpt) {
8882 return None;
8883 }
8884
8885 NSAPI::NSArrayMethodKind MK = *MKOpt;
8886
8887 switch (MK) {
8888 case NSAPI::NSMutableArr_addObject:
8889 case NSAPI::NSMutableArr_insertObjectAtIndex:
8890 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8891 return 0;
8892 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8893 return 1;
8894
8895 default:
8896 return None;
8897 }
8898
8899 return None;
8900}
8901
8902static
8903Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8904 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008905 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8906 Message->getReceiverInterface(),
8907 NSAPI::ClassId_NSMutableDictionary);
8908 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008909 return None;
8910 }
8911
8912 Selector Sel = Message->getSelector();
8913
8914 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8915 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8916 if (!MKOpt) {
8917 return None;
8918 }
8919
8920 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8921
8922 switch (MK) {
8923 case NSAPI::NSMutableDict_setObjectForKey:
8924 case NSAPI::NSMutableDict_setValueForKey:
8925 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8926 return 0;
8927
8928 default:
8929 return None;
8930 }
8931
8932 return None;
8933}
8934
8935static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008936 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8937 Message->getReceiverInterface(),
8938 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00008939
Alex Denisov5dfac812015-08-06 04:51:14 +00008940 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8941 Message->getReceiverInterface(),
8942 NSAPI::ClassId_NSMutableOrderedSet);
8943 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008944 return None;
8945 }
8946
8947 Selector Sel = Message->getSelector();
8948
8949 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8950 if (!MKOpt) {
8951 return None;
8952 }
8953
8954 NSAPI::NSSetMethodKind MK = *MKOpt;
8955
8956 switch (MK) {
8957 case NSAPI::NSMutableSet_addObject:
8958 case NSAPI::NSOrderedSet_setObjectAtIndex:
8959 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8960 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8961 return 0;
8962 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8963 return 1;
8964 }
8965
8966 return None;
8967}
8968
8969void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8970 if (!Message->isInstanceMessage()) {
8971 return;
8972 }
8973
8974 Optional<int> ArgOpt;
8975
8976 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8977 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8978 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8979 return;
8980 }
8981
8982 int ArgIndex = *ArgOpt;
8983
Alex Denisove1d882c2015-03-04 17:55:52 +00008984 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8985 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8986 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8987 }
8988
Alex Denisov5dfac812015-08-06 04:51:14 +00008989 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008990 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008991 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008992 Diag(Message->getSourceRange().getBegin(),
8993 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00008994 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00008995 }
8996 }
Alex Denisov5dfac812015-08-06 04:51:14 +00008997 } else {
8998 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8999
9000 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9001 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9002 }
9003
9004 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9005 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9006 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9007 ValueDecl *Decl = ReceiverRE->getDecl();
9008 Diag(Message->getSourceRange().getBegin(),
9009 diag::warn_objc_circular_container)
9010 << Decl->getName() << Decl->getName();
9011 if (!ArgRE->isObjCSelfExpr()) {
9012 Diag(Decl->getLocation(),
9013 diag::note_objc_circular_container_declared_here)
9014 << Decl->getName();
9015 }
9016 }
9017 }
9018 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9019 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9020 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9021 ObjCIvarDecl *Decl = IvarRE->getDecl();
9022 Diag(Message->getSourceRange().getBegin(),
9023 diag::warn_objc_circular_container)
9024 << Decl->getName() << Decl->getName();
9025 Diag(Decl->getLocation(),
9026 diag::note_objc_circular_container_declared_here)
9027 << Decl->getName();
9028 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009029 }
9030 }
9031 }
9032
9033}
9034
John McCall31168b02011-06-15 23:02:42 +00009035/// Check a message send to see if it's likely to cause a retain cycle.
9036void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9037 // Only check instance methods whose selector looks like a setter.
9038 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9039 return;
9040
9041 // Try to find a variable that the receiver is strongly owned by.
9042 RetainCycleOwner owner;
9043 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009044 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009045 return;
9046 } else {
9047 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9048 owner.Variable = getCurMethodDecl()->getSelfDecl();
9049 owner.Loc = msg->getSuperLoc();
9050 owner.Range = msg->getSuperLoc();
9051 }
9052
9053 // Check whether the receiver is captured by any of the arguments.
9054 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9055 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9056 return diagnoseRetainCycle(*this, capturer, owner);
9057}
9058
9059/// Check a property assign to see if it's likely to cause a retain cycle.
9060void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9061 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009062 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009063 return;
9064
9065 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9066 diagnoseRetainCycle(*this, capturer, owner);
9067}
9068
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009069void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9070 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009071 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009072 return;
9073
9074 // Because we don't have an expression for the variable, we have to set the
9075 // location explicitly here.
9076 Owner.Loc = Var->getLocation();
9077 Owner.Range = Var->getSourceRange();
9078
9079 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9080 diagnoseRetainCycle(*this, Capturer, Owner);
9081}
9082
Ted Kremenek9304da92012-12-21 08:04:28 +00009083static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9084 Expr *RHS, bool isProperty) {
9085 // Check if RHS is an Objective-C object literal, which also can get
9086 // immediately zapped in a weak reference. Note that we explicitly
9087 // allow ObjCStringLiterals, since those are designed to never really die.
9088 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009089
Ted Kremenek64873352012-12-21 22:46:35 +00009090 // This enum needs to match with the 'select' in
9091 // warn_objc_arc_literal_assign (off-by-1).
9092 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9093 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9094 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009095
9096 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009097 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009098 << (isProperty ? 0 : 1)
9099 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009100
9101 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009102}
9103
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009104static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9105 Qualifiers::ObjCLifetime LT,
9106 Expr *RHS, bool isProperty) {
9107 // Strip off any implicit cast added to get to the one ARC-specific.
9108 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9109 if (cast->getCastKind() == CK_ARCConsumeObject) {
9110 S.Diag(Loc, diag::warn_arc_retained_assign)
9111 << (LT == Qualifiers::OCL_ExplicitNone)
9112 << (isProperty ? 0 : 1)
9113 << RHS->getSourceRange();
9114 return true;
9115 }
9116 RHS = cast->getSubExpr();
9117 }
9118
9119 if (LT == Qualifiers::OCL_Weak &&
9120 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9121 return true;
9122
9123 return false;
9124}
9125
Ted Kremenekb36234d2012-12-21 08:04:20 +00009126bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9127 QualType LHS, Expr *RHS) {
9128 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9129
9130 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9131 return false;
9132
9133 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9134 return true;
9135
9136 return false;
9137}
9138
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009139void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9140 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009141 QualType LHSType;
9142 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009143 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009144 ObjCPropertyRefExpr *PRE
9145 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9146 if (PRE && !PRE->isImplicitProperty()) {
9147 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9148 if (PD)
9149 LHSType = PD->getType();
9150 }
9151
9152 if (LHSType.isNull())
9153 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009154
9155 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9156
9157 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009158 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009159 getCurFunction()->markSafeWeakUse(LHS);
9160 }
9161
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009162 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9163 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009164
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009165 // FIXME. Check for other life times.
9166 if (LT != Qualifiers::OCL_None)
9167 return;
9168
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009169 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009170 if (PRE->isImplicitProperty())
9171 return;
9172 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9173 if (!PD)
9174 return;
9175
Bill Wendling44426052012-12-20 19:22:21 +00009176 unsigned Attributes = PD->getPropertyAttributes();
9177 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009178 // when 'assign' attribute was not explicitly specified
9179 // by user, ignore it and rely on property type itself
9180 // for lifetime info.
9181 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9182 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9183 LHSType->isObjCRetainableType())
9184 return;
9185
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009186 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009187 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009188 Diag(Loc, diag::warn_arc_retained_property_assign)
9189 << RHS->getSourceRange();
9190 return;
9191 }
9192 RHS = cast->getSubExpr();
9193 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009194 }
Bill Wendling44426052012-12-20 19:22:21 +00009195 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009196 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9197 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009198 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009199 }
9200}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009201
9202//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9203
9204namespace {
9205bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9206 SourceLocation StmtLoc,
9207 const NullStmt *Body) {
9208 // Do not warn if the body is a macro that expands to nothing, e.g:
9209 //
9210 // #define CALL(x)
9211 // if (condition)
9212 // CALL(0);
9213 //
9214 if (Body->hasLeadingEmptyMacro())
9215 return false;
9216
9217 // Get line numbers of statement and body.
9218 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009219 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009220 &StmtLineInvalid);
9221 if (StmtLineInvalid)
9222 return false;
9223
9224 bool BodyLineInvalid;
9225 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9226 &BodyLineInvalid);
9227 if (BodyLineInvalid)
9228 return false;
9229
9230 // Warn if null statement and body are on the same line.
9231 if (StmtLine != BodyLine)
9232 return false;
9233
9234 return true;
9235}
9236} // Unnamed namespace
9237
9238void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9239 const Stmt *Body,
9240 unsigned DiagID) {
9241 // Since this is a syntactic check, don't emit diagnostic for template
9242 // instantiations, this just adds noise.
9243 if (CurrentInstantiationScope)
9244 return;
9245
9246 // The body should be a null statement.
9247 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9248 if (!NBody)
9249 return;
9250
9251 // Do the usual checks.
9252 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9253 return;
9254
9255 Diag(NBody->getSemiLoc(), DiagID);
9256 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9257}
9258
9259void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9260 const Stmt *PossibleBody) {
9261 assert(!CurrentInstantiationScope); // Ensured by caller
9262
9263 SourceLocation StmtLoc;
9264 const Stmt *Body;
9265 unsigned DiagID;
9266 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9267 StmtLoc = FS->getRParenLoc();
9268 Body = FS->getBody();
9269 DiagID = diag::warn_empty_for_body;
9270 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9271 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9272 Body = WS->getBody();
9273 DiagID = diag::warn_empty_while_body;
9274 } else
9275 return; // Neither `for' nor `while'.
9276
9277 // The body should be a null statement.
9278 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9279 if (!NBody)
9280 return;
9281
9282 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009283 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009284 return;
9285
9286 // Do the usual checks.
9287 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9288 return;
9289
9290 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9291 // noise level low, emit diagnostics only if for/while is followed by a
9292 // CompoundStmt, e.g.:
9293 // for (int i = 0; i < n; i++);
9294 // {
9295 // a(i);
9296 // }
9297 // or if for/while is followed by a statement with more indentation
9298 // than for/while itself:
9299 // for (int i = 0; i < n; i++);
9300 // a(i);
9301 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9302 if (!ProbableTypo) {
9303 bool BodyColInvalid;
9304 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9305 PossibleBody->getLocStart(),
9306 &BodyColInvalid);
9307 if (BodyColInvalid)
9308 return;
9309
9310 bool StmtColInvalid;
9311 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9312 S->getLocStart(),
9313 &StmtColInvalid);
9314 if (StmtColInvalid)
9315 return;
9316
9317 if (BodyCol > StmtCol)
9318 ProbableTypo = true;
9319 }
9320
9321 if (ProbableTypo) {
9322 Diag(NBody->getSemiLoc(), DiagID);
9323 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9324 }
9325}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009326
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009327//===--- CHECK: Warn on self move with std::move. -------------------------===//
9328
9329/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9330void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9331 SourceLocation OpLoc) {
9332
9333 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9334 return;
9335
9336 if (!ActiveTemplateInstantiations.empty())
9337 return;
9338
9339 // Strip parens and casts away.
9340 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9341 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9342
9343 // Check for a call expression
9344 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9345 if (!CE || CE->getNumArgs() != 1)
9346 return;
9347
9348 // Check for a call to std::move
9349 const FunctionDecl *FD = CE->getDirectCallee();
9350 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9351 !FD->getIdentifier()->isStr("move"))
9352 return;
9353
9354 // Get argument from std::move
9355 RHSExpr = CE->getArg(0);
9356
9357 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9358 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9359
9360 // Two DeclRefExpr's, check that the decls are the same.
9361 if (LHSDeclRef && RHSDeclRef) {
9362 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9363 return;
9364 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9365 RHSDeclRef->getDecl()->getCanonicalDecl())
9366 return;
9367
9368 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9369 << LHSExpr->getSourceRange()
9370 << RHSExpr->getSourceRange();
9371 return;
9372 }
9373
9374 // Member variables require a different approach to check for self moves.
9375 // MemberExpr's are the same if every nested MemberExpr refers to the same
9376 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9377 // the base Expr's are CXXThisExpr's.
9378 const Expr *LHSBase = LHSExpr;
9379 const Expr *RHSBase = RHSExpr;
9380 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9381 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9382 if (!LHSME || !RHSME)
9383 return;
9384
9385 while (LHSME && RHSME) {
9386 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9387 RHSME->getMemberDecl()->getCanonicalDecl())
9388 return;
9389
9390 LHSBase = LHSME->getBase();
9391 RHSBase = RHSME->getBase();
9392 LHSME = dyn_cast<MemberExpr>(LHSBase);
9393 RHSME = dyn_cast<MemberExpr>(RHSBase);
9394 }
9395
9396 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9397 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9398 if (LHSDeclRef && RHSDeclRef) {
9399 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9400 return;
9401 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9402 RHSDeclRef->getDecl()->getCanonicalDecl())
9403 return;
9404
9405 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9406 << LHSExpr->getSourceRange()
9407 << RHSExpr->getSourceRange();
9408 return;
9409 }
9410
9411 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9412 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9413 << LHSExpr->getSourceRange()
9414 << RHSExpr->getSourceRange();
9415}
9416
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009417//===--- Layout compatibility ----------------------------------------------//
9418
9419namespace {
9420
9421bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9422
9423/// \brief Check if two enumeration types are layout-compatible.
9424bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9425 // C++11 [dcl.enum] p8:
9426 // Two enumeration types are layout-compatible if they have the same
9427 // underlying type.
9428 return ED1->isComplete() && ED2->isComplete() &&
9429 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9430}
9431
9432/// \brief Check if two fields are layout-compatible.
9433bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9434 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9435 return false;
9436
9437 if (Field1->isBitField() != Field2->isBitField())
9438 return false;
9439
9440 if (Field1->isBitField()) {
9441 // Make sure that the bit-fields are the same length.
9442 unsigned Bits1 = Field1->getBitWidthValue(C);
9443 unsigned Bits2 = Field2->getBitWidthValue(C);
9444
9445 if (Bits1 != Bits2)
9446 return false;
9447 }
9448
9449 return true;
9450}
9451
9452/// \brief Check if two standard-layout structs are layout-compatible.
9453/// (C++11 [class.mem] p17)
9454bool isLayoutCompatibleStruct(ASTContext &C,
9455 RecordDecl *RD1,
9456 RecordDecl *RD2) {
9457 // If both records are C++ classes, check that base classes match.
9458 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9459 // If one of records is a CXXRecordDecl we are in C++ mode,
9460 // thus the other one is a CXXRecordDecl, too.
9461 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9462 // Check number of base classes.
9463 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9464 return false;
9465
9466 // Check the base classes.
9467 for (CXXRecordDecl::base_class_const_iterator
9468 Base1 = D1CXX->bases_begin(),
9469 BaseEnd1 = D1CXX->bases_end(),
9470 Base2 = D2CXX->bases_begin();
9471 Base1 != BaseEnd1;
9472 ++Base1, ++Base2) {
9473 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9474 return false;
9475 }
9476 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9477 // If only RD2 is a C++ class, it should have zero base classes.
9478 if (D2CXX->getNumBases() > 0)
9479 return false;
9480 }
9481
9482 // Check the fields.
9483 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9484 Field2End = RD2->field_end(),
9485 Field1 = RD1->field_begin(),
9486 Field1End = RD1->field_end();
9487 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9488 if (!isLayoutCompatible(C, *Field1, *Field2))
9489 return false;
9490 }
9491 if (Field1 != Field1End || Field2 != Field2End)
9492 return false;
9493
9494 return true;
9495}
9496
9497/// \brief Check if two standard-layout unions are layout-compatible.
9498/// (C++11 [class.mem] p18)
9499bool isLayoutCompatibleUnion(ASTContext &C,
9500 RecordDecl *RD1,
9501 RecordDecl *RD2) {
9502 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009503 for (auto *Field2 : RD2->fields())
9504 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009505
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009506 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009507 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9508 I = UnmatchedFields.begin(),
9509 E = UnmatchedFields.end();
9510
9511 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009512 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009513 bool Result = UnmatchedFields.erase(*I);
9514 (void) Result;
9515 assert(Result);
9516 break;
9517 }
9518 }
9519 if (I == E)
9520 return false;
9521 }
9522
9523 return UnmatchedFields.empty();
9524}
9525
9526bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9527 if (RD1->isUnion() != RD2->isUnion())
9528 return false;
9529
9530 if (RD1->isUnion())
9531 return isLayoutCompatibleUnion(C, RD1, RD2);
9532 else
9533 return isLayoutCompatibleStruct(C, RD1, RD2);
9534}
9535
9536/// \brief Check if two types are layout-compatible in C++11 sense.
9537bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9538 if (T1.isNull() || T2.isNull())
9539 return false;
9540
9541 // C++11 [basic.types] p11:
9542 // If two types T1 and T2 are the same type, then T1 and T2 are
9543 // layout-compatible types.
9544 if (C.hasSameType(T1, T2))
9545 return true;
9546
9547 T1 = T1.getCanonicalType().getUnqualifiedType();
9548 T2 = T2.getCanonicalType().getUnqualifiedType();
9549
9550 const Type::TypeClass TC1 = T1->getTypeClass();
9551 const Type::TypeClass TC2 = T2->getTypeClass();
9552
9553 if (TC1 != TC2)
9554 return false;
9555
9556 if (TC1 == Type::Enum) {
9557 return isLayoutCompatible(C,
9558 cast<EnumType>(T1)->getDecl(),
9559 cast<EnumType>(T2)->getDecl());
9560 } else if (TC1 == Type::Record) {
9561 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9562 return false;
9563
9564 return isLayoutCompatible(C,
9565 cast<RecordType>(T1)->getDecl(),
9566 cast<RecordType>(T2)->getDecl());
9567 }
9568
9569 return false;
9570}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009571}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009572
9573//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9574
9575namespace {
9576/// \brief Given a type tag expression find the type tag itself.
9577///
9578/// \param TypeExpr Type tag expression, as it appears in user's code.
9579///
9580/// \param VD Declaration of an identifier that appears in a type tag.
9581///
9582/// \param MagicValue Type tag magic value.
9583bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9584 const ValueDecl **VD, uint64_t *MagicValue) {
9585 while(true) {
9586 if (!TypeExpr)
9587 return false;
9588
9589 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9590
9591 switch (TypeExpr->getStmtClass()) {
9592 case Stmt::UnaryOperatorClass: {
9593 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9594 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9595 TypeExpr = UO->getSubExpr();
9596 continue;
9597 }
9598 return false;
9599 }
9600
9601 case Stmt::DeclRefExprClass: {
9602 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9603 *VD = DRE->getDecl();
9604 return true;
9605 }
9606
9607 case Stmt::IntegerLiteralClass: {
9608 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9609 llvm::APInt MagicValueAPInt = IL->getValue();
9610 if (MagicValueAPInt.getActiveBits() <= 64) {
9611 *MagicValue = MagicValueAPInt.getZExtValue();
9612 return true;
9613 } else
9614 return false;
9615 }
9616
9617 case Stmt::BinaryConditionalOperatorClass:
9618 case Stmt::ConditionalOperatorClass: {
9619 const AbstractConditionalOperator *ACO =
9620 cast<AbstractConditionalOperator>(TypeExpr);
9621 bool Result;
9622 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9623 if (Result)
9624 TypeExpr = ACO->getTrueExpr();
9625 else
9626 TypeExpr = ACO->getFalseExpr();
9627 continue;
9628 }
9629 return false;
9630 }
9631
9632 case Stmt::BinaryOperatorClass: {
9633 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9634 if (BO->getOpcode() == BO_Comma) {
9635 TypeExpr = BO->getRHS();
9636 continue;
9637 }
9638 return false;
9639 }
9640
9641 default:
9642 return false;
9643 }
9644 }
9645}
9646
9647/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9648///
9649/// \param TypeExpr Expression that specifies a type tag.
9650///
9651/// \param MagicValues Registered magic values.
9652///
9653/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9654/// kind.
9655///
9656/// \param TypeInfo Information about the corresponding C type.
9657///
9658/// \returns true if the corresponding C type was found.
9659bool GetMatchingCType(
9660 const IdentifierInfo *ArgumentKind,
9661 const Expr *TypeExpr, const ASTContext &Ctx,
9662 const llvm::DenseMap<Sema::TypeTagMagicValue,
9663 Sema::TypeTagData> *MagicValues,
9664 bool &FoundWrongKind,
9665 Sema::TypeTagData &TypeInfo) {
9666 FoundWrongKind = false;
9667
9668 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009669 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009670
9671 uint64_t MagicValue;
9672
9673 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9674 return false;
9675
9676 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009677 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009678 if (I->getArgumentKind() != ArgumentKind) {
9679 FoundWrongKind = true;
9680 return false;
9681 }
9682 TypeInfo.Type = I->getMatchingCType();
9683 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9684 TypeInfo.MustBeNull = I->getMustBeNull();
9685 return true;
9686 }
9687 return false;
9688 }
9689
9690 if (!MagicValues)
9691 return false;
9692
9693 llvm::DenseMap<Sema::TypeTagMagicValue,
9694 Sema::TypeTagData>::const_iterator I =
9695 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9696 if (I == MagicValues->end())
9697 return false;
9698
9699 TypeInfo = I->second;
9700 return true;
9701}
9702} // unnamed namespace
9703
9704void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9705 uint64_t MagicValue, QualType Type,
9706 bool LayoutCompatible,
9707 bool MustBeNull) {
9708 if (!TypeTagForDatatypeMagicValues)
9709 TypeTagForDatatypeMagicValues.reset(
9710 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9711
9712 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9713 (*TypeTagForDatatypeMagicValues)[Magic] =
9714 TypeTagData(Type, LayoutCompatible, MustBeNull);
9715}
9716
9717namespace {
9718bool IsSameCharType(QualType T1, QualType T2) {
9719 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9720 if (!BT1)
9721 return false;
9722
9723 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9724 if (!BT2)
9725 return false;
9726
9727 BuiltinType::Kind T1Kind = BT1->getKind();
9728 BuiltinType::Kind T2Kind = BT2->getKind();
9729
9730 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9731 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9732 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9733 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9734}
9735} // unnamed namespace
9736
9737void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9738 const Expr * const *ExprArgs) {
9739 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9740 bool IsPointerAttr = Attr->getIsPointer();
9741
9742 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9743 bool FoundWrongKind;
9744 TypeTagData TypeInfo;
9745 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9746 TypeTagForDatatypeMagicValues.get(),
9747 FoundWrongKind, TypeInfo)) {
9748 if (FoundWrongKind)
9749 Diag(TypeTagExpr->getExprLoc(),
9750 diag::warn_type_tag_for_datatype_wrong_kind)
9751 << TypeTagExpr->getSourceRange();
9752 return;
9753 }
9754
9755 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9756 if (IsPointerAttr) {
9757 // Skip implicit cast of pointer to `void *' (as a function argument).
9758 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009759 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009760 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009761 ArgumentExpr = ICE->getSubExpr();
9762 }
9763 QualType ArgumentType = ArgumentExpr->getType();
9764
9765 // Passing a `void*' pointer shouldn't trigger a warning.
9766 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9767 return;
9768
9769 if (TypeInfo.MustBeNull) {
9770 // Type tag with matching void type requires a null pointer.
9771 if (!ArgumentExpr->isNullPointerConstant(Context,
9772 Expr::NPC_ValueDependentIsNotNull)) {
9773 Diag(ArgumentExpr->getExprLoc(),
9774 diag::warn_type_safety_null_pointer_required)
9775 << ArgumentKind->getName()
9776 << ArgumentExpr->getSourceRange()
9777 << TypeTagExpr->getSourceRange();
9778 }
9779 return;
9780 }
9781
9782 QualType RequiredType = TypeInfo.Type;
9783 if (IsPointerAttr)
9784 RequiredType = Context.getPointerType(RequiredType);
9785
9786 bool mismatch = false;
9787 if (!TypeInfo.LayoutCompatible) {
9788 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9789
9790 // C++11 [basic.fundamental] p1:
9791 // Plain char, signed char, and unsigned char are three distinct types.
9792 //
9793 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9794 // char' depending on the current char signedness mode.
9795 if (mismatch)
9796 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9797 RequiredType->getPointeeType())) ||
9798 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9799 mismatch = false;
9800 } else
9801 if (IsPointerAttr)
9802 mismatch = !isLayoutCompatible(Context,
9803 ArgumentType->getPointeeType(),
9804 RequiredType->getPointeeType());
9805 else
9806 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9807
9808 if (mismatch)
9809 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009810 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009811 << TypeInfo.LayoutCompatible << RequiredType
9812 << ArgumentExpr->getSourceRange()
9813 << TypeTagExpr->getSourceRange();
9814}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009815