blob: a1f975a826f6cdfcd6c992bb65978b6bd6e6f6c5 [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>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000042
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000044using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045
Chris Lattnera26fb342009-02-18 17:49:48 +000046SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
47 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000048 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
49 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000050}
51
John McCallbebede42011-02-26 05:39:39 +000052/// Checks that a call expression's argument count is the desired number.
53/// This is useful when doing custom type-checking. Returns true on error.
54static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
55 unsigned argCount = call->getNumArgs();
56 if (argCount == desiredArgCount) return false;
57
58 if (argCount < desiredArgCount)
59 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
60 << 0 /*function call*/ << desiredArgCount << argCount
61 << call->getSourceRange();
62
63 // Highlight all the excess arguments.
64 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
65 call->getArg(argCount - 1)->getLocEnd());
66
67 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
68 << 0 /*function call*/ << desiredArgCount << argCount
69 << call->getArg(1)->getSourceRange();
70}
71
Julien Lerouge4a5b4442012-04-28 17:39:16 +000072/// Check that the first argument to __builtin_annotation is an integer
73/// and the second argument is a non-wide string literal.
74static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
75 if (checkArgCount(S, TheCall, 2))
76 return true;
77
78 // First argument should be an integer.
79 Expr *ValArg = TheCall->getArg(0);
80 QualType Ty = ValArg->getType();
81 if (!Ty->isIntegerType()) {
82 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
83 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000084 return true;
85 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000086
87 // Second argument should be a constant string.
88 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
89 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
90 if (!Literal || !Literal->isAscii()) {
91 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
92 << StrArg->getSourceRange();
93 return true;
94 }
95
96 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000097 return false;
98}
99
Richard Smith6cbd65d2013-07-11 02:27:57 +0000100/// Check that the argument to __builtin_addressof is a glvalue, and set the
101/// result type to the corresponding pointer type.
102static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
103 if (checkArgCount(S, TheCall, 1))
104 return true;
105
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000106 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000107 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
108 if (ResultType.isNull())
109 return true;
110
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000111 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000112 TheCall->setType(ResultType);
113 return false;
114}
115
John McCall03107a42015-10-29 20:48:01 +0000116static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
117 if (checkArgCount(S, TheCall, 3))
118 return true;
119
120 // First two arguments should be integers.
121 for (unsigned I = 0; I < 2; ++I) {
122 Expr *Arg = TheCall->getArg(I);
123 QualType Ty = Arg->getType();
124 if (!Ty->isIntegerType()) {
125 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
126 << Ty << Arg->getSourceRange();
127 return true;
128 }
129 }
130
131 // Third argument should be a pointer to a non-const integer.
132 // IRGen correctly handles volatile, restrict, and address spaces, and
133 // the other qualifiers aren't possible.
134 {
135 Expr *Arg = TheCall->getArg(2);
136 QualType Ty = Arg->getType();
137 const auto *PtrTy = Ty->getAs<PointerType>();
138 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
139 !PtrTy->getPointeeType().isConstQualified())) {
140 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
141 << Ty << Arg->getSourceRange();
142 return true;
143 }
144 }
145
146 return false;
147}
148
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000149static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
150 CallExpr *TheCall, unsigned SizeIdx,
151 unsigned DstSizeIdx) {
152 if (TheCall->getNumArgs() <= SizeIdx ||
153 TheCall->getNumArgs() <= DstSizeIdx)
154 return;
155
156 const Expr *SizeArg = TheCall->getArg(SizeIdx);
157 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
158
159 llvm::APSInt Size, DstSize;
160
161 // find out if both sizes are known at compile time
162 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
163 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
164 return;
165
166 if (Size.ule(DstSize))
167 return;
168
169 // confirmed overflow so generate the diagnostic.
170 IdentifierInfo *FnName = FDecl->getIdentifier();
171 SourceLocation SL = TheCall->getLocStart();
172 SourceRange SR = TheCall->getSourceRange();
173
174 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
175}
176
Peter Collingbournef7706832014-12-12 23:41:25 +0000177static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
178 if (checkArgCount(S, BuiltinCall, 2))
179 return true;
180
181 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
182 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
183 Expr *Call = BuiltinCall->getArg(0);
184 Expr *Chain = BuiltinCall->getArg(1);
185
186 if (Call->getStmtClass() != Stmt::CallExprClass) {
187 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
188 << Call->getSourceRange();
189 return true;
190 }
191
192 auto CE = cast<CallExpr>(Call);
193 if (CE->getCallee()->getType()->isBlockPointerType()) {
194 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
195 << Call->getSourceRange();
196 return true;
197 }
198
199 const Decl *TargetDecl = CE->getCalleeDecl();
200 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
201 if (FD->getBuiltinID()) {
202 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
203 << Call->getSourceRange();
204 return true;
205 }
206
207 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
208 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
209 << Call->getSourceRange();
210 return true;
211 }
212
213 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
214 if (ChainResult.isInvalid())
215 return true;
216 if (!ChainResult.get()->getType()->isPointerType()) {
217 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
218 << Chain->getSourceRange();
219 return true;
220 }
221
David Majnemerced8bdf2015-02-25 17:36:15 +0000222 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000223 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
224 QualType BuiltinTy = S.Context.getFunctionType(
225 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
226 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
227
228 Builtin =
229 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
230
231 BuiltinCall->setType(CE->getType());
232 BuiltinCall->setValueKind(CE->getValueKind());
233 BuiltinCall->setObjectKind(CE->getObjectKind());
234 BuiltinCall->setCallee(Builtin);
235 BuiltinCall->setArg(1, ChainResult.get());
236
237 return false;
238}
239
Reid Kleckner1d59f992015-01-22 01:36:17 +0000240static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
241 Scope::ScopeFlags NeededScopeFlags,
242 unsigned DiagID) {
243 // Scopes aren't available during instantiation. Fortunately, builtin
244 // functions cannot be template args so they cannot be formed through template
245 // instantiation. Therefore checking once during the parse is sufficient.
246 if (!SemaRef.ActiveTemplateInstantiations.empty())
247 return false;
248
249 Scope *S = SemaRef.getCurScope();
250 while (S && !S->isSEHExceptScope())
251 S = S->getParent();
252 if (!S || !(S->getFlags() & NeededScopeFlags)) {
253 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
254 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
255 << DRE->getDecl()->getIdentifier();
256 return true;
257 }
258
259 return false;
260}
261
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000262/// Returns readable name for a call.
263static StringRef getFunctionName(CallExpr *Call) {
264 return cast<FunctionDecl>(Call->getCalleeDecl())->getName();
265}
266
267/// Returns OpenCL access qual.
268// TODO: Refine OpenCLImageAccessAttr to OpenCLAccessAttr since pipe can use
269// it too
270static OpenCLImageAccessAttr *getOpenCLArgAccess(const Decl *D) {
271 if (D->hasAttr<OpenCLImageAccessAttr>())
272 return D->getAttr<OpenCLImageAccessAttr>();
273 return nullptr;
274}
275
276/// Returns true if pipe element type is different from the pointer.
277static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
278 const Expr *Arg0 = Call->getArg(0);
279 // First argument type should always be pipe.
280 if (!Arg0->getType()->isPipeType()) {
281 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
282 << getFunctionName(Call) << Arg0->getSourceRange();
283 return true;
284 }
285 OpenCLImageAccessAttr *AccessQual =
286 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
287 // Validates the access qualifier is compatible with the call.
288 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
289 // read_only and write_only, and assumed to be read_only if no qualifier is
290 // specified.
291 bool isValid = true;
292 bool ReadOnly = getFunctionName(Call).find("read") != StringRef::npos;
293 if (ReadOnly)
294 isValid = AccessQual == nullptr || AccessQual->isReadOnly();
295 else
296 isValid = AccessQual != nullptr && AccessQual->isWriteOnly();
297 if (!isValid) {
298 const char *AM = ReadOnly ? "read_only" : "write_only";
299 S.Diag(Arg0->getLocStart(),
300 diag::err_opencl_builtin_pipe_invalid_access_modifier)
301 << AM << Arg0->getSourceRange();
302 return true;
303 }
304
305 return false;
306}
307
308/// Returns true if pipe element type is different from the pointer.
309static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
310 const Expr *Arg0 = Call->getArg(0);
311 const Expr *ArgIdx = Call->getArg(Idx);
312 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
313 const Type *EltTy = PipeTy->getElementType().getTypePtr();
314 const PointerType *ArgTy =
315 dyn_cast<PointerType>(ArgIdx->getType().getTypePtr());
316 // The Idx argument should be a pointer and the type of the pointer and
317 // the type of pipe element should also be the same.
318 if (!ArgTy || EltTy != ArgTy->getPointeeType().getTypePtr()) {
319 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
320 << getFunctionName(Call)
321 << S.Context.getPointerType(PipeTy->getElementType())
322 << ArgIdx->getSourceRange();
323 return true;
324 }
325 return false;
326}
327
328// \brief Performs semantic analysis for the read/write_pipe call.
329// \param S Reference to the semantic analyzer.
330// \param Call A pointer to the builtin call.
331// \return True if a semantic error has been found, false otherwise.
332static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
333 // Two kinds of read/write pipe
334 // From OpenCL C Specification 6.13.16.2 the built-in read/write
335 // functions have following forms.
336 switch (Call->getNumArgs()) {
337 case 2: {
338 if (checkOpenCLPipeArg(S, Call))
339 return true;
340 // The call with 2 arguments should be
341 // read/write_pipe(pipe T, T*)
342 // check packet type T
343 if (checkOpenCLPipePacketType(S, Call, 1))
344 return true;
345 } break;
346
347 case 4: {
348 if (checkOpenCLPipeArg(S, Call))
349 return true;
350 // The call with 4 arguments should be
351 // read/write_pipe(pipe T, reserve_id_t, uint, T*)
352 // check reserve_id_t
353 if (!Call->getArg(1)->getType()->isReserveIDT()) {
354 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
355 << getFunctionName(Call) << S.Context.OCLReserveIDTy
356 << Call->getArg(1)->getSourceRange();
357 return true;
358 }
359
360 // check the index
361 const Expr *Arg2 = Call->getArg(2);
362 if (!Arg2->getType()->isIntegerType() &&
363 !Arg2->getType()->isUnsignedIntegerType()) {
364 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
365 << getFunctionName(Call) << S.Context.UnsignedIntTy
366 << Arg2->getSourceRange();
367 return true;
368 }
369
370 // check packet type T
371 if (checkOpenCLPipePacketType(S, Call, 3))
372 return true;
373 } break;
374 default:
375 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
376 << getFunctionName(Call) << Call->getSourceRange();
377 return true;
378 }
379
380 return false;
381}
382
383// \brief Performs a semantic analysis on the {work_group_/sub_group_
384// /_}reserve_{read/write}_pipe
385// \param S Reference to the semantic analyzer.
386// \param Call The call to the builtin function to be analyzed.
387// \return True if a semantic error was found, false otherwise.
388static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
389 if (checkArgCount(S, Call, 2))
390 return true;
391
392 if (checkOpenCLPipeArg(S, Call))
393 return true;
394
395 // check the reserve size
396 if (!Call->getArg(1)->getType()->isIntegerType() &&
397 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
398 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
399 << getFunctionName(Call) << S.Context.UnsignedIntTy
400 << Call->getArg(1)->getSourceRange();
401 return true;
402 }
403
404 return false;
405}
406
407// \brief Performs a semantic analysis on {work_group_/sub_group_
408// /_}commit_{read/write}_pipe
409// \param S Reference to the semantic analyzer.
410// \param Call The call to the builtin function to be analyzed.
411// \return True if a semantic error was found, false otherwise.
412static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
413 if (checkArgCount(S, Call, 2))
414 return true;
415
416 if (checkOpenCLPipeArg(S, Call))
417 return true;
418
419 // check reserve_id_t
420 if (!Call->getArg(1)->getType()->isReserveIDT()) {
421 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
422 << getFunctionName(Call) << S.Context.OCLReserveIDTy
423 << Call->getArg(1)->getSourceRange();
424 return true;
425 }
426
427 return false;
428}
429
430// \brief Performs a semantic analysis on the call to built-in Pipe
431// Query Functions.
432// \param S Reference to the semantic analyzer.
433// \param Call The call to the builtin function to be analyzed.
434// \return True if a semantic error was found, false otherwise.
435static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
436 if (checkArgCount(S, Call, 1))
437 return true;
438
439 if (!Call->getArg(0)->getType()->isPipeType()) {
440 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
441 << getFunctionName(Call) << Call->getArg(0)->getSourceRange();
442 return true;
443 }
444
445 return false;
446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000449Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
450 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000451 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000452
Chris Lattner3be167f2010-10-01 23:23:24 +0000453 // Find out if any arguments are required to be integer constant expressions.
454 unsigned ICEArguments = 0;
455 ASTContext::GetBuiltinTypeError Error;
456 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
457 if (Error != ASTContext::GE_None)
458 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
459
460 // If any arguments are required to be ICE's, check and diagnose.
461 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
462 // Skip arguments not required to be ICE's.
463 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
464
465 llvm::APSInt Result;
466 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
467 return true;
468 ICEArguments &= ~(1 << ArgNo);
469 }
470
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000471 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000472 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000473 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000474 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000475 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000476 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000477 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000478 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000479 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000480 if (SemaBuiltinVAStart(TheCall))
481 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000482 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000483 case Builtin::BI__va_start: {
484 switch (Context.getTargetInfo().getTriple().getArch()) {
485 case llvm::Triple::arm:
486 case llvm::Triple::thumb:
487 if (SemaBuiltinVAStartARM(TheCall))
488 return ExprError();
489 break;
490 default:
491 if (SemaBuiltinVAStart(TheCall))
492 return ExprError();
493 break;
494 }
495 break;
496 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000497 case Builtin::BI__builtin_isgreater:
498 case Builtin::BI__builtin_isgreaterequal:
499 case Builtin::BI__builtin_isless:
500 case Builtin::BI__builtin_islessequal:
501 case Builtin::BI__builtin_islessgreater:
502 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000503 if (SemaBuiltinUnorderedCompare(TheCall))
504 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000505 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000506 case Builtin::BI__builtin_fpclassify:
507 if (SemaBuiltinFPClassification(TheCall, 6))
508 return ExprError();
509 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000510 case Builtin::BI__builtin_isfinite:
511 case Builtin::BI__builtin_isinf:
512 case Builtin::BI__builtin_isinf_sign:
513 case Builtin::BI__builtin_isnan:
514 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000515 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000516 return ExprError();
517 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000518 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000519 return SemaBuiltinShuffleVector(TheCall);
520 // TheCall will be freed by the smart pointer here, but that's fine, since
521 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000522 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000523 if (SemaBuiltinPrefetch(TheCall))
524 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000525 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000526 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000527 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000528 if (SemaBuiltinAssume(TheCall))
529 return ExprError();
530 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000531 case Builtin::BI__builtin_assume_aligned:
532 if (SemaBuiltinAssumeAligned(TheCall))
533 return ExprError();
534 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000535 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000536 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000537 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000538 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000539 case Builtin::BI__builtin_longjmp:
540 if (SemaBuiltinLongjmp(TheCall))
541 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000542 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000543 case Builtin::BI__builtin_setjmp:
544 if (SemaBuiltinSetjmp(TheCall))
545 return ExprError();
546 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000547 case Builtin::BI_setjmp:
548 case Builtin::BI_setjmpex:
549 if (checkArgCount(*this, TheCall, 1))
550 return true;
551 break;
John McCallbebede42011-02-26 05:39:39 +0000552
553 case Builtin::BI__builtin_classify_type:
554 if (checkArgCount(*this, TheCall, 1)) return true;
555 TheCall->setType(Context.IntTy);
556 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000557 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000558 if (checkArgCount(*this, TheCall, 1)) return true;
559 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000560 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000561 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000562 case Builtin::BI__sync_fetch_and_add_1:
563 case Builtin::BI__sync_fetch_and_add_2:
564 case Builtin::BI__sync_fetch_and_add_4:
565 case Builtin::BI__sync_fetch_and_add_8:
566 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000567 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000568 case Builtin::BI__sync_fetch_and_sub_1:
569 case Builtin::BI__sync_fetch_and_sub_2:
570 case Builtin::BI__sync_fetch_and_sub_4:
571 case Builtin::BI__sync_fetch_and_sub_8:
572 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000573 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000574 case Builtin::BI__sync_fetch_and_or_1:
575 case Builtin::BI__sync_fetch_and_or_2:
576 case Builtin::BI__sync_fetch_and_or_4:
577 case Builtin::BI__sync_fetch_and_or_8:
578 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000579 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000580 case Builtin::BI__sync_fetch_and_and_1:
581 case Builtin::BI__sync_fetch_and_and_2:
582 case Builtin::BI__sync_fetch_and_and_4:
583 case Builtin::BI__sync_fetch_and_and_8:
584 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000585 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000586 case Builtin::BI__sync_fetch_and_xor_1:
587 case Builtin::BI__sync_fetch_and_xor_2:
588 case Builtin::BI__sync_fetch_and_xor_4:
589 case Builtin::BI__sync_fetch_and_xor_8:
590 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000591 case Builtin::BI__sync_fetch_and_nand:
592 case Builtin::BI__sync_fetch_and_nand_1:
593 case Builtin::BI__sync_fetch_and_nand_2:
594 case Builtin::BI__sync_fetch_and_nand_4:
595 case Builtin::BI__sync_fetch_and_nand_8:
596 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000597 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000598 case Builtin::BI__sync_add_and_fetch_1:
599 case Builtin::BI__sync_add_and_fetch_2:
600 case Builtin::BI__sync_add_and_fetch_4:
601 case Builtin::BI__sync_add_and_fetch_8:
602 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000603 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000604 case Builtin::BI__sync_sub_and_fetch_1:
605 case Builtin::BI__sync_sub_and_fetch_2:
606 case Builtin::BI__sync_sub_and_fetch_4:
607 case Builtin::BI__sync_sub_and_fetch_8:
608 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000609 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000610 case Builtin::BI__sync_and_and_fetch_1:
611 case Builtin::BI__sync_and_and_fetch_2:
612 case Builtin::BI__sync_and_and_fetch_4:
613 case Builtin::BI__sync_and_and_fetch_8:
614 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000615 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000616 case Builtin::BI__sync_or_and_fetch_1:
617 case Builtin::BI__sync_or_and_fetch_2:
618 case Builtin::BI__sync_or_and_fetch_4:
619 case Builtin::BI__sync_or_and_fetch_8:
620 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000621 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000622 case Builtin::BI__sync_xor_and_fetch_1:
623 case Builtin::BI__sync_xor_and_fetch_2:
624 case Builtin::BI__sync_xor_and_fetch_4:
625 case Builtin::BI__sync_xor_and_fetch_8:
626 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000627 case Builtin::BI__sync_nand_and_fetch:
628 case Builtin::BI__sync_nand_and_fetch_1:
629 case Builtin::BI__sync_nand_and_fetch_2:
630 case Builtin::BI__sync_nand_and_fetch_4:
631 case Builtin::BI__sync_nand_and_fetch_8:
632 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000633 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000634 case Builtin::BI__sync_val_compare_and_swap_1:
635 case Builtin::BI__sync_val_compare_and_swap_2:
636 case Builtin::BI__sync_val_compare_and_swap_4:
637 case Builtin::BI__sync_val_compare_and_swap_8:
638 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000639 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000640 case Builtin::BI__sync_bool_compare_and_swap_1:
641 case Builtin::BI__sync_bool_compare_and_swap_2:
642 case Builtin::BI__sync_bool_compare_and_swap_4:
643 case Builtin::BI__sync_bool_compare_and_swap_8:
644 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000645 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000646 case Builtin::BI__sync_lock_test_and_set_1:
647 case Builtin::BI__sync_lock_test_and_set_2:
648 case Builtin::BI__sync_lock_test_and_set_4:
649 case Builtin::BI__sync_lock_test_and_set_8:
650 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000651 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000652 case Builtin::BI__sync_lock_release_1:
653 case Builtin::BI__sync_lock_release_2:
654 case Builtin::BI__sync_lock_release_4:
655 case Builtin::BI__sync_lock_release_8:
656 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000657 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000658 case Builtin::BI__sync_swap_1:
659 case Builtin::BI__sync_swap_2:
660 case Builtin::BI__sync_swap_4:
661 case Builtin::BI__sync_swap_8:
662 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000663 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000664 case Builtin::BI__builtin_nontemporal_load:
665 case Builtin::BI__builtin_nontemporal_store:
666 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000667#define BUILTIN(ID, TYPE, ATTRS)
668#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
669 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000670 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000671#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000672 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000673 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000674 return ExprError();
675 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000676 case Builtin::BI__builtin_addressof:
677 if (SemaBuiltinAddressof(*this, TheCall))
678 return ExprError();
679 break;
John McCall03107a42015-10-29 20:48:01 +0000680 case Builtin::BI__builtin_add_overflow:
681 case Builtin::BI__builtin_sub_overflow:
682 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000683 if (SemaBuiltinOverflow(*this, TheCall))
684 return ExprError();
685 break;
Richard Smith760520b2014-06-03 23:27:44 +0000686 case Builtin::BI__builtin_operator_new:
687 case Builtin::BI__builtin_operator_delete:
688 if (!getLangOpts().CPlusPlus) {
689 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
690 << (BuiltinID == Builtin::BI__builtin_operator_new
691 ? "__builtin_operator_new"
692 : "__builtin_operator_delete")
693 << "C++";
694 return ExprError();
695 }
696 // CodeGen assumes it can find the global new and delete to call,
697 // so ensure that they are declared.
698 DeclareGlobalNewDelete();
699 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000700
701 // check secure string manipulation functions where overflows
702 // are detectable at compile time
703 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000704 case Builtin::BI__builtin___memmove_chk:
705 case Builtin::BI__builtin___memset_chk:
706 case Builtin::BI__builtin___strlcat_chk:
707 case Builtin::BI__builtin___strlcpy_chk:
708 case Builtin::BI__builtin___strncat_chk:
709 case Builtin::BI__builtin___strncpy_chk:
710 case Builtin::BI__builtin___stpncpy_chk:
711 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
712 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000713 case Builtin::BI__builtin___memccpy_chk:
714 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
715 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000716 case Builtin::BI__builtin___snprintf_chk:
717 case Builtin::BI__builtin___vsnprintf_chk:
718 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
719 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000720 case Builtin::BI__builtin_call_with_static_chain:
721 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
722 return ExprError();
723 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000724 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000725 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000726 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
727 diag::err_seh___except_block))
728 return ExprError();
729 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000730 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000731 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000732 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
733 diag::err_seh___except_filter))
734 return ExprError();
735 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000736 case Builtin::BI__GetExceptionInfo:
737 if (checkArgCount(*this, TheCall, 1))
738 return ExprError();
739
740 if (CheckCXXThrowOperand(
741 TheCall->getLocStart(),
742 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
743 TheCall))
744 return ExprError();
745
746 TheCall->setType(Context.VoidPtrTy);
747 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000748 case Builtin::BIread_pipe:
749 case Builtin::BIwrite_pipe:
750 // Since those two functions are declared with var args, we need a semantic
751 // check for the argument.
752 if (SemaBuiltinRWPipe(*this, TheCall))
753 return ExprError();
754 break;
755 case Builtin::BIreserve_read_pipe:
756 case Builtin::BIreserve_write_pipe:
757 case Builtin::BIwork_group_reserve_read_pipe:
758 case Builtin::BIwork_group_reserve_write_pipe:
759 case Builtin::BIsub_group_reserve_read_pipe:
760 case Builtin::BIsub_group_reserve_write_pipe:
761 if (SemaBuiltinReserveRWPipe(*this, TheCall))
762 return ExprError();
763 // Since return type of reserve_read/write_pipe built-in function is
764 // reserve_id_t, which is not defined in the builtin def file , we used int
765 // as return type and need to override the return type of these functions.
766 TheCall->setType(Context.OCLReserveIDTy);
767 break;
768 case Builtin::BIcommit_read_pipe:
769 case Builtin::BIcommit_write_pipe:
770 case Builtin::BIwork_group_commit_read_pipe:
771 case Builtin::BIwork_group_commit_write_pipe:
772 case Builtin::BIsub_group_commit_read_pipe:
773 case Builtin::BIsub_group_commit_write_pipe:
774 if (SemaBuiltinCommitRWPipe(*this, TheCall))
775 return ExprError();
776 break;
777 case Builtin::BIget_pipe_num_packets:
778 case Builtin::BIget_pipe_max_packets:
779 if (SemaBuiltinPipePackets(*this, TheCall))
780 return ExprError();
781 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000782 }
Richard Smith760520b2014-06-03 23:27:44 +0000783
Nate Begeman4904e322010-06-08 02:47:44 +0000784 // Since the target specific builtins for each arch overlap, only check those
785 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000786 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000787 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000788 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000789 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000790 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000791 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000792 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
793 return ExprError();
794 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000795 case llvm::Triple::aarch64:
796 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000797 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000798 return ExprError();
799 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000800 case llvm::Triple::mips:
801 case llvm::Triple::mipsel:
802 case llvm::Triple::mips64:
803 case llvm::Triple::mips64el:
804 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
805 return ExprError();
806 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000807 case llvm::Triple::systemz:
808 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
809 return ExprError();
810 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000811 case llvm::Triple::x86:
812 case llvm::Triple::x86_64:
813 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
814 return ExprError();
815 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000816 case llvm::Triple::ppc:
817 case llvm::Triple::ppc64:
818 case llvm::Triple::ppc64le:
819 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
820 return ExprError();
821 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000822 default:
823 break;
824 }
825 }
826
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000827 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000828}
829
Nate Begeman91e1fea2010-06-14 05:21:25 +0000830// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000831static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000832 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000833 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000834 switch (Type.getEltType()) {
835 case NeonTypeFlags::Int8:
836 case NeonTypeFlags::Poly8:
837 return shift ? 7 : (8 << IsQuad) - 1;
838 case NeonTypeFlags::Int16:
839 case NeonTypeFlags::Poly16:
840 return shift ? 15 : (4 << IsQuad) - 1;
841 case NeonTypeFlags::Int32:
842 return shift ? 31 : (2 << IsQuad) - 1;
843 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000844 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000845 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000846 case NeonTypeFlags::Poly128:
847 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000848 case NeonTypeFlags::Float16:
849 assert(!shift && "cannot shift float types!");
850 return (4 << IsQuad) - 1;
851 case NeonTypeFlags::Float32:
852 assert(!shift && "cannot shift float types!");
853 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000854 case NeonTypeFlags::Float64:
855 assert(!shift && "cannot shift float types!");
856 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000857 }
David Blaikie8a40f702012-01-17 06:56:22 +0000858 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000859}
860
Bob Wilsone4d77232011-11-08 05:04:11 +0000861/// getNeonEltType - Return the QualType corresponding to the elements of
862/// the vector type specified by the NeonTypeFlags. This is used to check
863/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000864static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000865 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000866 switch (Flags.getEltType()) {
867 case NeonTypeFlags::Int8:
868 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
869 case NeonTypeFlags::Int16:
870 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
871 case NeonTypeFlags::Int32:
872 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
873 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000874 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000875 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
876 else
877 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
878 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000879 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000880 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000881 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000882 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000883 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000884 if (IsInt64Long)
885 return Context.UnsignedLongTy;
886 else
887 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000888 case NeonTypeFlags::Poly128:
889 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000890 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000891 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000892 case NeonTypeFlags::Float32:
893 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000894 case NeonTypeFlags::Float64:
895 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000896 }
David Blaikie8a40f702012-01-17 06:56:22 +0000897 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000898}
899
Tim Northover12670412014-02-19 10:37:05 +0000900bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000901 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000902 uint64_t mask = 0;
903 unsigned TV = 0;
904 int PtrArgNum = -1;
905 bool HasConstPtr = false;
906 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000907#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000908#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000909#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000910 }
911
912 // For NEON intrinsics which are overloaded on vector element type, validate
913 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000914 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000915 if (mask) {
916 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
917 return true;
918
919 TV = Result.getLimitedValue(64);
920 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
921 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000922 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000923 }
924
925 if (PtrArgNum >= 0) {
926 // Check that pointer arguments have the specified type.
927 Expr *Arg = TheCall->getArg(PtrArgNum);
928 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
929 Arg = ICE->getSubExpr();
930 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
931 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000932
Tim Northovera2ee4332014-03-29 15:09:45 +0000933 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000934 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000935 bool IsInt64Long =
936 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
937 QualType EltTy =
938 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000939 if (HasConstPtr)
940 EltTy = EltTy.withConst();
941 QualType LHSTy = Context.getPointerType(EltTy);
942 AssignConvertType ConvTy;
943 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
944 if (RHS.isInvalid())
945 return true;
946 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
947 RHS.get(), AA_Assigning))
948 return true;
949 }
950
951 // For NEON intrinsics which take an immediate value as part of the
952 // instruction, range check them here.
953 unsigned i = 0, l = 0, u = 0;
954 switch (BuiltinID) {
955 default:
956 return false;
Tim Northover12670412014-02-19 10:37:05 +0000957#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000958#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000959#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000960 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000961
Richard Sandiford28940af2014-04-16 08:47:51 +0000962 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000963}
964
Tim Northovera2ee4332014-03-29 15:09:45 +0000965bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
966 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000967 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000968 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000969 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000970 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000971 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000972 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
973 BuiltinID == AArch64::BI__builtin_arm_strex ||
974 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000975 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000976 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000977 BuiltinID == ARM::BI__builtin_arm_ldaex ||
978 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
979 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000980
981 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
982
983 // Ensure that we have the proper number of arguments.
984 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
985 return true;
986
987 // Inspect the pointer argument of the atomic builtin. This should always be
988 // a pointer type, whose element is an integral scalar or pointer type.
989 // Because it is a pointer type, we don't have to worry about any implicit
990 // casts here.
991 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
992 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
993 if (PointerArgRes.isInvalid())
994 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000995 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000996
997 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
998 if (!pointerType) {
999 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1000 << PointerArg->getType() << PointerArg->getSourceRange();
1001 return true;
1002 }
1003
1004 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1005 // task is to insert the appropriate casts into the AST. First work out just
1006 // what the appropriate type is.
1007 QualType ValType = pointerType->getPointeeType();
1008 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1009 if (IsLdrex)
1010 AddrType.addConst();
1011
1012 // Issue a warning if the cast is dodgy.
1013 CastKind CastNeeded = CK_NoOp;
1014 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1015 CastNeeded = CK_BitCast;
1016 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1017 << PointerArg->getType()
1018 << Context.getPointerType(AddrType)
1019 << AA_Passing << PointerArg->getSourceRange();
1020 }
1021
1022 // Finally, do the cast and replace the argument with the corrected version.
1023 AddrType = Context.getPointerType(AddrType);
1024 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1025 if (PointerArgRes.isInvalid())
1026 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001027 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001028
1029 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1030
1031 // In general, we allow ints, floats and pointers to be loaded and stored.
1032 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1033 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1035 << PointerArg->getType() << PointerArg->getSourceRange();
1036 return true;
1037 }
1038
1039 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001040 if (Context.getTypeSize(ValType) > MaxWidth) {
1041 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001042 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1043 << PointerArg->getType() << PointerArg->getSourceRange();
1044 return true;
1045 }
1046
1047 switch (ValType.getObjCLifetime()) {
1048 case Qualifiers::OCL_None:
1049 case Qualifiers::OCL_ExplicitNone:
1050 // okay
1051 break;
1052
1053 case Qualifiers::OCL_Weak:
1054 case Qualifiers::OCL_Strong:
1055 case Qualifiers::OCL_Autoreleasing:
1056 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1057 << ValType << PointerArg->getSourceRange();
1058 return true;
1059 }
1060
Tim Northover6aacd492013-07-16 09:47:53 +00001061 if (IsLdrex) {
1062 TheCall->setType(ValType);
1063 return false;
1064 }
1065
1066 // Initialize the argument to be stored.
1067 ExprResult ValArg = TheCall->getArg(0);
1068 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1069 Context, ValType, /*consume*/ false);
1070 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1071 if (ValArg.isInvalid())
1072 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001073 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001074
1075 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1076 // but the custom checker bypasses all default analysis.
1077 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001078 return false;
1079}
1080
Nate Begeman4904e322010-06-08 02:47:44 +00001081bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001082 llvm::APSInt Result;
1083
Tim Northover6aacd492013-07-16 09:47:53 +00001084 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001085 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1086 BuiltinID == ARM::BI__builtin_arm_strex ||
1087 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001088 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001089 }
1090
Yi Kong26d104a2014-08-13 19:18:14 +00001091 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1092 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1093 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1094 }
1095
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001096 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1097 BuiltinID == ARM::BI__builtin_arm_wsr64)
1098 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1099
1100 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1101 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1102 BuiltinID == ARM::BI__builtin_arm_wsr ||
1103 BuiltinID == ARM::BI__builtin_arm_wsrp)
1104 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1105
Tim Northover12670412014-02-19 10:37:05 +00001106 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1107 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001108
Yi Kong4efadfb2014-07-03 16:01:25 +00001109 // For intrinsics which take an immediate value as part of the instruction,
1110 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001111 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001112 switch (BuiltinID) {
1113 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001114 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1115 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001116 case ARM::BI__builtin_arm_vcvtr_f:
1117 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001118 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001119 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001120 case ARM::BI__builtin_arm_isb:
1121 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001122 }
Nate Begemand773fe62010-06-13 04:47:52 +00001123
Nate Begemanf568b072010-08-03 21:32:34 +00001124 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001125 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001126}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001127
Tim Northover573cbee2014-05-24 12:52:07 +00001128bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001129 CallExpr *TheCall) {
1130 llvm::APSInt Result;
1131
Tim Northover573cbee2014-05-24 12:52:07 +00001132 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001133 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1134 BuiltinID == AArch64::BI__builtin_arm_strex ||
1135 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001136 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1137 }
1138
Yi Konga5548432014-08-13 19:18:20 +00001139 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1140 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1141 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1142 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1143 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1144 }
1145
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001146 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1147 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1148 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1149
1150 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1151 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1152 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1153 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1154 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1155
Tim Northovera2ee4332014-03-29 15:09:45 +00001156 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1157 return true;
1158
Yi Kong19a29ac2014-07-17 10:52:06 +00001159 // For intrinsics which take an immediate value as part of the instruction,
1160 // range check them here.
1161 unsigned i = 0, l = 0, u = 0;
1162 switch (BuiltinID) {
1163 default: return false;
1164 case AArch64::BI__builtin_arm_dmb:
1165 case AArch64::BI__builtin_arm_dsb:
1166 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1167 }
1168
Yi Kong19a29ac2014-07-17 10:52:06 +00001169 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001170}
1171
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001172bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1173 unsigned i = 0, l = 0, u = 0;
1174 switch (BuiltinID) {
1175 default: return false;
1176 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1177 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001178 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1179 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1180 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1181 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1182 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001183 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001184
Richard Sandiford28940af2014-04-16 08:47:51 +00001185 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001186}
1187
Kit Bartone50adcb2015-03-30 19:40:59 +00001188bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1189 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001190 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1191 BuiltinID == PPC::BI__builtin_divdeu ||
1192 BuiltinID == PPC::BI__builtin_bpermd;
1193 bool IsTarget64Bit = Context.getTargetInfo()
1194 .getTypeWidth(Context
1195 .getTargetInfo()
1196 .getIntPtrType()) == 64;
1197 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1198 BuiltinID == PPC::BI__builtin_divweu ||
1199 BuiltinID == PPC::BI__builtin_divde ||
1200 BuiltinID == PPC::BI__builtin_divdeu;
1201
1202 if (Is64BitBltin && !IsTarget64Bit)
1203 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1204 << TheCall->getSourceRange();
1205
1206 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1207 (BuiltinID == PPC::BI__builtin_bpermd &&
1208 !Context.getTargetInfo().hasFeature("bpermd")))
1209 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1210 << TheCall->getSourceRange();
1211
Kit Bartone50adcb2015-03-30 19:40:59 +00001212 switch (BuiltinID) {
1213 default: return false;
1214 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1215 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1216 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1217 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1218 case PPC::BI__builtin_tbegin:
1219 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1220 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1221 case PPC::BI__builtin_tabortwc:
1222 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1223 case PPC::BI__builtin_tabortwci:
1224 case PPC::BI__builtin_tabortdci:
1225 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1226 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1227 }
1228 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1229}
1230
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001231bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1232 CallExpr *TheCall) {
1233 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1234 Expr *Arg = TheCall->getArg(0);
1235 llvm::APSInt AbortCode(32);
1236 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1237 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1238 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1239 << Arg->getSourceRange();
1240 }
1241
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001242 // For intrinsics which take an immediate value as part of the instruction,
1243 // range check them here.
1244 unsigned i = 0, l = 0, u = 0;
1245 switch (BuiltinID) {
1246 default: return false;
1247 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1248 case SystemZ::BI__builtin_s390_verimb:
1249 case SystemZ::BI__builtin_s390_verimh:
1250 case SystemZ::BI__builtin_s390_verimf:
1251 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1252 case SystemZ::BI__builtin_s390_vfaeb:
1253 case SystemZ::BI__builtin_s390_vfaeh:
1254 case SystemZ::BI__builtin_s390_vfaef:
1255 case SystemZ::BI__builtin_s390_vfaebs:
1256 case SystemZ::BI__builtin_s390_vfaehs:
1257 case SystemZ::BI__builtin_s390_vfaefs:
1258 case SystemZ::BI__builtin_s390_vfaezb:
1259 case SystemZ::BI__builtin_s390_vfaezh:
1260 case SystemZ::BI__builtin_s390_vfaezf:
1261 case SystemZ::BI__builtin_s390_vfaezbs:
1262 case SystemZ::BI__builtin_s390_vfaezhs:
1263 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1264 case SystemZ::BI__builtin_s390_vfidb:
1265 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1266 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1267 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1268 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1269 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1270 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1271 case SystemZ::BI__builtin_s390_vstrcb:
1272 case SystemZ::BI__builtin_s390_vstrch:
1273 case SystemZ::BI__builtin_s390_vstrcf:
1274 case SystemZ::BI__builtin_s390_vstrczb:
1275 case SystemZ::BI__builtin_s390_vstrczh:
1276 case SystemZ::BI__builtin_s390_vstrczf:
1277 case SystemZ::BI__builtin_s390_vstrcbs:
1278 case SystemZ::BI__builtin_s390_vstrchs:
1279 case SystemZ::BI__builtin_s390_vstrcfs:
1280 case SystemZ::BI__builtin_s390_vstrczbs:
1281 case SystemZ::BI__builtin_s390_vstrczhs:
1282 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1283 }
1284 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001285}
1286
Craig Topper5ba2c502015-11-07 08:08:31 +00001287/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1288/// This checks that the target supports __builtin_cpu_supports and
1289/// that the string argument is constant and valid.
1290static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1291 Expr *Arg = TheCall->getArg(0);
1292
1293 // Check if the argument is a string literal.
1294 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1295 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1296 << Arg->getSourceRange();
1297
1298 // Check the contents of the string.
1299 StringRef Feature =
1300 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1301 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1302 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1303 << Arg->getSourceRange();
1304 return false;
1305}
1306
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001307bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001308 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001309 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001310 default:
1311 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001312 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001313 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001314 case X86::BI__builtin_ms_va_start:
1315 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001316 case X86::BI_mm_prefetch:
1317 i = 1;
1318 l = 0;
1319 u = 3;
1320 break;
1321 case X86::BI__builtin_ia32_sha1rnds4:
1322 i = 2;
1323 l = 0;
1324 u = 3;
1325 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001326 case X86::BI__builtin_ia32_vpermil2pd:
1327 case X86::BI__builtin_ia32_vpermil2pd256:
1328 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001329 case X86::BI__builtin_ia32_vpermil2ps256:
1330 i = 3;
1331 l = 0;
1332 u = 3;
1333 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001334 case X86::BI__builtin_ia32_cmpb128_mask:
1335 case X86::BI__builtin_ia32_cmpw128_mask:
1336 case X86::BI__builtin_ia32_cmpd128_mask:
1337 case X86::BI__builtin_ia32_cmpq128_mask:
1338 case X86::BI__builtin_ia32_cmpb256_mask:
1339 case X86::BI__builtin_ia32_cmpw256_mask:
1340 case X86::BI__builtin_ia32_cmpd256_mask:
1341 case X86::BI__builtin_ia32_cmpq256_mask:
1342 case X86::BI__builtin_ia32_cmpb512_mask:
1343 case X86::BI__builtin_ia32_cmpw512_mask:
1344 case X86::BI__builtin_ia32_cmpd512_mask:
1345 case X86::BI__builtin_ia32_cmpq512_mask:
1346 case X86::BI__builtin_ia32_ucmpb128_mask:
1347 case X86::BI__builtin_ia32_ucmpw128_mask:
1348 case X86::BI__builtin_ia32_ucmpd128_mask:
1349 case X86::BI__builtin_ia32_ucmpq128_mask:
1350 case X86::BI__builtin_ia32_ucmpb256_mask:
1351 case X86::BI__builtin_ia32_ucmpw256_mask:
1352 case X86::BI__builtin_ia32_ucmpd256_mask:
1353 case X86::BI__builtin_ia32_ucmpq256_mask:
1354 case X86::BI__builtin_ia32_ucmpb512_mask:
1355 case X86::BI__builtin_ia32_ucmpw512_mask:
1356 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001357 case X86::BI__builtin_ia32_ucmpq512_mask:
1358 i = 2;
1359 l = 0;
1360 u = 7;
1361 break;
Craig Topper16015252015-01-31 06:31:23 +00001362 case X86::BI__builtin_ia32_roundps:
1363 case X86::BI__builtin_ia32_roundpd:
1364 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001365 case X86::BI__builtin_ia32_roundpd256:
1366 i = 1;
1367 l = 0;
1368 u = 15;
1369 break;
Craig Topper16015252015-01-31 06:31:23 +00001370 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001371 case X86::BI__builtin_ia32_roundsd:
1372 i = 2;
1373 l = 0;
1374 u = 15;
1375 break;
Craig Topper16015252015-01-31 06:31:23 +00001376 case X86::BI__builtin_ia32_cmpps:
1377 case X86::BI__builtin_ia32_cmpss:
1378 case X86::BI__builtin_ia32_cmppd:
1379 case X86::BI__builtin_ia32_cmpsd:
1380 case X86::BI__builtin_ia32_cmpps256:
1381 case X86::BI__builtin_ia32_cmppd256:
1382 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001383 case X86::BI__builtin_ia32_cmppd512_mask:
1384 i = 2;
1385 l = 0;
1386 u = 31;
1387 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001388 case X86::BI__builtin_ia32_vpcomub:
1389 case X86::BI__builtin_ia32_vpcomuw:
1390 case X86::BI__builtin_ia32_vpcomud:
1391 case X86::BI__builtin_ia32_vpcomuq:
1392 case X86::BI__builtin_ia32_vpcomb:
1393 case X86::BI__builtin_ia32_vpcomw:
1394 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001395 case X86::BI__builtin_ia32_vpcomq:
1396 i = 2;
1397 l = 0;
1398 u = 7;
1399 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001400 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001401 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001402}
1403
Richard Smith55ce3522012-06-25 20:30:08 +00001404/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1405/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1406/// Returns true when the format fits the function and the FormatStringInfo has
1407/// been populated.
1408bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1409 FormatStringInfo *FSI) {
1410 FSI->HasVAListArg = Format->getFirstArg() == 0;
1411 FSI->FormatIdx = Format->getFormatIdx() - 1;
1412 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001413
Richard Smith55ce3522012-06-25 20:30:08 +00001414 // The way the format attribute works in GCC, the implicit this argument
1415 // of member functions is counted. However, it doesn't appear in our own
1416 // lists, so decrement format_idx in that case.
1417 if (IsCXXMember) {
1418 if(FSI->FormatIdx == 0)
1419 return false;
1420 --FSI->FormatIdx;
1421 if (FSI->FirstDataArg != 0)
1422 --FSI->FirstDataArg;
1423 }
1424 return true;
1425}
Mike Stump11289f42009-09-09 15:08:12 +00001426
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001427/// Checks if a the given expression evaluates to null.
1428///
1429/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001430static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001431 // If the expression has non-null type, it doesn't evaluate to null.
1432 if (auto nullability
1433 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1434 if (*nullability == NullabilityKind::NonNull)
1435 return false;
1436 }
1437
Ted Kremeneka146db32014-01-17 06:24:47 +00001438 // As a special case, transparent unions initialized with zero are
1439 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001440 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001441 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1442 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001443 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001444 if (const InitListExpr *ILE =
1445 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001446 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001447 }
1448
1449 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001450 return (!Expr->isValueDependent() &&
1451 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1452 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001453}
1454
1455static void CheckNonNullArgument(Sema &S,
1456 const Expr *ArgExpr,
1457 SourceLocation CallSiteLoc) {
1458 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001459 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1460 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001461}
1462
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001463bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1464 FormatStringInfo FSI;
1465 if ((GetFormatStringType(Format) == FST_NSString) &&
1466 getFormatStringInfo(Format, false, &FSI)) {
1467 Idx = FSI.FormatIdx;
1468 return true;
1469 }
1470 return false;
1471}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001472/// \brief Diagnose use of %s directive in an NSString which is being passed
1473/// as formatting string to formatting method.
1474static void
1475DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1476 const NamedDecl *FDecl,
1477 Expr **Args,
1478 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001479 unsigned Idx = 0;
1480 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001481 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1482 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001483 Idx = 2;
1484 Format = true;
1485 }
1486 else
1487 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1488 if (S.GetFormatNSStringIdx(I, Idx)) {
1489 Format = true;
1490 break;
1491 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001492 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001493 if (!Format || NumArgs <= Idx)
1494 return;
1495 const Expr *FormatExpr = Args[Idx];
1496 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1497 FormatExpr = CSCE->getSubExpr();
1498 const StringLiteral *FormatString;
1499 if (const ObjCStringLiteral *OSL =
1500 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1501 FormatString = OSL->getString();
1502 else
1503 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1504 if (!FormatString)
1505 return;
1506 if (S.FormatStringHasSArg(FormatString)) {
1507 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1508 << "%s" << 1 << 1;
1509 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1510 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001511 }
1512}
1513
Douglas Gregorb4866e82015-06-19 18:13:19 +00001514/// Determine whether the given type has a non-null nullability annotation.
1515static bool isNonNullType(ASTContext &ctx, QualType type) {
1516 if (auto nullability = type->getNullability(ctx))
1517 return *nullability == NullabilityKind::NonNull;
1518
1519 return false;
1520}
1521
Ted Kremenek2bc73332014-01-17 06:24:43 +00001522static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001523 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001524 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001525 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001526 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001527 assert((FDecl || Proto) && "Need a function declaration or prototype");
1528
Ted Kremenek9aedc152014-01-17 06:24:56 +00001529 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001530 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001531 if (FDecl) {
1532 // Handle the nonnull attribute on the function/method declaration itself.
1533 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1534 if (!NonNull->args_size()) {
1535 // Easy case: all pointer arguments are nonnull.
1536 for (const auto *Arg : Args)
1537 if (S.isValidPointerAttrType(Arg->getType()))
1538 CheckNonNullArgument(S, Arg, CallSiteLoc);
1539 return;
1540 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001541
Douglas Gregorb4866e82015-06-19 18:13:19 +00001542 for (unsigned Val : NonNull->args()) {
1543 if (Val >= Args.size())
1544 continue;
1545 if (NonNullArgs.empty())
1546 NonNullArgs.resize(Args.size());
1547 NonNullArgs.set(Val);
1548 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001549 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001550 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001551
Douglas Gregorb4866e82015-06-19 18:13:19 +00001552 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1553 // Handle the nonnull attribute on the parameters of the
1554 // function/method.
1555 ArrayRef<ParmVarDecl*> parms;
1556 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1557 parms = FD->parameters();
1558 else
1559 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1560
1561 unsigned ParamIndex = 0;
1562 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1563 I != E; ++I, ++ParamIndex) {
1564 const ParmVarDecl *PVD = *I;
1565 if (PVD->hasAttr<NonNullAttr>() ||
1566 isNonNullType(S.Context, PVD->getType())) {
1567 if (NonNullArgs.empty())
1568 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001569
Douglas Gregorb4866e82015-06-19 18:13:19 +00001570 NonNullArgs.set(ParamIndex);
1571 }
1572 }
1573 } else {
1574 // If we have a non-function, non-method declaration but no
1575 // function prototype, try to dig out the function prototype.
1576 if (!Proto) {
1577 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1578 QualType type = VD->getType().getNonReferenceType();
1579 if (auto pointerType = type->getAs<PointerType>())
1580 type = pointerType->getPointeeType();
1581 else if (auto blockType = type->getAs<BlockPointerType>())
1582 type = blockType->getPointeeType();
1583 // FIXME: data member pointers?
1584
1585 // Dig out the function prototype, if there is one.
1586 Proto = type->getAs<FunctionProtoType>();
1587 }
1588 }
1589
1590 // Fill in non-null argument information from the nullability
1591 // information on the parameter types (if we have them).
1592 if (Proto) {
1593 unsigned Index = 0;
1594 for (auto paramType : Proto->getParamTypes()) {
1595 if (isNonNullType(S.Context, paramType)) {
1596 if (NonNullArgs.empty())
1597 NonNullArgs.resize(Args.size());
1598
1599 NonNullArgs.set(Index);
1600 }
1601
1602 ++Index;
1603 }
1604 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001605 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001606
Douglas Gregorb4866e82015-06-19 18:13:19 +00001607 // Check for non-null arguments.
1608 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1609 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001610 if (NonNullArgs[ArgIndex])
1611 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001612 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001613}
1614
Richard Smith55ce3522012-06-25 20:30:08 +00001615/// Handles the checks for format strings, non-POD arguments to vararg
1616/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001617void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1618 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001619 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001620 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001621 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001622 if (CurContext->isDependentContext())
1623 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001624
Ted Kremenekb8176da2010-09-09 04:33:05 +00001625 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001626 llvm::SmallBitVector CheckedVarArgs;
1627 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001628 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001629 // Only create vector if there are format attributes.
1630 CheckedVarArgs.resize(Args.size());
1631
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001632 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001633 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001634 }
Richard Smithd7293d72013-08-05 18:49:43 +00001635 }
Richard Smith55ce3522012-06-25 20:30:08 +00001636
1637 // Refuse POD arguments that weren't caught by the format string
1638 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001639 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001640 unsigned NumParams = Proto ? Proto->getNumParams()
1641 : FDecl && isa<FunctionDecl>(FDecl)
1642 ? cast<FunctionDecl>(FDecl)->getNumParams()
1643 : FDecl && isa<ObjCMethodDecl>(FDecl)
1644 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1645 : 0;
1646
Alp Toker9cacbab2014-01-20 20:26:09 +00001647 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001648 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001649 if (const Expr *Arg = Args[ArgIdx]) {
1650 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1651 checkVariadicArgument(Arg, CallType);
1652 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001653 }
Richard Smithd7293d72013-08-05 18:49:43 +00001654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Douglas Gregorb4866e82015-06-19 18:13:19 +00001656 if (FDecl || Proto) {
1657 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001658
Richard Trieu41bc0992013-06-22 00:20:41 +00001659 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001660 if (FDecl) {
1661 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1662 CheckArgumentWithTypeTag(I, Args.data());
1663 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001664 }
Richard Smith55ce3522012-06-25 20:30:08 +00001665}
1666
1667/// CheckConstructorCall - Check a constructor call for correctness and safety
1668/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001669void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1670 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001671 const FunctionProtoType *Proto,
1672 SourceLocation Loc) {
1673 VariadicCallType CallType =
1674 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001675 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1676 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001677}
1678
1679/// CheckFunctionCall - Check a direct function call for various correctness
1680/// and safety properties not strictly enforced by the C type system.
1681bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1682 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001683 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1684 isa<CXXMethodDecl>(FDecl);
1685 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1686 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001687 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1688 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001689 Expr** Args = TheCall->getArgs();
1690 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001691 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001692 // If this is a call to a member operator, hide the first argument
1693 // from checkCall.
1694 // FIXME: Our choice of AST representation here is less than ideal.
1695 ++Args;
1696 --NumArgs;
1697 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001698 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001699 IsMemberFunction, TheCall->getRParenLoc(),
1700 TheCall->getCallee()->getSourceRange(), CallType);
1701
1702 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1703 // None of the checks below are needed for functions that don't have
1704 // simple names (e.g., C++ conversion functions).
1705 if (!FnInfo)
1706 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001707
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001708 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001709 if (getLangOpts().ObjC1)
1710 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001711
Anna Zaks22122702012-01-17 00:37:07 +00001712 unsigned CMId = FDecl->getMemoryFunctionKind();
1713 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001714 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001715
Anna Zaks201d4892012-01-13 21:52:01 +00001716 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001717 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001718 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001719 else if (CMId == Builtin::BIstrncat)
1720 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001721 else
Anna Zaks22122702012-01-17 00:37:07 +00001722 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001723
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001724 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001725}
1726
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001727bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001728 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001729 VariadicCallType CallType =
1730 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001731
Douglas Gregorb4866e82015-06-19 18:13:19 +00001732 checkCall(Method, nullptr, Args,
1733 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1734 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001735
1736 return false;
1737}
1738
Richard Trieu664c4c62013-06-20 21:03:13 +00001739bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1740 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001741 QualType Ty;
1742 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001743 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001744 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001745 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001746 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001747 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001748
Douglas Gregorb4866e82015-06-19 18:13:19 +00001749 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1750 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001751 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001752
Richard Trieu664c4c62013-06-20 21:03:13 +00001753 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001754 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001755 CallType = VariadicDoesNotApply;
1756 } else if (Ty->isBlockPointerType()) {
1757 CallType = VariadicBlock;
1758 } else { // Ty->isFunctionPointerType()
1759 CallType = VariadicFunction;
1760 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001761
Douglas Gregorb4866e82015-06-19 18:13:19 +00001762 checkCall(NDecl, Proto,
1763 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1764 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001765 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001766
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001767 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001768}
1769
Richard Trieu41bc0992013-06-22 00:20:41 +00001770/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1771/// such as function pointers returned from functions.
1772bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001773 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001774 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001775 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001776 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001777 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001778 TheCall->getCallee()->getSourceRange(), CallType);
1779
1780 return false;
1781}
1782
Tim Northovere94a34c2014-03-11 10:49:14 +00001783static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1784 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1785 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1786 return false;
1787
1788 switch (Op) {
1789 case AtomicExpr::AO__c11_atomic_init:
1790 llvm_unreachable("There is no ordering argument for an init");
1791
1792 case AtomicExpr::AO__c11_atomic_load:
1793 case AtomicExpr::AO__atomic_load_n:
1794 case AtomicExpr::AO__atomic_load:
1795 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1796 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1797
1798 case AtomicExpr::AO__c11_atomic_store:
1799 case AtomicExpr::AO__atomic_store:
1800 case AtomicExpr::AO__atomic_store_n:
1801 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1802 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1803 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1804
1805 default:
1806 return true;
1807 }
1808}
1809
Richard Smithfeea8832012-04-12 05:08:17 +00001810ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1811 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001812 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1813 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001814
Richard Smithfeea8832012-04-12 05:08:17 +00001815 // All these operations take one of the following forms:
1816 enum {
1817 // C __c11_atomic_init(A *, C)
1818 Init,
1819 // C __c11_atomic_load(A *, int)
1820 Load,
1821 // void __atomic_load(A *, CP, int)
1822 Copy,
1823 // C __c11_atomic_add(A *, M, int)
1824 Arithmetic,
1825 // C __atomic_exchange_n(A *, CP, int)
1826 Xchg,
1827 // void __atomic_exchange(A *, C *, CP, int)
1828 GNUXchg,
1829 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1830 C11CmpXchg,
1831 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1832 GNUCmpXchg
1833 } Form = Init;
1834 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1835 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1836 // where:
1837 // C is an appropriate type,
1838 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1839 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1840 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1841 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001842
Gabor Horvath98bd0982015-03-16 09:59:54 +00001843 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1844 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1845 AtomicExpr::AO__atomic_load,
1846 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001847 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1848 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1849 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1850 Op == AtomicExpr::AO__atomic_store_n ||
1851 Op == AtomicExpr::AO__atomic_exchange_n ||
1852 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1853 bool IsAddSub = false;
1854
1855 switch (Op) {
1856 case AtomicExpr::AO__c11_atomic_init:
1857 Form = Init;
1858 break;
1859
1860 case AtomicExpr::AO__c11_atomic_load:
1861 case AtomicExpr::AO__atomic_load_n:
1862 Form = Load;
1863 break;
1864
1865 case AtomicExpr::AO__c11_atomic_store:
1866 case AtomicExpr::AO__atomic_load:
1867 case AtomicExpr::AO__atomic_store:
1868 case AtomicExpr::AO__atomic_store_n:
1869 Form = Copy;
1870 break;
1871
1872 case AtomicExpr::AO__c11_atomic_fetch_add:
1873 case AtomicExpr::AO__c11_atomic_fetch_sub:
1874 case AtomicExpr::AO__atomic_fetch_add:
1875 case AtomicExpr::AO__atomic_fetch_sub:
1876 case AtomicExpr::AO__atomic_add_fetch:
1877 case AtomicExpr::AO__atomic_sub_fetch:
1878 IsAddSub = true;
1879 // Fall through.
1880 case AtomicExpr::AO__c11_atomic_fetch_and:
1881 case AtomicExpr::AO__c11_atomic_fetch_or:
1882 case AtomicExpr::AO__c11_atomic_fetch_xor:
1883 case AtomicExpr::AO__atomic_fetch_and:
1884 case AtomicExpr::AO__atomic_fetch_or:
1885 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001886 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001887 case AtomicExpr::AO__atomic_and_fetch:
1888 case AtomicExpr::AO__atomic_or_fetch:
1889 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001890 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001891 Form = Arithmetic;
1892 break;
1893
1894 case AtomicExpr::AO__c11_atomic_exchange:
1895 case AtomicExpr::AO__atomic_exchange_n:
1896 Form = Xchg;
1897 break;
1898
1899 case AtomicExpr::AO__atomic_exchange:
1900 Form = GNUXchg;
1901 break;
1902
1903 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1904 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1905 Form = C11CmpXchg;
1906 break;
1907
1908 case AtomicExpr::AO__atomic_compare_exchange:
1909 case AtomicExpr::AO__atomic_compare_exchange_n:
1910 Form = GNUCmpXchg;
1911 break;
1912 }
1913
1914 // Check we have the right number of arguments.
1915 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001916 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001917 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001918 << TheCall->getCallee()->getSourceRange();
1919 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001920 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1921 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001922 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001923 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001924 << TheCall->getCallee()->getSourceRange();
1925 return ExprError();
1926 }
1927
Richard Smithfeea8832012-04-12 05:08:17 +00001928 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001929 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001930 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1931 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1932 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001933 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001934 << Ptr->getType() << Ptr->getSourceRange();
1935 return ExprError();
1936 }
1937
Richard Smithfeea8832012-04-12 05:08:17 +00001938 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1939 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1940 QualType ValType = AtomTy; // 'C'
1941 if (IsC11) {
1942 if (!AtomTy->isAtomicType()) {
1943 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1944 << Ptr->getType() << Ptr->getSourceRange();
1945 return ExprError();
1946 }
Richard Smithe00921a2012-09-15 06:09:58 +00001947 if (AtomTy.isConstQualified()) {
1948 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1949 << Ptr->getType() << Ptr->getSourceRange();
1950 return ExprError();
1951 }
Richard Smithfeea8832012-04-12 05:08:17 +00001952 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001953 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1954 if (ValType.isConstQualified()) {
1955 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1956 << Ptr->getType() << Ptr->getSourceRange();
1957 return ExprError();
1958 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001959 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001960
Richard Smithfeea8832012-04-12 05:08:17 +00001961 // For an arithmetic operation, the implied arithmetic must be well-formed.
1962 if (Form == Arithmetic) {
1963 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1964 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1965 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1966 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1967 return ExprError();
1968 }
1969 if (!IsAddSub && !ValType->isIntegerType()) {
1970 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1971 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1972 return ExprError();
1973 }
David Majnemere85cff82015-01-28 05:48:06 +00001974 if (IsC11 && ValType->isPointerType() &&
1975 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1976 diag::err_incomplete_type)) {
1977 return ExprError();
1978 }
Richard Smithfeea8832012-04-12 05:08:17 +00001979 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1980 // For __atomic_*_n operations, the value type must be a scalar integral or
1981 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001982 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001983 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1984 return ExprError();
1985 }
1986
Eli Friedmanaa769812013-09-11 03:49:34 +00001987 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1988 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001989 // For GNU atomics, require a trivially-copyable type. This is not part of
1990 // the GNU atomics specification, but we enforce it for sanity.
1991 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001992 << Ptr->getType() << Ptr->getSourceRange();
1993 return ExprError();
1994 }
1995
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001996 switch (ValType.getObjCLifetime()) {
1997 case Qualifiers::OCL_None:
1998 case Qualifiers::OCL_ExplicitNone:
1999 // okay
2000 break;
2001
2002 case Qualifiers::OCL_Weak:
2003 case Qualifiers::OCL_Strong:
2004 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002005 // FIXME: Can this happen? By this point, ValType should be known
2006 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002007 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2008 << ValType << Ptr->getSourceRange();
2009 return ExprError();
2010 }
2011
David Majnemerc6eb6502015-06-03 00:26:35 +00002012 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2013 // volatile-ness of the pointee-type inject itself into the result or the
2014 // other operands.
2015 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002016 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00002017 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002018 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002019 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002020 ResultType = Context.BoolTy;
2021
Richard Smithfeea8832012-04-12 05:08:17 +00002022 // The type of a parameter passed 'by value'. In the GNU atomics, such
2023 // arguments are actually passed as pointers.
2024 QualType ByValType = ValType; // 'CP'
2025 if (!IsC11 && !IsN)
2026 ByValType = Ptr->getType();
2027
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002028 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2029 // but not the second argument. We need to manually remove possible const
2030 // qualifiers.
2031
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002032 // The first argument --- the pointer --- has a fixed type; we
2033 // deduce the types of the rest of the arguments accordingly. Walk
2034 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002035 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002036 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002037 if (i < NumVals[Form] + 1) {
2038 switch (i) {
2039 case 1:
2040 // The second argument is the non-atomic operand. For arithmetic, this
2041 // is always passed by value, and for a compare_exchange it is always
2042 // passed by address. For the rest, GNU uses by-address and C11 uses
2043 // by-value.
2044 assert(Form != Load);
2045 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2046 Ty = ValType;
2047 else if (Form == Copy || Form == Xchg)
2048 Ty = ByValType;
2049 else if (Form == Arithmetic)
2050 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002051 else {
2052 Expr *ValArg = TheCall->getArg(i);
2053 unsigned AS = 0;
2054 // Keep address space of non-atomic pointer type.
2055 if (const PointerType *PtrTy =
2056 ValArg->getType()->getAs<PointerType>()) {
2057 AS = PtrTy->getPointeeType().getAddressSpace();
2058 }
2059 Ty = Context.getPointerType(
2060 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2061 }
Richard Smithfeea8832012-04-12 05:08:17 +00002062 break;
2063 case 2:
2064 // The third argument to compare_exchange / GNU exchange is a
2065 // (pointer to a) desired value.
2066 Ty = ByValType;
2067 break;
2068 case 3:
2069 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2070 Ty = Context.BoolTy;
2071 break;
2072 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002073 } else {
2074 // The order(s) are always converted to int.
2075 Ty = Context.IntTy;
2076 }
Richard Smithfeea8832012-04-12 05:08:17 +00002077
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002078 InitializedEntity Entity =
2079 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002080 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002081 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2082 if (Arg.isInvalid())
2083 return true;
2084 TheCall->setArg(i, Arg.get());
2085 }
2086
Richard Smithfeea8832012-04-12 05:08:17 +00002087 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002088 SmallVector<Expr*, 5> SubExprs;
2089 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002090 switch (Form) {
2091 case Init:
2092 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002093 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002094 break;
2095 case Load:
2096 SubExprs.push_back(TheCall->getArg(1)); // Order
2097 break;
2098 case Copy:
2099 case Arithmetic:
2100 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002101 SubExprs.push_back(TheCall->getArg(2)); // Order
2102 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002103 break;
2104 case GNUXchg:
2105 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2106 SubExprs.push_back(TheCall->getArg(3)); // Order
2107 SubExprs.push_back(TheCall->getArg(1)); // Val1
2108 SubExprs.push_back(TheCall->getArg(2)); // Val2
2109 break;
2110 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002111 SubExprs.push_back(TheCall->getArg(3)); // Order
2112 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002113 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002114 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002115 break;
2116 case GNUCmpXchg:
2117 SubExprs.push_back(TheCall->getArg(4)); // Order
2118 SubExprs.push_back(TheCall->getArg(1)); // Val1
2119 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2120 SubExprs.push_back(TheCall->getArg(2)); // Val2
2121 SubExprs.push_back(TheCall->getArg(3)); // Weak
2122 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002123 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002124
2125 if (SubExprs.size() >= 2 && Form != Init) {
2126 llvm::APSInt Result(32);
2127 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2128 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002129 Diag(SubExprs[1]->getLocStart(),
2130 diag::warn_atomic_op_has_invalid_memory_order)
2131 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002132 }
2133
Fariborz Jahanian615de762013-05-28 17:37:39 +00002134 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2135 SubExprs, ResultType, Op,
2136 TheCall->getRParenLoc());
2137
2138 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2139 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2140 Context.AtomicUsesUnsupportedLibcall(AE))
2141 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2142 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002143
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002144 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002145}
2146
John McCall29ad95b2011-08-27 01:09:30 +00002147/// checkBuiltinArgument - Given a call to a builtin function, perform
2148/// normal type-checking on the given argument, updating the call in
2149/// place. This is useful when a builtin function requires custom
2150/// type-checking for some of its arguments but not necessarily all of
2151/// them.
2152///
2153/// Returns true on error.
2154static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2155 FunctionDecl *Fn = E->getDirectCallee();
2156 assert(Fn && "builtin call without direct callee!");
2157
2158 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2159 InitializedEntity Entity =
2160 InitializedEntity::InitializeParameter(S.Context, Param);
2161
2162 ExprResult Arg = E->getArg(0);
2163 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2164 if (Arg.isInvalid())
2165 return true;
2166
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002167 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002168 return false;
2169}
2170
Chris Lattnerdc046542009-05-08 06:58:22 +00002171/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2172/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2173/// type of its first argument. The main ActOnCallExpr routines have already
2174/// promoted the types of arguments because all of these calls are prototyped as
2175/// void(...).
2176///
2177/// This function goes through and does final semantic checking for these
2178/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002179ExprResult
2180Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002181 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002182 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2183 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2184
2185 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002186 if (TheCall->getNumArgs() < 1) {
2187 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2188 << 0 << 1 << TheCall->getNumArgs()
2189 << TheCall->getCallee()->getSourceRange();
2190 return ExprError();
2191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Chris Lattnerdc046542009-05-08 06:58:22 +00002193 // Inspect the first argument of the atomic builtin. This should always be
2194 // a pointer type, whose element is an integral scalar or pointer type.
2195 // Because it is a pointer type, we don't have to worry about any implicit
2196 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002197 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002198 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002199 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2200 if (FirstArgResult.isInvalid())
2201 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002202 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002203 TheCall->setArg(0, FirstArg);
2204
John McCall31168b02011-06-15 23:02:42 +00002205 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2206 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002207 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2208 << FirstArg->getType() << FirstArg->getSourceRange();
2209 return ExprError();
2210 }
Mike Stump11289f42009-09-09 15:08:12 +00002211
John McCall31168b02011-06-15 23:02:42 +00002212 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002213 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002214 !ValType->isBlockPointerType()) {
2215 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2216 << FirstArg->getType() << FirstArg->getSourceRange();
2217 return ExprError();
2218 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002219
John McCall31168b02011-06-15 23:02:42 +00002220 switch (ValType.getObjCLifetime()) {
2221 case Qualifiers::OCL_None:
2222 case Qualifiers::OCL_ExplicitNone:
2223 // okay
2224 break;
2225
2226 case Qualifiers::OCL_Weak:
2227 case Qualifiers::OCL_Strong:
2228 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002229 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002230 << ValType << FirstArg->getSourceRange();
2231 return ExprError();
2232 }
2233
John McCallb50451a2011-10-05 07:41:44 +00002234 // Strip any qualifiers off ValType.
2235 ValType = ValType.getUnqualifiedType();
2236
Chandler Carruth3973af72010-07-18 20:54:12 +00002237 // The majority of builtins return a value, but a few have special return
2238 // types, so allow them to override appropriately below.
2239 QualType ResultType = ValType;
2240
Chris Lattnerdc046542009-05-08 06:58:22 +00002241 // We need to figure out which concrete builtin this maps onto. For example,
2242 // __sync_fetch_and_add with a 2 byte object turns into
2243 // __sync_fetch_and_add_2.
2244#define BUILTIN_ROW(x) \
2245 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2246 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002247
Chris Lattnerdc046542009-05-08 06:58:22 +00002248 static const unsigned BuiltinIndices[][5] = {
2249 BUILTIN_ROW(__sync_fetch_and_add),
2250 BUILTIN_ROW(__sync_fetch_and_sub),
2251 BUILTIN_ROW(__sync_fetch_and_or),
2252 BUILTIN_ROW(__sync_fetch_and_and),
2253 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002254 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattnerdc046542009-05-08 06:58:22 +00002256 BUILTIN_ROW(__sync_add_and_fetch),
2257 BUILTIN_ROW(__sync_sub_and_fetch),
2258 BUILTIN_ROW(__sync_and_and_fetch),
2259 BUILTIN_ROW(__sync_or_and_fetch),
2260 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002261 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattnerdc046542009-05-08 06:58:22 +00002263 BUILTIN_ROW(__sync_val_compare_and_swap),
2264 BUILTIN_ROW(__sync_bool_compare_and_swap),
2265 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002266 BUILTIN_ROW(__sync_lock_release),
2267 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002268 };
Mike Stump11289f42009-09-09 15:08:12 +00002269#undef BUILTIN_ROW
2270
Chris Lattnerdc046542009-05-08 06:58:22 +00002271 // Determine the index of the size.
2272 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002273 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002274 case 1: SizeIndex = 0; break;
2275 case 2: SizeIndex = 1; break;
2276 case 4: SizeIndex = 2; break;
2277 case 8: SizeIndex = 3; break;
2278 case 16: SizeIndex = 4; break;
2279 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002280 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2281 << FirstArg->getType() << FirstArg->getSourceRange();
2282 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002283 }
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnerdc046542009-05-08 06:58:22 +00002285 // Each of these builtins has one pointer argument, followed by some number of
2286 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2287 // that we ignore. Find out which row of BuiltinIndices to read from as well
2288 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002289 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002290 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002291 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002292 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002293 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002294 case Builtin::BI__sync_fetch_and_add:
2295 case Builtin::BI__sync_fetch_and_add_1:
2296 case Builtin::BI__sync_fetch_and_add_2:
2297 case Builtin::BI__sync_fetch_and_add_4:
2298 case Builtin::BI__sync_fetch_and_add_8:
2299 case Builtin::BI__sync_fetch_and_add_16:
2300 BuiltinIndex = 0;
2301 break;
2302
2303 case Builtin::BI__sync_fetch_and_sub:
2304 case Builtin::BI__sync_fetch_and_sub_1:
2305 case Builtin::BI__sync_fetch_and_sub_2:
2306 case Builtin::BI__sync_fetch_and_sub_4:
2307 case Builtin::BI__sync_fetch_and_sub_8:
2308 case Builtin::BI__sync_fetch_and_sub_16:
2309 BuiltinIndex = 1;
2310 break;
2311
2312 case Builtin::BI__sync_fetch_and_or:
2313 case Builtin::BI__sync_fetch_and_or_1:
2314 case Builtin::BI__sync_fetch_and_or_2:
2315 case Builtin::BI__sync_fetch_and_or_4:
2316 case Builtin::BI__sync_fetch_and_or_8:
2317 case Builtin::BI__sync_fetch_and_or_16:
2318 BuiltinIndex = 2;
2319 break;
2320
2321 case Builtin::BI__sync_fetch_and_and:
2322 case Builtin::BI__sync_fetch_and_and_1:
2323 case Builtin::BI__sync_fetch_and_and_2:
2324 case Builtin::BI__sync_fetch_and_and_4:
2325 case Builtin::BI__sync_fetch_and_and_8:
2326 case Builtin::BI__sync_fetch_and_and_16:
2327 BuiltinIndex = 3;
2328 break;
Mike Stump11289f42009-09-09 15:08:12 +00002329
Douglas Gregor73722482011-11-28 16:30:08 +00002330 case Builtin::BI__sync_fetch_and_xor:
2331 case Builtin::BI__sync_fetch_and_xor_1:
2332 case Builtin::BI__sync_fetch_and_xor_2:
2333 case Builtin::BI__sync_fetch_and_xor_4:
2334 case Builtin::BI__sync_fetch_and_xor_8:
2335 case Builtin::BI__sync_fetch_and_xor_16:
2336 BuiltinIndex = 4;
2337 break;
2338
Hal Finkeld2208b52014-10-02 20:53:50 +00002339 case Builtin::BI__sync_fetch_and_nand:
2340 case Builtin::BI__sync_fetch_and_nand_1:
2341 case Builtin::BI__sync_fetch_and_nand_2:
2342 case Builtin::BI__sync_fetch_and_nand_4:
2343 case Builtin::BI__sync_fetch_and_nand_8:
2344 case Builtin::BI__sync_fetch_and_nand_16:
2345 BuiltinIndex = 5;
2346 WarnAboutSemanticsChange = true;
2347 break;
2348
Douglas Gregor73722482011-11-28 16:30:08 +00002349 case Builtin::BI__sync_add_and_fetch:
2350 case Builtin::BI__sync_add_and_fetch_1:
2351 case Builtin::BI__sync_add_and_fetch_2:
2352 case Builtin::BI__sync_add_and_fetch_4:
2353 case Builtin::BI__sync_add_and_fetch_8:
2354 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002355 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002356 break;
2357
2358 case Builtin::BI__sync_sub_and_fetch:
2359 case Builtin::BI__sync_sub_and_fetch_1:
2360 case Builtin::BI__sync_sub_and_fetch_2:
2361 case Builtin::BI__sync_sub_and_fetch_4:
2362 case Builtin::BI__sync_sub_and_fetch_8:
2363 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002364 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002365 break;
2366
2367 case Builtin::BI__sync_and_and_fetch:
2368 case Builtin::BI__sync_and_and_fetch_1:
2369 case Builtin::BI__sync_and_and_fetch_2:
2370 case Builtin::BI__sync_and_and_fetch_4:
2371 case Builtin::BI__sync_and_and_fetch_8:
2372 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002373 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002374 break;
2375
2376 case Builtin::BI__sync_or_and_fetch:
2377 case Builtin::BI__sync_or_and_fetch_1:
2378 case Builtin::BI__sync_or_and_fetch_2:
2379 case Builtin::BI__sync_or_and_fetch_4:
2380 case Builtin::BI__sync_or_and_fetch_8:
2381 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002382 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002383 break;
2384
2385 case Builtin::BI__sync_xor_and_fetch:
2386 case Builtin::BI__sync_xor_and_fetch_1:
2387 case Builtin::BI__sync_xor_and_fetch_2:
2388 case Builtin::BI__sync_xor_and_fetch_4:
2389 case Builtin::BI__sync_xor_and_fetch_8:
2390 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002391 BuiltinIndex = 10;
2392 break;
2393
2394 case Builtin::BI__sync_nand_and_fetch:
2395 case Builtin::BI__sync_nand_and_fetch_1:
2396 case Builtin::BI__sync_nand_and_fetch_2:
2397 case Builtin::BI__sync_nand_and_fetch_4:
2398 case Builtin::BI__sync_nand_and_fetch_8:
2399 case Builtin::BI__sync_nand_and_fetch_16:
2400 BuiltinIndex = 11;
2401 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002402 break;
Mike Stump11289f42009-09-09 15:08:12 +00002403
Chris Lattnerdc046542009-05-08 06:58:22 +00002404 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002405 case Builtin::BI__sync_val_compare_and_swap_1:
2406 case Builtin::BI__sync_val_compare_and_swap_2:
2407 case Builtin::BI__sync_val_compare_and_swap_4:
2408 case Builtin::BI__sync_val_compare_and_swap_8:
2409 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002410 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002411 NumFixed = 2;
2412 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002413
Chris Lattnerdc046542009-05-08 06:58:22 +00002414 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002415 case Builtin::BI__sync_bool_compare_and_swap_1:
2416 case Builtin::BI__sync_bool_compare_and_swap_2:
2417 case Builtin::BI__sync_bool_compare_and_swap_4:
2418 case Builtin::BI__sync_bool_compare_and_swap_8:
2419 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002420 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002421 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002422 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002423 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002424
2425 case Builtin::BI__sync_lock_test_and_set:
2426 case Builtin::BI__sync_lock_test_and_set_1:
2427 case Builtin::BI__sync_lock_test_and_set_2:
2428 case Builtin::BI__sync_lock_test_and_set_4:
2429 case Builtin::BI__sync_lock_test_and_set_8:
2430 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002431 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002432 break;
2433
Chris Lattnerdc046542009-05-08 06:58:22 +00002434 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002435 case Builtin::BI__sync_lock_release_1:
2436 case Builtin::BI__sync_lock_release_2:
2437 case Builtin::BI__sync_lock_release_4:
2438 case Builtin::BI__sync_lock_release_8:
2439 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002440 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002441 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002442 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002443 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002444
2445 case Builtin::BI__sync_swap:
2446 case Builtin::BI__sync_swap_1:
2447 case Builtin::BI__sync_swap_2:
2448 case Builtin::BI__sync_swap_4:
2449 case Builtin::BI__sync_swap_8:
2450 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002451 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002452 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002453 }
Mike Stump11289f42009-09-09 15:08:12 +00002454
Chris Lattnerdc046542009-05-08 06:58:22 +00002455 // Now that we know how many fixed arguments we expect, first check that we
2456 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002457 if (TheCall->getNumArgs() < 1+NumFixed) {
2458 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2459 << 0 << 1+NumFixed << TheCall->getNumArgs()
2460 << TheCall->getCallee()->getSourceRange();
2461 return ExprError();
2462 }
Mike Stump11289f42009-09-09 15:08:12 +00002463
Hal Finkeld2208b52014-10-02 20:53:50 +00002464 if (WarnAboutSemanticsChange) {
2465 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2466 << TheCall->getCallee()->getSourceRange();
2467 }
2468
Chris Lattner5b9241b2009-05-08 15:36:58 +00002469 // Get the decl for the concrete builtin from this, we can tell what the
2470 // concrete integer type we should convert to is.
2471 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002472 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002473 FunctionDecl *NewBuiltinDecl;
2474 if (NewBuiltinID == BuiltinID)
2475 NewBuiltinDecl = FDecl;
2476 else {
2477 // Perform builtin lookup to avoid redeclaring it.
2478 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2479 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2480 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2481 assert(Res.getFoundDecl());
2482 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002483 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002484 return ExprError();
2485 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002486
John McCallcf142162010-08-07 06:22:56 +00002487 // The first argument --- the pointer --- has a fixed type; we
2488 // deduce the types of the rest of the arguments accordingly. Walk
2489 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002490 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002491 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Chris Lattnerdc046542009-05-08 06:58:22 +00002493 // GCC does an implicit conversion to the pointer or integer ValType. This
2494 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002495 // Initialize the argument.
2496 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2497 ValType, /*consume*/ false);
2498 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002499 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002500 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattnerdc046542009-05-08 06:58:22 +00002502 // Okay, we have something that *can* be converted to the right type. Check
2503 // to see if there is a potentially weird extension going on here. This can
2504 // happen when you do an atomic operation on something like an char* and
2505 // pass in 42. The 42 gets converted to char. This is even more strange
2506 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002507 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002508 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002509 }
Mike Stump11289f42009-09-09 15:08:12 +00002510
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002511 ASTContext& Context = this->getASTContext();
2512
2513 // Create a new DeclRefExpr to refer to the new decl.
2514 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2515 Context,
2516 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002517 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002518 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002519 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002520 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002521 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002522 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002523
Chris Lattnerdc046542009-05-08 06:58:22 +00002524 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002525 // FIXME: This loses syntactic information.
2526 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2527 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2528 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002529 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002530
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002531 // Change the result type of the call to match the original value type. This
2532 // is arbitrary, but the codegen for these builtins ins design to handle it
2533 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002534 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002535
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002536 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002537}
2538
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002539/// SemaBuiltinNontemporalOverloaded - We have a call to
2540/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2541/// overloaded function based on the pointer type of its last argument.
2542///
2543/// This function goes through and does final semantic checking for these
2544/// builtins.
2545ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2546 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2547 DeclRefExpr *DRE =
2548 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2549 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2550 unsigned BuiltinID = FDecl->getBuiltinID();
2551 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2552 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2553 "Unexpected nontemporal load/store builtin!");
2554 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2555 unsigned numArgs = isStore ? 2 : 1;
2556
2557 // Ensure that we have the proper number of arguments.
2558 if (checkArgCount(*this, TheCall, numArgs))
2559 return ExprError();
2560
2561 // Inspect the last argument of the nontemporal builtin. This should always
2562 // be a pointer type, from which we imply the type of the memory access.
2563 // Because it is a pointer type, we don't have to worry about any implicit
2564 // casts here.
2565 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2566 ExprResult PointerArgResult =
2567 DefaultFunctionArrayLvalueConversion(PointerArg);
2568
2569 if (PointerArgResult.isInvalid())
2570 return ExprError();
2571 PointerArg = PointerArgResult.get();
2572 TheCall->setArg(numArgs - 1, PointerArg);
2573
2574 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2575 if (!pointerType) {
2576 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2577 << PointerArg->getType() << PointerArg->getSourceRange();
2578 return ExprError();
2579 }
2580
2581 QualType ValType = pointerType->getPointeeType();
2582
2583 // Strip any qualifiers off ValType.
2584 ValType = ValType.getUnqualifiedType();
2585 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2586 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2587 !ValType->isVectorType()) {
2588 Diag(DRE->getLocStart(),
2589 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2590 << PointerArg->getType() << PointerArg->getSourceRange();
2591 return ExprError();
2592 }
2593
2594 if (!isStore) {
2595 TheCall->setType(ValType);
2596 return TheCallResult;
2597 }
2598
2599 ExprResult ValArg = TheCall->getArg(0);
2600 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2601 Context, ValType, /*consume*/ false);
2602 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2603 if (ValArg.isInvalid())
2604 return ExprError();
2605
2606 TheCall->setArg(0, ValArg.get());
2607 TheCall->setType(Context.VoidTy);
2608 return TheCallResult;
2609}
2610
Chris Lattner6436fb62009-02-18 06:01:06 +00002611/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002612/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002613/// Note: It might also make sense to do the UTF-16 conversion here (would
2614/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002615bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002616 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002617 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2618
Douglas Gregorfb65e592011-07-27 05:40:30 +00002619 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002620 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2621 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002622 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002625 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002627 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002628 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002629 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002630 UTF16 *ToPtr = &ToBuf[0];
2631
2632 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2633 &ToPtr, ToPtr + NumBytes,
2634 strictConversion);
2635 // Check for conversion failure.
2636 if (Result != conversionOK)
2637 Diag(Arg->getLocStart(),
2638 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2639 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002640 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002641}
2642
Charles Davisc7d5c942015-09-17 20:55:33 +00002643/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2644/// for validity. Emit an error and return true on failure; return false
2645/// on success.
2646bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002647 Expr *Fn = TheCall->getCallee();
2648 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002649 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002650 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002651 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2652 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002653 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002654 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002655 return true;
2656 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002657
2658 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002659 return Diag(TheCall->getLocEnd(),
2660 diag::err_typecheck_call_too_few_args_at_least)
2661 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002662 }
2663
John McCall29ad95b2011-08-27 01:09:30 +00002664 // Type-check the first argument normally.
2665 if (checkBuiltinArgument(*this, TheCall, 0))
2666 return true;
2667
Chris Lattnere202e6a2007-12-20 00:05:45 +00002668 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002669 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002670 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002671 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002672 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002673 else if (FunctionDecl *FD = getCurFunctionDecl())
2674 isVariadic = FD->isVariadic();
2675 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002676 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002677
Chris Lattnere202e6a2007-12-20 00:05:45 +00002678 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002679 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2680 return true;
2681 }
Mike Stump11289f42009-09-09 15:08:12 +00002682
Chris Lattner43be2e62007-12-19 23:59:04 +00002683 // Verify that the second argument to the builtin is the last argument of the
2684 // current function or method.
2685 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002686 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002687
Nico Weber9eea7642013-05-24 23:31:57 +00002688 // These are valid if SecondArgIsLastNamedArgument is false after the next
2689 // block.
2690 QualType Type;
2691 SourceLocation ParamLoc;
2692
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002693 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2694 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002695 // FIXME: This isn't correct for methods (results in bogus warning).
2696 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002697 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002698 if (CurBlock)
2699 LastArg = *(CurBlock->TheDecl->param_end()-1);
2700 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002701 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002702 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002703 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002704 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002705
2706 Type = PV->getType();
2707 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002708 }
2709 }
Mike Stump11289f42009-09-09 15:08:12 +00002710
Chris Lattner43be2e62007-12-19 23:59:04 +00002711 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002712 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002713 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002714 else if (Type->isReferenceType()) {
2715 Diag(Arg->getLocStart(),
2716 diag::warn_va_start_of_reference_type_is_undefined);
2717 Diag(ParamLoc, diag::note_parameter_type) << Type;
2718 }
2719
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002720 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002721 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002722}
Chris Lattner43be2e62007-12-19 23:59:04 +00002723
Charles Davisc7d5c942015-09-17 20:55:33 +00002724/// Check the arguments to '__builtin_va_start' for validity, and that
2725/// it was called from a function of the native ABI.
2726/// Emit an error and return true on failure; return false on success.
2727bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2728 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2729 // On x64 Windows, don't allow this in System V ABI functions.
2730 // (Yes, that means there's no corresponding way to support variadic
2731 // System V ABI functions on Windows.)
2732 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2733 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2734 clang::CallingConv CC = CC_C;
2735 if (const FunctionDecl *FD = getCurFunctionDecl())
2736 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2737 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2738 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2739 return Diag(TheCall->getCallee()->getLocStart(),
2740 diag::err_va_start_used_in_wrong_abi_function)
2741 << (OS != llvm::Triple::Win32);
2742 }
2743 return SemaBuiltinVAStartImpl(TheCall);
2744}
2745
2746/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2747/// it was called from a Win64 ABI function.
2748/// Emit an error and return true on failure; return false on success.
2749bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2750 // This only makes sense for x86-64.
2751 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2752 Expr *Callee = TheCall->getCallee();
2753 if (TT.getArch() != llvm::Triple::x86_64)
2754 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2755 // Don't allow this in System V ABI functions.
2756 clang::CallingConv CC = CC_C;
2757 if (const FunctionDecl *FD = getCurFunctionDecl())
2758 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2759 if (CC == CC_X86_64SysV ||
2760 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2761 return Diag(Callee->getLocStart(),
2762 diag::err_ms_va_start_used_in_sysv_function);
2763 return SemaBuiltinVAStartImpl(TheCall);
2764}
2765
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002766bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2767 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2768 // const char *named_addr);
2769
2770 Expr *Func = Call->getCallee();
2771
2772 if (Call->getNumArgs() < 3)
2773 return Diag(Call->getLocEnd(),
2774 diag::err_typecheck_call_too_few_args_at_least)
2775 << 0 /*function call*/ << 3 << Call->getNumArgs();
2776
2777 // Determine whether the current function is variadic or not.
2778 bool IsVariadic;
2779 if (BlockScopeInfo *CurBlock = getCurBlock())
2780 IsVariadic = CurBlock->TheDecl->isVariadic();
2781 else if (FunctionDecl *FD = getCurFunctionDecl())
2782 IsVariadic = FD->isVariadic();
2783 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2784 IsVariadic = MD->isVariadic();
2785 else
2786 llvm_unreachable("unexpected statement type");
2787
2788 if (!IsVariadic) {
2789 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2790 return true;
2791 }
2792
2793 // Type-check the first argument normally.
2794 if (checkBuiltinArgument(*this, Call, 0))
2795 return true;
2796
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002797 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002798 unsigned ArgNo;
2799 QualType Type;
2800 } ArgumentTypes[] = {
2801 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2802 { 2, Context.getSizeType() },
2803 };
2804
2805 for (const auto &AT : ArgumentTypes) {
2806 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2807 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2808 continue;
2809 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2810 << Arg->getType() << AT.Type << 1 /* different class */
2811 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2812 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2813 }
2814
2815 return false;
2816}
2817
Chris Lattner2da14fb2007-12-20 00:26:33 +00002818/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2819/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002820bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2821 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002822 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002823 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002824 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002825 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002826 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002827 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002828 << SourceRange(TheCall->getArg(2)->getLocStart(),
2829 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002830
John Wiegley01296292011-04-08 18:41:53 +00002831 ExprResult OrigArg0 = TheCall->getArg(0);
2832 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002833
Chris Lattner2da14fb2007-12-20 00:26:33 +00002834 // Do standard promotions between the two arguments, returning their common
2835 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002836 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002837 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2838 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002839
2840 // Make sure any conversions are pushed back into the call; this is
2841 // type safe since unordered compare builtins are declared as "_Bool
2842 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002843 TheCall->setArg(0, OrigArg0.get());
2844 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002845
John Wiegley01296292011-04-08 18:41:53 +00002846 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002847 return false;
2848
Chris Lattner2da14fb2007-12-20 00:26:33 +00002849 // If the common type isn't a real floating type, then the arguments were
2850 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002851 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002852 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002853 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002854 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2855 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002856
Chris Lattner2da14fb2007-12-20 00:26:33 +00002857 return false;
2858}
2859
Benjamin Kramer634fc102010-02-15 22:42:31 +00002860/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2861/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002862/// to check everything. We expect the last argument to be a floating point
2863/// value.
2864bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2865 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002866 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002867 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002868 if (TheCall->getNumArgs() > NumArgs)
2869 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002870 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002871 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002872 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002873 (*(TheCall->arg_end()-1))->getLocEnd());
2874
Benjamin Kramer64aae502010-02-16 10:07:31 +00002875 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002876
Eli Friedman7e4faac2009-08-31 20:06:00 +00002877 if (OrigArg->isTypeDependent())
2878 return false;
2879
Chris Lattner68784ef2010-05-06 05:50:07 +00002880 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002881 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002882 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002883 diag::err_typecheck_call_invalid_unary_fp)
2884 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002885
Chris Lattner68784ef2010-05-06 05:50:07 +00002886 // If this is an implicit conversion from float -> double, remove it.
2887 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2888 Expr *CastArg = Cast->getSubExpr();
2889 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2890 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2891 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002892 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002893 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002894 }
2895 }
2896
Eli Friedman7e4faac2009-08-31 20:06:00 +00002897 return false;
2898}
2899
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002900/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2901// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002902ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002903 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002904 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002905 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002906 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2907 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002908
Nate Begemana0110022010-06-08 00:16:34 +00002909 // Determine which of the following types of shufflevector we're checking:
2910 // 1) unary, vector mask: (lhs, mask)
2911 // 2) binary, vector mask: (lhs, rhs, mask)
2912 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2913 QualType resType = TheCall->getArg(0)->getType();
2914 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002915
Douglas Gregorc25f7662009-05-19 22:10:17 +00002916 if (!TheCall->getArg(0)->isTypeDependent() &&
2917 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002918 QualType LHSType = TheCall->getArg(0)->getType();
2919 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002920
Craig Topperbaca3892013-07-29 06:47:04 +00002921 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2922 return ExprError(Diag(TheCall->getLocStart(),
2923 diag::err_shufflevector_non_vector)
2924 << SourceRange(TheCall->getArg(0)->getLocStart(),
2925 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002926
Nate Begemana0110022010-06-08 00:16:34 +00002927 numElements = LHSType->getAs<VectorType>()->getNumElements();
2928 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002929
Nate Begemana0110022010-06-08 00:16:34 +00002930 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2931 // with mask. If so, verify that RHS is an integer vector type with the
2932 // same number of elts as lhs.
2933 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002934 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002935 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002936 return ExprError(Diag(TheCall->getLocStart(),
2937 diag::err_shufflevector_incompatible_vector)
2938 << SourceRange(TheCall->getArg(1)->getLocStart(),
2939 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002940 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002941 return ExprError(Diag(TheCall->getLocStart(),
2942 diag::err_shufflevector_incompatible_vector)
2943 << SourceRange(TheCall->getArg(0)->getLocStart(),
2944 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002945 } else if (numElements != numResElements) {
2946 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002947 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002948 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002949 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002950 }
2951
2952 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002953 if (TheCall->getArg(i)->isTypeDependent() ||
2954 TheCall->getArg(i)->isValueDependent())
2955 continue;
2956
Nate Begemana0110022010-06-08 00:16:34 +00002957 llvm::APSInt Result(32);
2958 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2959 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002960 diag::err_shufflevector_nonconstant_argument)
2961 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002962
Craig Topper50ad5b72013-08-03 17:40:38 +00002963 // Allow -1 which will be translated to undef in the IR.
2964 if (Result.isSigned() && Result.isAllOnesValue())
2965 continue;
2966
Chris Lattner7ab824e2008-08-10 02:05:13 +00002967 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002969 diag::err_shufflevector_argument_too_large)
2970 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002971 }
2972
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002973 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002974
Chris Lattner7ab824e2008-08-10 02:05:13 +00002975 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002976 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002977 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002978 }
2979
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002980 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2981 TheCall->getCallee()->getLocStart(),
2982 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002983}
Chris Lattner43be2e62007-12-19 23:59:04 +00002984
Hal Finkelc4d7c822013-09-18 03:29:45 +00002985/// SemaConvertVectorExpr - Handle __builtin_convertvector
2986ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2987 SourceLocation BuiltinLoc,
2988 SourceLocation RParenLoc) {
2989 ExprValueKind VK = VK_RValue;
2990 ExprObjectKind OK = OK_Ordinary;
2991 QualType DstTy = TInfo->getType();
2992 QualType SrcTy = E->getType();
2993
2994 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2995 return ExprError(Diag(BuiltinLoc,
2996 diag::err_convertvector_non_vector)
2997 << E->getSourceRange());
2998 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2999 return ExprError(Diag(BuiltinLoc,
3000 diag::err_convertvector_non_vector_type));
3001
3002 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3003 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3004 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3005 if (SrcElts != DstElts)
3006 return ExprError(Diag(BuiltinLoc,
3007 diag::err_convertvector_incompatible_vector)
3008 << E->getSourceRange());
3009 }
3010
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003011 return new (Context)
3012 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003013}
3014
Daniel Dunbarb7257262008-07-21 22:59:13 +00003015/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3016// This is declared to take (const void*, ...) and can take two
3017// optional constant int args.
3018bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003019 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003020
Chris Lattner3b054132008-11-19 05:08:23 +00003021 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003022 return Diag(TheCall->getLocEnd(),
3023 diag::err_typecheck_call_too_many_args_at_most)
3024 << 0 /*function call*/ << 3 << NumArgs
3025 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003026
3027 // Argument 0 is checked for us and the remaining arguments must be
3028 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003029 for (unsigned i = 1; i != NumArgs; ++i)
3030 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003031 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003032
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003033 return false;
3034}
3035
Hal Finkelf0417332014-07-17 14:25:55 +00003036/// SemaBuiltinAssume - Handle __assume (MS Extension).
3037// __assume does not evaluate its arguments, and should warn if its argument
3038// has side effects.
3039bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3040 Expr *Arg = TheCall->getArg(0);
3041 if (Arg->isInstantiationDependent()) return false;
3042
3043 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003044 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003045 << Arg->getSourceRange()
3046 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3047
3048 return false;
3049}
3050
3051/// Handle __builtin_assume_aligned. This is declared
3052/// as (const void*, size_t, ...) and can take one optional constant int arg.
3053bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3054 unsigned NumArgs = TheCall->getNumArgs();
3055
3056 if (NumArgs > 3)
3057 return Diag(TheCall->getLocEnd(),
3058 diag::err_typecheck_call_too_many_args_at_most)
3059 << 0 /*function call*/ << 3 << NumArgs
3060 << TheCall->getSourceRange();
3061
3062 // The alignment must be a constant integer.
3063 Expr *Arg = TheCall->getArg(1);
3064
3065 // We can't check the value of a dependent argument.
3066 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3067 llvm::APSInt Result;
3068 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3069 return true;
3070
3071 if (!Result.isPowerOf2())
3072 return Diag(TheCall->getLocStart(),
3073 diag::err_alignment_not_power_of_two)
3074 << Arg->getSourceRange();
3075 }
3076
3077 if (NumArgs > 2) {
3078 ExprResult Arg(TheCall->getArg(2));
3079 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3080 Context.getSizeType(), false);
3081 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3082 if (Arg.isInvalid()) return true;
3083 TheCall->setArg(2, Arg.get());
3084 }
Hal Finkelf0417332014-07-17 14:25:55 +00003085
3086 return false;
3087}
3088
Eric Christopher8d0c6212010-04-17 02:26:23 +00003089/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3090/// TheCall is a constant expression.
3091bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3092 llvm::APSInt &Result) {
3093 Expr *Arg = TheCall->getArg(ArgNum);
3094 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3095 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3096
3097 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3098
3099 if (!Arg->isIntegerConstantExpr(Result, Context))
3100 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003101 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003102
Chris Lattnerd545ad12009-09-23 06:06:36 +00003103 return false;
3104}
3105
Richard Sandiford28940af2014-04-16 08:47:51 +00003106/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3107/// TheCall is a constant expression in the range [Low, High].
3108bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3109 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003110 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003111
3112 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003113 Expr *Arg = TheCall->getArg(ArgNum);
3114 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003115 return false;
3116
Eric Christopher8d0c6212010-04-17 02:26:23 +00003117 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003119 return true;
3120
Richard Sandiford28940af2014-04-16 08:47:51 +00003121 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003122 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003123 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003124
3125 return false;
3126}
3127
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003128/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3129/// TheCall is an ARM/AArch64 special register string literal.
3130bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3131 int ArgNum, unsigned ExpectedFieldNum,
3132 bool AllowName) {
3133 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3134 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3135 BuiltinID == ARM::BI__builtin_arm_rsr ||
3136 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3137 BuiltinID == ARM::BI__builtin_arm_wsr ||
3138 BuiltinID == ARM::BI__builtin_arm_wsrp;
3139 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3140 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3141 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3142 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3143 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3144 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3145 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3146
3147 // We can't check the value of a dependent argument.
3148 Expr *Arg = TheCall->getArg(ArgNum);
3149 if (Arg->isTypeDependent() || Arg->isValueDependent())
3150 return false;
3151
3152 // Check if the argument is a string literal.
3153 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3154 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3155 << Arg->getSourceRange();
3156
3157 // Check the type of special register given.
3158 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3159 SmallVector<StringRef, 6> Fields;
3160 Reg.split(Fields, ":");
3161
3162 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3163 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3164 << Arg->getSourceRange();
3165
3166 // If the string is the name of a register then we cannot check that it is
3167 // valid here but if the string is of one the forms described in ACLE then we
3168 // can check that the supplied fields are integers and within the valid
3169 // ranges.
3170 if (Fields.size() > 1) {
3171 bool FiveFields = Fields.size() == 5;
3172
3173 bool ValidString = true;
3174 if (IsARMBuiltin) {
3175 ValidString &= Fields[0].startswith_lower("cp") ||
3176 Fields[0].startswith_lower("p");
3177 if (ValidString)
3178 Fields[0] =
3179 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3180
3181 ValidString &= Fields[2].startswith_lower("c");
3182 if (ValidString)
3183 Fields[2] = Fields[2].drop_front(1);
3184
3185 if (FiveFields) {
3186 ValidString &= Fields[3].startswith_lower("c");
3187 if (ValidString)
3188 Fields[3] = Fields[3].drop_front(1);
3189 }
3190 }
3191
3192 SmallVector<int, 5> Ranges;
3193 if (FiveFields)
3194 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3195 else
3196 Ranges.append({15, 7, 15});
3197
3198 for (unsigned i=0; i<Fields.size(); ++i) {
3199 int IntField;
3200 ValidString &= !Fields[i].getAsInteger(10, IntField);
3201 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3202 }
3203
3204 if (!ValidString)
3205 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3206 << Arg->getSourceRange();
3207
3208 } else if (IsAArch64Builtin && Fields.size() == 1) {
3209 // If the register name is one of those that appear in the condition below
3210 // and the special register builtin being used is one of the write builtins,
3211 // then we require that the argument provided for writing to the register
3212 // is an integer constant expression. This is because it will be lowered to
3213 // an MSR (immediate) instruction, so we need to know the immediate at
3214 // compile time.
3215 if (TheCall->getNumArgs() != 2)
3216 return false;
3217
3218 std::string RegLower = Reg.lower();
3219 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3220 RegLower != "pan" && RegLower != "uao")
3221 return false;
3222
3223 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3224 }
3225
3226 return false;
3227}
3228
Eli Friedmanc97d0142009-05-03 06:04:26 +00003229/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003230/// This checks that the target supports __builtin_longjmp and
3231/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003232bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003233 if (!Context.getTargetInfo().hasSjLjLowering())
3234 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3235 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3236
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003237 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003238 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003239
Eric Christopher8d0c6212010-04-17 02:26:23 +00003240 // TODO: This is less than ideal. Overload this to take a value.
3241 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3242 return true;
3243
3244 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003245 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3246 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3247
3248 return false;
3249}
3250
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003251/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3252/// This checks that the target supports __builtin_setjmp.
3253bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3254 if (!Context.getTargetInfo().hasSjLjLowering())
3255 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3256 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3257 return false;
3258}
3259
Richard Smithd7293d72013-08-05 18:49:43 +00003260namespace {
3261enum StringLiteralCheckType {
3262 SLCT_NotALiteral,
3263 SLCT_UncheckedLiteral,
3264 SLCT_CheckedLiteral
3265};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003266} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003267
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003268static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3269 const Expr *OrigFormatExpr,
3270 ArrayRef<const Expr *> Args,
3271 bool HasVAListArg, unsigned format_idx,
3272 unsigned firstDataArg,
3273 Sema::FormatStringType Type,
3274 bool inFunctionCall,
3275 Sema::VariadicCallType CallType,
3276 llvm::SmallBitVector &CheckedVarArgs);
3277
Richard Smith55ce3522012-06-25 20:30:08 +00003278// Determine if an expression is a string literal or constant string.
3279// If this function returns false on the arguments to a function expecting a
3280// format string, we will usually need to emit a warning.
3281// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003282static StringLiteralCheckType
3283checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3284 bool HasVAListArg, unsigned format_idx,
3285 unsigned firstDataArg, Sema::FormatStringType Type,
3286 Sema::VariadicCallType CallType, bool InFunctionCall,
3287 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003288 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003289 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003290 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003291
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003292 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003293
Richard Smithd7293d72013-08-05 18:49:43 +00003294 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003295 // Technically -Wformat-nonliteral does not warn about this case.
3296 // The behavior of printf and friends in this case is implementation
3297 // dependent. Ideally if the format string cannot be null then
3298 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003299 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003300
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003301 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003302 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003303 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003304 // The expression is a literal if both sub-expressions were, and it was
3305 // completely checked only if both sub-expressions were checked.
3306 const AbstractConditionalOperator *C =
3307 cast<AbstractConditionalOperator>(E);
3308 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003309 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003310 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003311 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003312 if (Left == SLCT_NotALiteral)
3313 return SLCT_NotALiteral;
3314 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003315 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003316 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003317 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003318 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003319 }
3320
3321 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003322 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3323 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003324 }
3325
John McCallc07a0c72011-02-17 10:25:35 +00003326 case Stmt::OpaqueValueExprClass:
3327 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3328 E = src;
3329 goto tryAgain;
3330 }
Richard Smith55ce3522012-06-25 20:30:08 +00003331 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003332
Ted Kremeneka8890832011-02-24 23:03:04 +00003333 case Stmt::PredefinedExprClass:
3334 // While __func__, etc., are technically not string literals, they
3335 // cannot contain format specifiers and thus are not a security
3336 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003337 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003338
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003339 case Stmt::DeclRefExprClass: {
3340 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003341
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003342 // As an exception, do not flag errors for variables binding to
3343 // const string literals.
3344 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3345 bool isConstant = false;
3346 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003347
Richard Smithd7293d72013-08-05 18:49:43 +00003348 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3349 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003350 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003351 isConstant = T.isConstant(S.Context) &&
3352 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003353 } else if (T->isObjCObjectPointerType()) {
3354 // In ObjC, there is usually no "const ObjectPointer" type,
3355 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003356 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003357 }
Mike Stump11289f42009-09-09 15:08:12 +00003358
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003359 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003360 if (const Expr *Init = VD->getAnyInitializer()) {
3361 // Look through initializers like const char c[] = { "foo" }
3362 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3363 if (InitList->isStringLiteralInit())
3364 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3365 }
Richard Smithd7293d72013-08-05 18:49:43 +00003366 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003367 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003368 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003369 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003370 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003371 }
Mike Stump11289f42009-09-09 15:08:12 +00003372
Anders Carlssonb012ca92009-06-28 19:55:58 +00003373 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3374 // special check to see if the format string is a function parameter
3375 // of the function calling the printf function. If the function
3376 // has an attribute indicating it is a printf-like function, then we
3377 // should suppress warnings concerning non-literals being used in a call
3378 // to a vprintf function. For example:
3379 //
3380 // void
3381 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3382 // va_list ap;
3383 // va_start(ap, fmt);
3384 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3385 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003386 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003387 if (HasVAListArg) {
3388 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3389 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3390 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003391 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003392 // adjust for implicit parameter
3393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3394 if (MD->isInstance())
3395 ++PVIndex;
3396 // We also check if the formats are compatible.
3397 // We can't pass a 'scanf' string to a 'printf' function.
3398 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003399 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003400 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003401 }
3402 }
3403 }
3404 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003405 }
Mike Stump11289f42009-09-09 15:08:12 +00003406
Richard Smith55ce3522012-06-25 20:30:08 +00003407 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003408 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003409
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003410 case Stmt::CallExprClass:
3411 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003412 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003413 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3414 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3415 unsigned ArgIndex = FA->getFormatIdx();
3416 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3417 if (MD->isInstance())
3418 --ArgIndex;
3419 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003420
Richard Smithd7293d72013-08-05 18:49:43 +00003421 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003422 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003423 Type, CallType, InFunctionCall,
3424 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003425 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3426 unsigned BuiltinID = FD->getBuiltinID();
3427 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3428 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3429 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003430 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003431 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003432 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003433 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003434 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003435 }
3436 }
Mike Stump11289f42009-09-09 15:08:12 +00003437
Richard Smith55ce3522012-06-25 20:30:08 +00003438 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003439 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003440 case Stmt::ObjCStringLiteralClass:
3441 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003442 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003443
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003444 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003445 StrE = ObjCFExpr->getString();
3446 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003447 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003448
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003449 if (StrE) {
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00003450 CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3451 firstDataArg, Type, InFunctionCall, CallType,
3452 CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003453 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003454 }
Mike Stump11289f42009-09-09 15:08:12 +00003455
Richard Smith55ce3522012-06-25 20:30:08 +00003456 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003457 }
Mike Stump11289f42009-09-09 15:08:12 +00003458
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003459 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003460 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003461 }
3462}
3463
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003464Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003465 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003466 .Case("scanf", FST_Scanf)
3467 .Cases("printf", "printf0", FST_Printf)
3468 .Cases("NSString", "CFString", FST_NSString)
3469 .Case("strftime", FST_Strftime)
3470 .Case("strfmon", FST_Strfmon)
3471 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003472 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003473 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003474 .Default(FST_Unknown);
3475}
3476
Jordan Rose3e0ec582012-07-19 18:10:23 +00003477/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003478/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003479/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003480bool Sema::CheckFormatArguments(const FormatAttr *Format,
3481 ArrayRef<const Expr *> Args,
3482 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003483 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003484 SourceLocation Loc, SourceRange Range,
3485 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003486 FormatStringInfo FSI;
3487 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003488 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003489 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003490 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003491 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003492}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003493
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003494bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003495 bool HasVAListArg, unsigned format_idx,
3496 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003497 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003498 SourceLocation Loc, SourceRange Range,
3499 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003500 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003501 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003502 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003503 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003504 }
Mike Stump11289f42009-09-09 15:08:12 +00003505
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003506 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003507
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003508 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003509 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003510 // Dynamically generated format strings are difficult to
3511 // automatically vet at compile time. Requiring that format strings
3512 // are string literals: (1) permits the checking of format strings by
3513 // the compiler and thereby (2) can practically remove the source of
3514 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003515
Mike Stump11289f42009-09-09 15:08:12 +00003516 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003517 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003518 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003519 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003520 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003521 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3522 format_idx, firstDataArg, Type, CallType,
3523 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003524 if (CT != SLCT_NotALiteral)
3525 // Literal format string found, check done!
3526 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003527
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003528 // Strftime is particular as it always uses a single 'time' argument,
3529 // so it is safe to pass a non-literal string.
3530 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003531 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003532
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003533 // Do not emit diag when the string param is a macro expansion and the
3534 // format is either NSString or CFString. This is a hack to prevent
3535 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3536 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003537 if (Type == FST_NSString &&
3538 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003539 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003540
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003541 // If there are no arguments specified, warn with -Wformat-security, otherwise
3542 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003543 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003544 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003545 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003546 << OrigFormatExpr->getSourceRange();
3547 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003548 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003549 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003550 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003551 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003552}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003553
Ted Kremenekab278de2010-01-28 23:39:18 +00003554namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003555class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3556protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003557 Sema &S;
3558 const StringLiteral *FExpr;
3559 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003560 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003561 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003562 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003563 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003564 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003565 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003566 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003567 bool usesPositionalArgs;
3568 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003569 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003570 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003571 llvm::SmallBitVector &CheckedVarArgs;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003572
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003573public:
Ted Kremenek02087932010-07-16 02:11:22 +00003574 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003575 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003576 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003577 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003578 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003579 Sema::VariadicCallType callType,
3580 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003581 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003582 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3583 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003584 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003585 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003586 inFunctionCall(inFunctionCall), CallType(callType),
3587 CheckedVarArgs(CheckedVarArgs) {
3588 CoveredArgs.resize(numDataArgs);
3589 CoveredArgs.reset();
3590 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003591
Ted Kremenek019d2242010-01-29 01:50:07 +00003592 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003593
Ted Kremenek02087932010-07-16 02:11:22 +00003594 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003595 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003596
Jordan Rose92303592012-09-08 04:00:03 +00003597 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003598 const analyze_format_string::FormatSpecifier &FS,
3599 const analyze_format_string::ConversionSpecifier &CS,
3600 const char *startSpecifier, unsigned specifierLen,
3601 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003602
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003603 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003604 const analyze_format_string::FormatSpecifier &FS,
3605 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003606
3607 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003608 const analyze_format_string::ConversionSpecifier &CS,
3609 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003610
Craig Toppere14c0f82014-03-12 04:55:44 +00003611 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003612
Craig Toppere14c0f82014-03-12 04:55:44 +00003613 void HandleInvalidPosition(const char *startSpecifier,
3614 unsigned specifierLen,
3615 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003616
Craig Toppere14c0f82014-03-12 04:55:44 +00003617 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003618
Craig Toppere14c0f82014-03-12 04:55:44 +00003619 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003620
Richard Trieu03cf7b72011-10-28 00:41:25 +00003621 template <typename Range>
3622 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3623 const Expr *ArgumentExpr,
3624 PartialDiagnostic PDiag,
3625 SourceLocation StringLoc,
3626 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003627 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003628
Ted Kremenek02087932010-07-16 02:11:22 +00003629protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003630 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3631 const char *startSpec,
3632 unsigned specifierLen,
3633 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003634
3635 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3636 const char *startSpec,
3637 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003638
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003639 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003640 CharSourceRange getSpecifierRange(const char *startSpecifier,
3641 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003642 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003643
Ted Kremenek5739de72010-01-29 01:06:55 +00003644 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003645
3646 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3647 const analyze_format_string::ConversionSpecifier &CS,
3648 const char *startSpecifier, unsigned specifierLen,
3649 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003650
3651 template <typename Range>
3652 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3653 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003654 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003655};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003656} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003657
Ted Kremenek02087932010-07-16 02:11:22 +00003658SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003659 return OrigFormatExpr->getSourceRange();
3660}
3661
Ted Kremenek02087932010-07-16 02:11:22 +00003662CharSourceRange CheckFormatHandler::
3663getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003664 SourceLocation Start = getLocationOfByte(startSpecifier);
3665 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3666
3667 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003668 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003669
3670 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003671}
3672
Ted Kremenek02087932010-07-16 02:11:22 +00003673SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003674 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003675}
3676
Ted Kremenek02087932010-07-16 02:11:22 +00003677void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3678 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003679 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3680 getLocationOfByte(startSpecifier),
3681 /*IsStringLocation*/true,
3682 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003683}
3684
Jordan Rose92303592012-09-08 04:00:03 +00003685void CheckFormatHandler::HandleInvalidLengthModifier(
3686 const analyze_format_string::FormatSpecifier &FS,
3687 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003688 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003689 using namespace analyze_format_string;
3690
3691 const LengthModifier &LM = FS.getLengthModifier();
3692 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3693
3694 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003695 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003696 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003697 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003698 getLocationOfByte(LM.getStart()),
3699 /*IsStringLocation*/true,
3700 getSpecifierRange(startSpecifier, specifierLen));
3701
3702 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3703 << FixedLM->toString()
3704 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3705
3706 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003707 FixItHint Hint;
3708 if (DiagID == diag::warn_format_nonsensical_length)
3709 Hint = FixItHint::CreateRemoval(LMRange);
3710
3711 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003712 getLocationOfByte(LM.getStart()),
3713 /*IsStringLocation*/true,
3714 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003715 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003716 }
3717}
3718
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003719void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003720 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003721 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003722 using namespace analyze_format_string;
3723
3724 const LengthModifier &LM = FS.getLengthModifier();
3725 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3726
3727 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003728 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003729 if (FixedLM) {
3730 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3731 << LM.toString() << 0,
3732 getLocationOfByte(LM.getStart()),
3733 /*IsStringLocation*/true,
3734 getSpecifierRange(startSpecifier, specifierLen));
3735
3736 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3737 << FixedLM->toString()
3738 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3739
3740 } else {
3741 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3742 << LM.toString() << 0,
3743 getLocationOfByte(LM.getStart()),
3744 /*IsStringLocation*/true,
3745 getSpecifierRange(startSpecifier, specifierLen));
3746 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003747}
3748
3749void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3750 const analyze_format_string::ConversionSpecifier &CS,
3751 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003752 using namespace analyze_format_string;
3753
3754 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003755 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003756 if (FixedCS) {
3757 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3758 << CS.toString() << /*conversion specifier*/1,
3759 getLocationOfByte(CS.getStart()),
3760 /*IsStringLocation*/true,
3761 getSpecifierRange(startSpecifier, specifierLen));
3762
3763 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3764 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3765 << FixedCS->toString()
3766 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3767 } else {
3768 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3769 << CS.toString() << /*conversion specifier*/1,
3770 getLocationOfByte(CS.getStart()),
3771 /*IsStringLocation*/true,
3772 getSpecifierRange(startSpecifier, specifierLen));
3773 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003774}
3775
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003776void CheckFormatHandler::HandlePosition(const char *startPos,
3777 unsigned posLen) {
3778 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3779 getLocationOfByte(startPos),
3780 /*IsStringLocation*/true,
3781 getSpecifierRange(startPos, posLen));
3782}
3783
Ted Kremenekd1668192010-02-27 01:41:03 +00003784void
Ted Kremenek02087932010-07-16 02:11:22 +00003785CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3786 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003787 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3788 << (unsigned) p,
3789 getLocationOfByte(startPos), /*IsStringLocation*/true,
3790 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003791}
3792
Ted Kremenek02087932010-07-16 02:11:22 +00003793void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003794 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003795 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3796 getLocationOfByte(startPos),
3797 /*IsStringLocation*/true,
3798 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003799}
3800
Ted Kremenek02087932010-07-16 02:11:22 +00003801void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003802 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003803 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003804 EmitFormatDiagnostic(
3805 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3806 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3807 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003808 }
Ted Kremenek02087932010-07-16 02:11:22 +00003809}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003810
Jordan Rose58bbe422012-07-19 18:10:08 +00003811// Note that this may return NULL if there was an error parsing or building
3812// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003813const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003814 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003815}
3816
3817void CheckFormatHandler::DoneProcessing() {
3818 // Does the number of data arguments exceed the number of
3819 // format conversions in the format string?
3820 if (!HasVAListArg) {
3821 // Find any arguments that weren't covered.
3822 CoveredArgs.flip();
3823 signed notCoveredArg = CoveredArgs.find_first();
3824 if (notCoveredArg >= 0) {
3825 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003826 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3827 SourceLocation Loc = E->getLocStart();
3828 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3830 Loc, /*IsStringLocation*/false,
3831 getFormatStringRange());
3832 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003833 }
Ted Kremenek02087932010-07-16 02:11:22 +00003834 }
3835 }
3836}
3837
Ted Kremenekce815422010-07-19 21:25:57 +00003838bool
3839CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3840 SourceLocation Loc,
3841 const char *startSpec,
3842 unsigned specifierLen,
3843 const char *csStart,
3844 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003845 bool keepGoing = true;
3846 if (argIndex < NumDataArgs) {
3847 // Consider the argument coverered, even though the specifier doesn't
3848 // make sense.
3849 CoveredArgs.set(argIndex);
3850 }
3851 else {
3852 // If argIndex exceeds the number of data arguments we
3853 // don't issue a warning because that is just a cascade of warnings (and
3854 // they may have intended '%%' anyway). We don't want to continue processing
3855 // the format string after this point, however, as we will like just get
3856 // gibberish when trying to match arguments.
3857 keepGoing = false;
3858 }
3859
Richard Trieu03cf7b72011-10-28 00:41:25 +00003860 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3861 << StringRef(csStart, csLen),
3862 Loc, /*IsStringLocation*/true,
3863 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003864
3865 return keepGoing;
3866}
3867
Richard Trieu03cf7b72011-10-28 00:41:25 +00003868void
3869CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3870 const char *startSpec,
3871 unsigned specifierLen) {
3872 EmitFormatDiagnostic(
3873 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3874 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3875}
3876
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003877bool
3878CheckFormatHandler::CheckNumArgs(
3879 const analyze_format_string::FormatSpecifier &FS,
3880 const analyze_format_string::ConversionSpecifier &CS,
3881 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3882
3883 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003884 PartialDiagnostic PDiag = FS.usesPositionalArg()
3885 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3886 << (argIndex+1) << NumDataArgs)
3887 : S.PDiag(diag::warn_printf_insufficient_data_args);
3888 EmitFormatDiagnostic(
3889 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3890 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003891 return false;
3892 }
3893 return true;
3894}
3895
Richard Trieu03cf7b72011-10-28 00:41:25 +00003896template<typename Range>
3897void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3898 SourceLocation Loc,
3899 bool IsStringLocation,
3900 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003901 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003902 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003903 Loc, IsStringLocation, StringRange, FixIt);
3904}
3905
3906/// \brief If the format string is not within the funcion call, emit a note
3907/// so that the function call and string are in diagnostic messages.
3908///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003909/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003910/// call and only one diagnostic message will be produced. Otherwise, an
3911/// extra note will be emitted pointing to location of the format string.
3912///
3913/// \param ArgumentExpr the expression that is passed as the format string
3914/// argument in the function call. Used for getting locations when two
3915/// diagnostics are emitted.
3916///
3917/// \param PDiag the callee should already have provided any strings for the
3918/// diagnostic message. This function only adds locations and fixits
3919/// to diagnostics.
3920///
3921/// \param Loc primary location for diagnostic. If two diagnostics are
3922/// required, one will be at Loc and a new SourceLocation will be created for
3923/// the other one.
3924///
3925/// \param IsStringLocation if true, Loc points to the format string should be
3926/// used for the note. Otherwise, Loc points to the argument list and will
3927/// be used with PDiag.
3928///
3929/// \param StringRange some or all of the string to highlight. This is
3930/// templated so it can accept either a CharSourceRange or a SourceRange.
3931///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003932/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003933template<typename Range>
3934void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3935 const Expr *ArgumentExpr,
3936 PartialDiagnostic PDiag,
3937 SourceLocation Loc,
3938 bool IsStringLocation,
3939 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003940 ArrayRef<FixItHint> FixIt) {
3941 if (InFunctionCall) {
3942 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3943 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003944 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003945 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003946 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3947 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003948
3949 const Sema::SemaDiagnosticBuilder &Note =
3950 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3951 diag::note_format_string_defined);
3952
3953 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003954 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003955 }
3956}
3957
Ted Kremenek02087932010-07-16 02:11:22 +00003958//===--- CHECK: Printf format string checking ------------------------------===//
3959
3960namespace {
3961class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003962 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003963
Ted Kremenek02087932010-07-16 02:11:22 +00003964public:
3965 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3966 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003967 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003968 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003969 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003970 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003971 Sema::VariadicCallType CallType,
3972 llvm::SmallBitVector &CheckedVarArgs)
3973 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3974 numDataArgs, beg, hasVAListArg, Args,
3975 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3976 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003977 {}
3978
Ted Kremenek02087932010-07-16 02:11:22 +00003979 bool HandleInvalidPrintfConversionSpecifier(
3980 const analyze_printf::PrintfSpecifier &FS,
3981 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003982 unsigned specifierLen) override;
3983
Ted Kremenek02087932010-07-16 02:11:22 +00003984 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3985 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003986 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003987 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3988 const char *StartSpecifier,
3989 unsigned SpecifierLen,
3990 const Expr *E);
3991
Ted Kremenek02087932010-07-16 02:11:22 +00003992 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3993 const char *startSpecifier, unsigned specifierLen);
3994 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3995 const analyze_printf::OptionalAmount &Amt,
3996 unsigned type,
3997 const char *startSpecifier, unsigned specifierLen);
3998 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3999 const analyze_printf::OptionalFlag &flag,
4000 const char *startSpecifier, unsigned specifierLen);
4001 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4002 const analyze_printf::OptionalFlag &ignoredFlag,
4003 const analyze_printf::OptionalFlag &flag,
4004 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004005 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00004006 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00004007
4008 void HandleEmptyObjCModifierFlag(const char *startFlag,
4009 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00004010
Ted Kremenek2b417712015-07-02 05:39:16 +00004011 void HandleInvalidObjCModifierFlag(const char *startFlag,
4012 unsigned flagLen) override;
4013
4014 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4015 const char *flagsEnd,
4016 const char *conversionPosition)
4017 override;
4018};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004019} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004020
4021bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4022 const analyze_printf::PrintfSpecifier &FS,
4023 const char *startSpecifier,
4024 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004025 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004026 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004027
Ted Kremenekce815422010-07-19 21:25:57 +00004028 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4029 getLocationOfByte(CS.getStart()),
4030 startSpecifier, specifierLen,
4031 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004032}
4033
Ted Kremenek02087932010-07-16 02:11:22 +00004034bool CheckPrintfHandler::HandleAmount(
4035 const analyze_format_string::OptionalAmount &Amt,
4036 unsigned k, const char *startSpecifier,
4037 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004038 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004039 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004040 unsigned argIndex = Amt.getArgIndex();
4041 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004042 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4043 << k,
4044 getLocationOfByte(Amt.getStart()),
4045 /*IsStringLocation*/true,
4046 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004047 // Don't do any more checking. We will just emit
4048 // spurious errors.
4049 return false;
4050 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004051
Ted Kremenek5739de72010-01-29 01:06:55 +00004052 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004053 // Although not in conformance with C99, we also allow the argument to be
4054 // an 'unsigned int' as that is a reasonably safe case. GCC also
4055 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004056 CoveredArgs.set(argIndex);
4057 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004058 if (!Arg)
4059 return false;
4060
Ted Kremenek5739de72010-01-29 01:06:55 +00004061 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004062
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004063 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4064 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004065
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004066 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004067 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004068 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004069 << T << Arg->getSourceRange(),
4070 getLocationOfByte(Amt.getStart()),
4071 /*IsStringLocation*/true,
4072 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004073 // Don't do any more checking. We will just emit
4074 // spurious errors.
4075 return false;
4076 }
4077 }
4078 }
4079 return true;
4080}
Ted Kremenek5739de72010-01-29 01:06:55 +00004081
Tom Careb49ec692010-06-17 19:00:27 +00004082void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004083 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004084 const analyze_printf::OptionalAmount &Amt,
4085 unsigned type,
4086 const char *startSpecifier,
4087 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004088 const analyze_printf::PrintfConversionSpecifier &CS =
4089 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004090
Richard Trieu03cf7b72011-10-28 00:41:25 +00004091 FixItHint fixit =
4092 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4093 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4094 Amt.getConstantLength()))
4095 : FixItHint();
4096
4097 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4098 << type << CS.toString(),
4099 getLocationOfByte(Amt.getStart()),
4100 /*IsStringLocation*/true,
4101 getSpecifierRange(startSpecifier, specifierLen),
4102 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004103}
4104
Ted Kremenek02087932010-07-16 02:11:22 +00004105void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004106 const analyze_printf::OptionalFlag &flag,
4107 const char *startSpecifier,
4108 unsigned specifierLen) {
4109 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004110 const analyze_printf::PrintfConversionSpecifier &CS =
4111 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004112 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4113 << flag.toString() << CS.toString(),
4114 getLocationOfByte(flag.getPosition()),
4115 /*IsStringLocation*/true,
4116 getSpecifierRange(startSpecifier, specifierLen),
4117 FixItHint::CreateRemoval(
4118 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004119}
4120
4121void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004122 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004123 const analyze_printf::OptionalFlag &ignoredFlag,
4124 const analyze_printf::OptionalFlag &flag,
4125 const char *startSpecifier,
4126 unsigned specifierLen) {
4127 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004128 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4129 << ignoredFlag.toString() << flag.toString(),
4130 getLocationOfByte(ignoredFlag.getPosition()),
4131 /*IsStringLocation*/true,
4132 getSpecifierRange(startSpecifier, specifierLen),
4133 FixItHint::CreateRemoval(
4134 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004135}
4136
Ted Kremenek2b417712015-07-02 05:39:16 +00004137// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4138// bool IsStringLocation, Range StringRange,
4139// ArrayRef<FixItHint> Fixit = None);
4140
4141void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4142 unsigned flagLen) {
4143 // Warn about an empty flag.
4144 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4145 getLocationOfByte(startFlag),
4146 /*IsStringLocation*/true,
4147 getSpecifierRange(startFlag, flagLen));
4148}
4149
4150void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4151 unsigned flagLen) {
4152 // Warn about an invalid flag.
4153 auto Range = getSpecifierRange(startFlag, flagLen);
4154 StringRef flag(startFlag, flagLen);
4155 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4156 getLocationOfByte(startFlag),
4157 /*IsStringLocation*/true,
4158 Range, FixItHint::CreateRemoval(Range));
4159}
4160
4161void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4162 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4163 // Warn about using '[...]' without a '@' conversion.
4164 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4165 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4166 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4167 getLocationOfByte(conversionPosition),
4168 /*IsStringLocation*/true,
4169 Range, FixItHint::CreateRemoval(Range));
4170}
4171
Richard Smith55ce3522012-06-25 20:30:08 +00004172// Determines if the specified is a C++ class or struct containing
4173// a member with the specified name and kind (e.g. a CXXMethodDecl named
4174// "c_str()").
4175template<typename MemberKind>
4176static llvm::SmallPtrSet<MemberKind*, 1>
4177CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4178 const RecordType *RT = Ty->getAs<RecordType>();
4179 llvm::SmallPtrSet<MemberKind*, 1> Results;
4180
4181 if (!RT)
4182 return Results;
4183 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004184 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004185 return Results;
4186
Alp Tokerb6cc5922014-05-03 03:45:55 +00004187 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004188 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004189 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004190
4191 // We just need to include all members of the right kind turned up by the
4192 // filter, at this point.
4193 if (S.LookupQualifiedName(R, RT->getDecl()))
4194 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4195 NamedDecl *decl = (*I)->getUnderlyingDecl();
4196 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4197 Results.insert(FK);
4198 }
4199 return Results;
4200}
4201
Richard Smith2868a732014-02-28 01:36:39 +00004202/// Check if we could call '.c_str()' on an object.
4203///
4204/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4205/// allow the call, or if it would be ambiguous).
4206bool Sema::hasCStrMethod(const Expr *E) {
4207 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4208 MethodSet Results =
4209 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4210 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4211 MI != ME; ++MI)
4212 if ((*MI)->getMinRequiredArguments() == 0)
4213 return true;
4214 return false;
4215}
4216
Richard Smith55ce3522012-06-25 20:30:08 +00004217// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004218// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004219// Returns true when a c_str() conversion method is found.
4220bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004221 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004222 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4223
4224 MethodSet Results =
4225 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4226
4227 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4228 MI != ME; ++MI) {
4229 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004230 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004231 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004232 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004233 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004234 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4235 << "c_str()"
4236 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4237 return true;
4238 }
4239 }
4240
4241 return false;
4242}
4243
Ted Kremenekab278de2010-01-28 23:39:18 +00004244bool
Ted Kremenek02087932010-07-16 02:11:22 +00004245CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004246 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004247 const char *startSpecifier,
4248 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004249 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004250 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004251 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004252
Ted Kremenek6cd69422010-07-19 22:01:06 +00004253 if (FS.consumesDataArgument()) {
4254 if (atFirstArg) {
4255 atFirstArg = false;
4256 usesPositionalArgs = FS.usesPositionalArg();
4257 }
4258 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004259 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4260 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004261 return false;
4262 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004263 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004264
Ted Kremenekd1668192010-02-27 01:41:03 +00004265 // First check if the field width, precision, and conversion specifier
4266 // have matching data arguments.
4267 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4268 startSpecifier, specifierLen)) {
4269 return false;
4270 }
4271
4272 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4273 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004274 return false;
4275 }
4276
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004277 if (!CS.consumesDataArgument()) {
4278 // FIXME: Technically specifying a precision or field width here
4279 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004280 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004281 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004282
Ted Kremenek4a49d982010-02-26 19:18:41 +00004283 // Consume the argument.
4284 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004285 if (argIndex < NumDataArgs) {
4286 // The check to see if the argIndex is valid will come later.
4287 // We set the bit here because we may exit early from this
4288 // function if we encounter some other error.
4289 CoveredArgs.set(argIndex);
4290 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004291
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004292 // FreeBSD kernel extensions.
4293 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4294 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4295 // We need at least two arguments.
4296 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4297 return false;
4298
4299 // Claim the second argument.
4300 CoveredArgs.set(argIndex + 1);
4301
4302 // Type check the first argument (int for %b, pointer for %D)
4303 const Expr *Ex = getDataArg(argIndex);
4304 const analyze_printf::ArgType &AT =
4305 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4306 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4307 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4308 EmitFormatDiagnostic(
4309 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4310 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4311 << false << Ex->getSourceRange(),
4312 Ex->getLocStart(), /*IsStringLocation*/false,
4313 getSpecifierRange(startSpecifier, specifierLen));
4314
4315 // Type check the second argument (char * for both %b and %D)
4316 Ex = getDataArg(argIndex + 1);
4317 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4318 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4319 EmitFormatDiagnostic(
4320 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4321 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4322 << false << Ex->getSourceRange(),
4323 Ex->getLocStart(), /*IsStringLocation*/false,
4324 getSpecifierRange(startSpecifier, specifierLen));
4325
4326 return true;
4327 }
4328
Ted Kremenek4a49d982010-02-26 19:18:41 +00004329 // Check for using an Objective-C specific conversion specifier
4330 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004331 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004332 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4333 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004334 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004335
Tom Careb49ec692010-06-17 19:00:27 +00004336 // Check for invalid use of field width
4337 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004338 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004339 startSpecifier, specifierLen);
4340 }
4341
4342 // Check for invalid use of precision
4343 if (!FS.hasValidPrecision()) {
4344 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4345 startSpecifier, specifierLen);
4346 }
4347
4348 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004349 if (!FS.hasValidThousandsGroupingPrefix())
4350 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004351 if (!FS.hasValidLeadingZeros())
4352 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4353 if (!FS.hasValidPlusPrefix())
4354 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004355 if (!FS.hasValidSpacePrefix())
4356 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004357 if (!FS.hasValidAlternativeForm())
4358 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4359 if (!FS.hasValidLeftJustified())
4360 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4361
4362 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004363 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4364 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4365 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004366 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4367 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4368 startSpecifier, specifierLen);
4369
4370 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004371 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004372 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4373 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004374 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004375 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004376 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004377 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4378 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004379
Jordan Rose92303592012-09-08 04:00:03 +00004380 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4381 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4382
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004383 // The remaining checks depend on the data arguments.
4384 if (HasVAListArg)
4385 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004386
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004387 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004388 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004389
Jordan Rose58bbe422012-07-19 18:10:08 +00004390 const Expr *Arg = getDataArg(argIndex);
4391 if (!Arg)
4392 return true;
4393
4394 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004395}
4396
Jordan Roseaee34382012-09-05 22:56:26 +00004397static bool requiresParensToAddCast(const Expr *E) {
4398 // FIXME: We should have a general way to reason about operator
4399 // precedence and whether parens are actually needed here.
4400 // Take care of a few common cases where they aren't.
4401 const Expr *Inside = E->IgnoreImpCasts();
4402 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4403 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4404
4405 switch (Inside->getStmtClass()) {
4406 case Stmt::ArraySubscriptExprClass:
4407 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004408 case Stmt::CharacterLiteralClass:
4409 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004410 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004411 case Stmt::FloatingLiteralClass:
4412 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004413 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004414 case Stmt::ObjCArrayLiteralClass:
4415 case Stmt::ObjCBoolLiteralExprClass:
4416 case Stmt::ObjCBoxedExprClass:
4417 case Stmt::ObjCDictionaryLiteralClass:
4418 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004419 case Stmt::ObjCIvarRefExprClass:
4420 case Stmt::ObjCMessageExprClass:
4421 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004422 case Stmt::ObjCStringLiteralClass:
4423 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004424 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004425 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004426 case Stmt::UnaryOperatorClass:
4427 return false;
4428 default:
4429 return true;
4430 }
4431}
4432
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004433static std::pair<QualType, StringRef>
4434shouldNotPrintDirectly(const ASTContext &Context,
4435 QualType IntendedTy,
4436 const Expr *E) {
4437 // Use a 'while' to peel off layers of typedefs.
4438 QualType TyTy = IntendedTy;
4439 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4440 StringRef Name = UserTy->getDecl()->getName();
4441 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4442 .Case("NSInteger", Context.LongTy)
4443 .Case("NSUInteger", Context.UnsignedLongTy)
4444 .Case("SInt32", Context.IntTy)
4445 .Case("UInt32", Context.UnsignedIntTy)
4446 .Default(QualType());
4447
4448 if (!CastTy.isNull())
4449 return std::make_pair(CastTy, Name);
4450
4451 TyTy = UserTy->desugar();
4452 }
4453
4454 // Strip parens if necessary.
4455 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4456 return shouldNotPrintDirectly(Context,
4457 PE->getSubExpr()->getType(),
4458 PE->getSubExpr());
4459
4460 // If this is a conditional expression, then its result type is constructed
4461 // via usual arithmetic conversions and thus there might be no necessary
4462 // typedef sugar there. Recurse to operands to check for NSInteger &
4463 // Co. usage condition.
4464 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4465 QualType TrueTy, FalseTy;
4466 StringRef TrueName, FalseName;
4467
4468 std::tie(TrueTy, TrueName) =
4469 shouldNotPrintDirectly(Context,
4470 CO->getTrueExpr()->getType(),
4471 CO->getTrueExpr());
4472 std::tie(FalseTy, FalseName) =
4473 shouldNotPrintDirectly(Context,
4474 CO->getFalseExpr()->getType(),
4475 CO->getFalseExpr());
4476
4477 if (TrueTy == FalseTy)
4478 return std::make_pair(TrueTy, TrueName);
4479 else if (TrueTy.isNull())
4480 return std::make_pair(FalseTy, FalseName);
4481 else if (FalseTy.isNull())
4482 return std::make_pair(TrueTy, TrueName);
4483 }
4484
4485 return std::make_pair(QualType(), StringRef());
4486}
4487
Richard Smith55ce3522012-06-25 20:30:08 +00004488bool
4489CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4490 const char *StartSpecifier,
4491 unsigned SpecifierLen,
4492 const Expr *E) {
4493 using namespace analyze_format_string;
4494 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004495 // Now type check the data expression that matches the
4496 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004497 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4498 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004499 if (!AT.isValid())
4500 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004501
Jordan Rose598ec092012-12-05 18:44:40 +00004502 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004503 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4504 ExprTy = TET->getUnderlyingExpr()->getType();
4505 }
4506
Seth Cantrellb4802962015-03-04 03:12:10 +00004507 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4508
4509 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004510 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004511 }
Jordan Rose98709982012-06-04 22:48:57 +00004512
Jordan Rose22b74712012-09-05 22:56:19 +00004513 // Look through argument promotions for our error message's reported type.
4514 // This includes the integral and floating promotions, but excludes array
4515 // and function pointer decay; seeing that an argument intended to be a
4516 // string has type 'char [6]' is probably more confusing than 'char *'.
4517 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4518 if (ICE->getCastKind() == CK_IntegralCast ||
4519 ICE->getCastKind() == CK_FloatingCast) {
4520 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004521 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004522
4523 // Check if we didn't match because of an implicit cast from a 'char'
4524 // or 'short' to an 'int'. This is done because printf is a varargs
4525 // function.
4526 if (ICE->getType() == S.Context.IntTy ||
4527 ICE->getType() == S.Context.UnsignedIntTy) {
4528 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004529 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004530 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004531 }
Jordan Rose98709982012-06-04 22:48:57 +00004532 }
Jordan Rose598ec092012-12-05 18:44:40 +00004533 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4534 // Special case for 'a', which has type 'int' in C.
4535 // Note, however, that we do /not/ want to treat multibyte constants like
4536 // 'MooV' as characters! This form is deprecated but still exists.
4537 if (ExprTy == S.Context.IntTy)
4538 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4539 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004540 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004541
Jordan Rosebc53ed12014-05-31 04:12:14 +00004542 // Look through enums to their underlying type.
4543 bool IsEnum = false;
4544 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4545 ExprTy = EnumTy->getDecl()->getIntegerType();
4546 IsEnum = true;
4547 }
4548
Jordan Rose0e5badd2012-12-05 18:44:49 +00004549 // %C in an Objective-C context prints a unichar, not a wchar_t.
4550 // If the argument is an integer of some kind, believe the %C and suggest
4551 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004552 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004553 if (ObjCContext &&
4554 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4555 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4556 !ExprTy->isCharType()) {
4557 // 'unichar' is defined as a typedef of unsigned short, but we should
4558 // prefer using the typedef if it is visible.
4559 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004560
4561 // While we are here, check if the value is an IntegerLiteral that happens
4562 // to be within the valid range.
4563 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4564 const llvm::APInt &V = IL->getValue();
4565 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4566 return true;
4567 }
4568
Jordan Rose0e5badd2012-12-05 18:44:49 +00004569 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4570 Sema::LookupOrdinaryName);
4571 if (S.LookupName(Result, S.getCurScope())) {
4572 NamedDecl *ND = Result.getFoundDecl();
4573 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4574 if (TD->getUnderlyingType() == IntendedTy)
4575 IntendedTy = S.Context.getTypedefType(TD);
4576 }
4577 }
4578 }
4579
4580 // Special-case some of Darwin's platform-independence types by suggesting
4581 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004582 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004583 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004584 QualType CastTy;
4585 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4586 if (!CastTy.isNull()) {
4587 IntendedTy = CastTy;
4588 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004589 }
4590 }
4591
Jordan Rose22b74712012-09-05 22:56:19 +00004592 // We may be able to offer a FixItHint if it is a supported type.
4593 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004594 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004595 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004596
Jordan Rose22b74712012-09-05 22:56:19 +00004597 if (success) {
4598 // Get the fix string from the fixed format specifier
4599 SmallString<16> buf;
4600 llvm::raw_svector_ostream os(buf);
4601 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004602
Jordan Roseaee34382012-09-05 22:56:26 +00004603 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4604
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004605 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004606 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4607 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4608 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4609 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004610 // In this case, the specifier is wrong and should be changed to match
4611 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004612 EmitFormatDiagnostic(S.PDiag(diag)
4613 << AT.getRepresentativeTypeName(S.Context)
4614 << IntendedTy << IsEnum << E->getSourceRange(),
4615 E->getLocStart(),
4616 /*IsStringLocation*/ false, SpecRange,
4617 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004618 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004619 // The canonical type for formatting this value is different from the
4620 // actual type of the expression. (This occurs, for example, with Darwin's
4621 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4622 // should be printed as 'long' for 64-bit compatibility.)
4623 // Rather than emitting a normal format/argument mismatch, we want to
4624 // add a cast to the recommended type (and correct the format string
4625 // if necessary).
4626 SmallString<16> CastBuf;
4627 llvm::raw_svector_ostream CastFix(CastBuf);
4628 CastFix << "(";
4629 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4630 CastFix << ")";
4631
4632 SmallVector<FixItHint,4> Hints;
4633 if (!AT.matchesType(S.Context, IntendedTy))
4634 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4635
4636 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4637 // If there's already a cast present, just replace it.
4638 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4639 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4640
4641 } else if (!requiresParensToAddCast(E)) {
4642 // If the expression has high enough precedence,
4643 // just write the C-style cast.
4644 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4645 CastFix.str()));
4646 } else {
4647 // Otherwise, add parens around the expression as well as the cast.
4648 CastFix << "(";
4649 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4650 CastFix.str()));
4651
Alp Tokerb6cc5922014-05-03 03:45:55 +00004652 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004653 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4654 }
4655
Jordan Rose0e5badd2012-12-05 18:44:49 +00004656 if (ShouldNotPrintDirectly) {
4657 // The expression has a type that should not be printed directly.
4658 // We extract the name from the typedef because we don't want to show
4659 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004660 StringRef Name;
4661 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4662 Name = TypedefTy->getDecl()->getName();
4663 else
4664 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004665 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004666 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004667 << E->getSourceRange(),
4668 E->getLocStart(), /*IsStringLocation=*/false,
4669 SpecRange, Hints);
4670 } else {
4671 // In this case, the expression could be printed using a different
4672 // specifier, but we've decided that the specifier is probably correct
4673 // and we should cast instead. Just use the normal warning message.
4674 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004675 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4676 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004677 << E->getSourceRange(),
4678 E->getLocStart(), /*IsStringLocation*/false,
4679 SpecRange, Hints);
4680 }
Jordan Roseaee34382012-09-05 22:56:26 +00004681 }
Jordan Rose22b74712012-09-05 22:56:19 +00004682 } else {
4683 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4684 SpecifierLen);
4685 // Since the warning for passing non-POD types to variadic functions
4686 // was deferred until now, we emit a warning for non-POD
4687 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004688 switch (S.isValidVarArgType(ExprTy)) {
4689 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004690 case Sema::VAK_ValidInCXX11: {
4691 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4692 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4693 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4694 }
Richard Smithd7293d72013-08-05 18:49:43 +00004695
Seth Cantrellb4802962015-03-04 03:12:10 +00004696 EmitFormatDiagnostic(
4697 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4698 << IsEnum << CSR << E->getSourceRange(),
4699 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4700 break;
4701 }
Richard Smithd7293d72013-08-05 18:49:43 +00004702 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004703 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004704 EmitFormatDiagnostic(
4705 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004706 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004707 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004708 << CallType
4709 << AT.getRepresentativeTypeName(S.Context)
4710 << CSR
4711 << E->getSourceRange(),
4712 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004713 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004714 break;
4715
4716 case Sema::VAK_Invalid:
4717 if (ExprTy->isObjCObjectType())
4718 EmitFormatDiagnostic(
4719 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4720 << S.getLangOpts().CPlusPlus11
4721 << ExprTy
4722 << CallType
4723 << AT.getRepresentativeTypeName(S.Context)
4724 << CSR
4725 << E->getSourceRange(),
4726 E->getLocStart(), /*IsStringLocation*/false, CSR);
4727 else
4728 // FIXME: If this is an initializer list, suggest removing the braces
4729 // or inserting a cast to the target type.
4730 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4731 << isa<InitListExpr>(E) << ExprTy << CallType
4732 << AT.getRepresentativeTypeName(S.Context)
4733 << E->getSourceRange();
4734 break;
4735 }
4736
4737 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4738 "format string specifier index out of range");
4739 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004740 }
4741
Ted Kremenekab278de2010-01-28 23:39:18 +00004742 return true;
4743}
4744
Ted Kremenek02087932010-07-16 02:11:22 +00004745//===--- CHECK: Scanf format string checking ------------------------------===//
4746
4747namespace {
4748class CheckScanfHandler : public CheckFormatHandler {
4749public:
4750 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4751 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004752 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004753 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004754 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004755 Sema::VariadicCallType CallType,
4756 llvm::SmallBitVector &CheckedVarArgs)
4757 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4758 numDataArgs, beg, hasVAListArg,
4759 Args, formatIdx, inFunctionCall, CallType,
4760 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004761 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004762
4763 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4764 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004765 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004766
4767 bool HandleInvalidScanfConversionSpecifier(
4768 const analyze_scanf::ScanfSpecifier &FS,
4769 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004770 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004771
Craig Toppere14c0f82014-03-12 04:55:44 +00004772 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004773};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004774} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004775
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004776void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4777 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004778 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4779 getLocationOfByte(end), /*IsStringLocation*/true,
4780 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004781}
4782
Ted Kremenekce815422010-07-19 21:25:57 +00004783bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4784 const analyze_scanf::ScanfSpecifier &FS,
4785 const char *startSpecifier,
4786 unsigned specifierLen) {
4787
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004788 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004789 FS.getConversionSpecifier();
4790
4791 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4792 getLocationOfByte(CS.getStart()),
4793 startSpecifier, specifierLen,
4794 CS.getStart(), CS.getLength());
4795}
4796
Ted Kremenek02087932010-07-16 02:11:22 +00004797bool CheckScanfHandler::HandleScanfSpecifier(
4798 const analyze_scanf::ScanfSpecifier &FS,
4799 const char *startSpecifier,
4800 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004801 using namespace analyze_scanf;
4802 using namespace analyze_format_string;
4803
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004804 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004805
Ted Kremenek6cd69422010-07-19 22:01:06 +00004806 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4807 // be used to decide if we are using positional arguments consistently.
4808 if (FS.consumesDataArgument()) {
4809 if (atFirstArg) {
4810 atFirstArg = false;
4811 usesPositionalArgs = FS.usesPositionalArg();
4812 }
4813 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004814 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4815 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004816 return false;
4817 }
Ted Kremenek02087932010-07-16 02:11:22 +00004818 }
4819
4820 // Check if the field with is non-zero.
4821 const OptionalAmount &Amt = FS.getFieldWidth();
4822 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4823 if (Amt.getConstantAmount() == 0) {
4824 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4825 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004826 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4827 getLocationOfByte(Amt.getStart()),
4828 /*IsStringLocation*/true, R,
4829 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004830 }
4831 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004832
Ted Kremenek02087932010-07-16 02:11:22 +00004833 if (!FS.consumesDataArgument()) {
4834 // FIXME: Technically specifying a precision or field width here
4835 // makes no sense. Worth issuing a warning at some point.
4836 return true;
4837 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004838
Ted Kremenek02087932010-07-16 02:11:22 +00004839 // Consume the argument.
4840 unsigned argIndex = FS.getArgIndex();
4841 if (argIndex < NumDataArgs) {
4842 // The check to see if the argIndex is valid will come later.
4843 // We set the bit here because we may exit early from this
4844 // function if we encounter some other error.
4845 CoveredArgs.set(argIndex);
4846 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004847
Ted Kremenek4407ea42010-07-20 20:04:47 +00004848 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004849 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004850 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4851 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004852 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004853 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004854 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004855 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4856 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004857
Jordan Rose92303592012-09-08 04:00:03 +00004858 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4859 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4860
Ted Kremenek02087932010-07-16 02:11:22 +00004861 // The remaining checks depend on the data arguments.
4862 if (HasVAListArg)
4863 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004864
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004865 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004866 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004867
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004868 // Check that the argument type matches the format specifier.
4869 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004870 if (!Ex)
4871 return true;
4872
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004873 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004874
4875 if (!AT.isValid()) {
4876 return true;
4877 }
4878
Seth Cantrellb4802962015-03-04 03:12:10 +00004879 analyze_format_string::ArgType::MatchKind match =
4880 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004881 if (match == analyze_format_string::ArgType::Match) {
4882 return true;
4883 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004884
Seth Cantrell79340072015-03-04 05:58:08 +00004885 ScanfSpecifier fixedFS = FS;
4886 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4887 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004888
Seth Cantrell79340072015-03-04 05:58:08 +00004889 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4890 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4891 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4892 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004893
Seth Cantrell79340072015-03-04 05:58:08 +00004894 if (success) {
4895 // Get the fix string from the fixed format specifier.
4896 SmallString<128> buf;
4897 llvm::raw_svector_ostream os(buf);
4898 fixedFS.toString(os);
4899
4900 EmitFormatDiagnostic(
4901 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4902 << Ex->getType() << false << Ex->getSourceRange(),
4903 Ex->getLocStart(),
4904 /*IsStringLocation*/ false,
4905 getSpecifierRange(startSpecifier, specifierLen),
4906 FixItHint::CreateReplacement(
4907 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4908 } else {
4909 EmitFormatDiagnostic(S.PDiag(diag)
4910 << AT.getRepresentativeTypeName(S.Context)
4911 << Ex->getType() << false << Ex->getSourceRange(),
4912 Ex->getLocStart(),
4913 /*IsStringLocation*/ false,
4914 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004915 }
4916
Ted Kremenek02087932010-07-16 02:11:22 +00004917 return true;
4918}
4919
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004920static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
4921 const Expr *OrigFormatExpr,
4922 ArrayRef<const Expr *> Args,
4923 bool HasVAListArg, unsigned format_idx,
4924 unsigned firstDataArg,
4925 Sema::FormatStringType Type,
4926 bool inFunctionCall,
4927 Sema::VariadicCallType CallType,
4928 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenekab278de2010-01-28 23:39:18 +00004929 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004930 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004931 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004932 S, inFunctionCall, Args[format_idx],
4933 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004934 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004935 return;
4936 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004937
Ted Kremenekab278de2010-01-28 23:39:18 +00004938 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004939 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004940 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004941 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004942 const ConstantArrayType *T =
4943 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004944 assert(T && "String literal not of constant array type!");
4945 size_t TypeSize = T->getSize().getZExtValue();
4946 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004947 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004948
4949 // Emit a warning if the string literal is truncated and does not contain an
4950 // embedded null character.
4951 if (TypeSize <= StrRef.size() &&
4952 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4953 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004954 S, inFunctionCall, Args[format_idx],
4955 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004956 FExpr->getLocStart(),
4957 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4958 return;
4959 }
4960
Ted Kremenekab278de2010-01-28 23:39:18 +00004961 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004962 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004963 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004964 S, inFunctionCall, Args[format_idx],
4965 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00004966 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004967 return;
4968 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004969
4970 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
4971 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
4972 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
4973 numDataArgs, (Type == Sema::FST_NSString ||
4974 Type == Sema::FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004975 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004976 inFunctionCall, CallType, CheckedVarArgs);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004977
Hans Wennborg23926bd2011-12-15 10:25:47 +00004978 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004979 S.getLangOpts(),
4980 S.Context.getTargetInfo(),
4981 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004982 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004983 } else if (Type == Sema::FST_Scanf) {
4984 CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004985 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004986 inFunctionCall, CallType, CheckedVarArgs);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004987
Hans Wennborg23926bd2011-12-15 10:25:47 +00004988 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004989 S.getLangOpts(),
4990 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004991 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004992 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004993}
4994
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004995bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4996 // Str - The format string. NOTE: this is NOT null-terminated!
4997 StringRef StrRef = FExpr->getString();
4998 const char *Str = StrRef.data();
4999 // Account for cases where the string literal is truncated in a declaration.
5000 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5001 assert(T && "String literal not of constant array type!");
5002 size_t TypeSize = T->getSize().getZExtValue();
5003 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5004 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5005 getLangOpts(),
5006 Context.getTargetInfo());
5007}
5008
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005009//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5010
5011// Returns the related absolute value function that is larger, of 0 if one
5012// does not exist.
5013static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5014 switch (AbsFunction) {
5015 default:
5016 return 0;
5017
5018 case Builtin::BI__builtin_abs:
5019 return Builtin::BI__builtin_labs;
5020 case Builtin::BI__builtin_labs:
5021 return Builtin::BI__builtin_llabs;
5022 case Builtin::BI__builtin_llabs:
5023 return 0;
5024
5025 case Builtin::BI__builtin_fabsf:
5026 return Builtin::BI__builtin_fabs;
5027 case Builtin::BI__builtin_fabs:
5028 return Builtin::BI__builtin_fabsl;
5029 case Builtin::BI__builtin_fabsl:
5030 return 0;
5031
5032 case Builtin::BI__builtin_cabsf:
5033 return Builtin::BI__builtin_cabs;
5034 case Builtin::BI__builtin_cabs:
5035 return Builtin::BI__builtin_cabsl;
5036 case Builtin::BI__builtin_cabsl:
5037 return 0;
5038
5039 case Builtin::BIabs:
5040 return Builtin::BIlabs;
5041 case Builtin::BIlabs:
5042 return Builtin::BIllabs;
5043 case Builtin::BIllabs:
5044 return 0;
5045
5046 case Builtin::BIfabsf:
5047 return Builtin::BIfabs;
5048 case Builtin::BIfabs:
5049 return Builtin::BIfabsl;
5050 case Builtin::BIfabsl:
5051 return 0;
5052
5053 case Builtin::BIcabsf:
5054 return Builtin::BIcabs;
5055 case Builtin::BIcabs:
5056 return Builtin::BIcabsl;
5057 case Builtin::BIcabsl:
5058 return 0;
5059 }
5060}
5061
5062// Returns the argument type of the absolute value function.
5063static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5064 unsigned AbsType) {
5065 if (AbsType == 0)
5066 return QualType();
5067
5068 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5069 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5070 if (Error != ASTContext::GE_None)
5071 return QualType();
5072
5073 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5074 if (!FT)
5075 return QualType();
5076
5077 if (FT->getNumParams() != 1)
5078 return QualType();
5079
5080 return FT->getParamType(0);
5081}
5082
5083// Returns the best absolute value function, or zero, based on type and
5084// current absolute value function.
5085static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5086 unsigned AbsFunctionKind) {
5087 unsigned BestKind = 0;
5088 uint64_t ArgSize = Context.getTypeSize(ArgType);
5089 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5090 Kind = getLargerAbsoluteValueFunction(Kind)) {
5091 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5092 if (Context.getTypeSize(ParamType) >= ArgSize) {
5093 if (BestKind == 0)
5094 BestKind = Kind;
5095 else if (Context.hasSameType(ParamType, ArgType)) {
5096 BestKind = Kind;
5097 break;
5098 }
5099 }
5100 }
5101 return BestKind;
5102}
5103
5104enum AbsoluteValueKind {
5105 AVK_Integer,
5106 AVK_Floating,
5107 AVK_Complex
5108};
5109
5110static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5111 if (T->isIntegralOrEnumerationType())
5112 return AVK_Integer;
5113 if (T->isRealFloatingType())
5114 return AVK_Floating;
5115 if (T->isAnyComplexType())
5116 return AVK_Complex;
5117
5118 llvm_unreachable("Type not integer, floating, or complex");
5119}
5120
5121// Changes the absolute value function to a different type. Preserves whether
5122// the function is a builtin.
5123static unsigned changeAbsFunction(unsigned AbsKind,
5124 AbsoluteValueKind ValueKind) {
5125 switch (ValueKind) {
5126 case AVK_Integer:
5127 switch (AbsKind) {
5128 default:
5129 return 0;
5130 case Builtin::BI__builtin_fabsf:
5131 case Builtin::BI__builtin_fabs:
5132 case Builtin::BI__builtin_fabsl:
5133 case Builtin::BI__builtin_cabsf:
5134 case Builtin::BI__builtin_cabs:
5135 case Builtin::BI__builtin_cabsl:
5136 return Builtin::BI__builtin_abs;
5137 case Builtin::BIfabsf:
5138 case Builtin::BIfabs:
5139 case Builtin::BIfabsl:
5140 case Builtin::BIcabsf:
5141 case Builtin::BIcabs:
5142 case Builtin::BIcabsl:
5143 return Builtin::BIabs;
5144 }
5145 case AVK_Floating:
5146 switch (AbsKind) {
5147 default:
5148 return 0;
5149 case Builtin::BI__builtin_abs:
5150 case Builtin::BI__builtin_labs:
5151 case Builtin::BI__builtin_llabs:
5152 case Builtin::BI__builtin_cabsf:
5153 case Builtin::BI__builtin_cabs:
5154 case Builtin::BI__builtin_cabsl:
5155 return Builtin::BI__builtin_fabsf;
5156 case Builtin::BIabs:
5157 case Builtin::BIlabs:
5158 case Builtin::BIllabs:
5159 case Builtin::BIcabsf:
5160 case Builtin::BIcabs:
5161 case Builtin::BIcabsl:
5162 return Builtin::BIfabsf;
5163 }
5164 case AVK_Complex:
5165 switch (AbsKind) {
5166 default:
5167 return 0;
5168 case Builtin::BI__builtin_abs:
5169 case Builtin::BI__builtin_labs:
5170 case Builtin::BI__builtin_llabs:
5171 case Builtin::BI__builtin_fabsf:
5172 case Builtin::BI__builtin_fabs:
5173 case Builtin::BI__builtin_fabsl:
5174 return Builtin::BI__builtin_cabsf;
5175 case Builtin::BIabs:
5176 case Builtin::BIlabs:
5177 case Builtin::BIllabs:
5178 case Builtin::BIfabsf:
5179 case Builtin::BIfabs:
5180 case Builtin::BIfabsl:
5181 return Builtin::BIcabsf;
5182 }
5183 }
5184 llvm_unreachable("Unable to convert function");
5185}
5186
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005187static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005188 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5189 if (!FnInfo)
5190 return 0;
5191
5192 switch (FDecl->getBuiltinID()) {
5193 default:
5194 return 0;
5195 case Builtin::BI__builtin_abs:
5196 case Builtin::BI__builtin_fabs:
5197 case Builtin::BI__builtin_fabsf:
5198 case Builtin::BI__builtin_fabsl:
5199 case Builtin::BI__builtin_labs:
5200 case Builtin::BI__builtin_llabs:
5201 case Builtin::BI__builtin_cabs:
5202 case Builtin::BI__builtin_cabsf:
5203 case Builtin::BI__builtin_cabsl:
5204 case Builtin::BIabs:
5205 case Builtin::BIlabs:
5206 case Builtin::BIllabs:
5207 case Builtin::BIfabs:
5208 case Builtin::BIfabsf:
5209 case Builtin::BIfabsl:
5210 case Builtin::BIcabs:
5211 case Builtin::BIcabsf:
5212 case Builtin::BIcabsl:
5213 return FDecl->getBuiltinID();
5214 }
5215 llvm_unreachable("Unknown Builtin type");
5216}
5217
5218// If the replacement is valid, emit a note with replacement function.
5219// Additionally, suggest including the proper header if not already included.
5220static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005221 unsigned AbsKind, QualType ArgType) {
5222 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005223 const char *HeaderName = nullptr;
5224 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005225 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5226 FunctionName = "std::abs";
5227 if (ArgType->isIntegralOrEnumerationType()) {
5228 HeaderName = "cstdlib";
5229 } else if (ArgType->isRealFloatingType()) {
5230 HeaderName = "cmath";
5231 } else {
5232 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005233 }
Richard Trieubeffb832014-04-15 23:47:53 +00005234
5235 // Lookup all std::abs
5236 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005237 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005238 R.suppressDiagnostics();
5239 S.LookupQualifiedName(R, Std);
5240
5241 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005242 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005243 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5244 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5245 } else {
5246 FDecl = dyn_cast<FunctionDecl>(I);
5247 }
5248 if (!FDecl)
5249 continue;
5250
5251 // Found std::abs(), check that they are the right ones.
5252 if (FDecl->getNumParams() != 1)
5253 continue;
5254
5255 // Check that the parameter type can handle the argument.
5256 QualType ParamType = FDecl->getParamDecl(0)->getType();
5257 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5258 S.Context.getTypeSize(ArgType) <=
5259 S.Context.getTypeSize(ParamType)) {
5260 // Found a function, don't need the header hint.
5261 EmitHeaderHint = false;
5262 break;
5263 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005264 }
Richard Trieubeffb832014-04-15 23:47:53 +00005265 }
5266 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005267 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005268 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5269
5270 if (HeaderName) {
5271 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5272 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5273 R.suppressDiagnostics();
5274 S.LookupName(R, S.getCurScope());
5275
5276 if (R.isSingleResult()) {
5277 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5278 if (FD && FD->getBuiltinID() == AbsKind) {
5279 EmitHeaderHint = false;
5280 } else {
5281 return;
5282 }
5283 } else if (!R.empty()) {
5284 return;
5285 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005286 }
5287 }
5288
5289 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005290 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005291
Richard Trieubeffb832014-04-15 23:47:53 +00005292 if (!HeaderName)
5293 return;
5294
5295 if (!EmitHeaderHint)
5296 return;
5297
Alp Toker5d96e0a2014-07-11 20:53:51 +00005298 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5299 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005300}
5301
5302static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5303 if (!FDecl)
5304 return false;
5305
5306 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5307 return false;
5308
5309 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5310
5311 while (ND && ND->isInlineNamespace()) {
5312 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005313 }
Richard Trieubeffb832014-04-15 23:47:53 +00005314
5315 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5316 return false;
5317
5318 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5319 return false;
5320
5321 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005322}
5323
5324// Warn when using the wrong abs() function.
5325void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5326 const FunctionDecl *FDecl,
5327 IdentifierInfo *FnInfo) {
5328 if (Call->getNumArgs() != 1)
5329 return;
5330
5331 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005332 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5333 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005334 return;
5335
5336 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5337 QualType ParamType = Call->getArg(0)->getType();
5338
Alp Toker5d96e0a2014-07-11 20:53:51 +00005339 // Unsigned types cannot be negative. Suggest removing the absolute value
5340 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005341 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005342 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005343 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005344 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5345 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005346 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005347 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5348 return;
5349 }
5350
David Majnemer7f77eb92015-11-15 03:04:34 +00005351 // Taking the absolute value of a pointer is very suspicious, they probably
5352 // wanted to index into an array, dereference a pointer, call a function, etc.
5353 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5354 unsigned DiagType = 0;
5355 if (ArgType->isFunctionType())
5356 DiagType = 1;
5357 else if (ArgType->isArrayType())
5358 DiagType = 2;
5359
5360 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5361 return;
5362 }
5363
Richard Trieubeffb832014-04-15 23:47:53 +00005364 // std::abs has overloads which prevent most of the absolute value problems
5365 // from occurring.
5366 if (IsStdAbs)
5367 return;
5368
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005369 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5370 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5371
5372 // The argument and parameter are the same kind. Check if they are the right
5373 // size.
5374 if (ArgValueKind == ParamValueKind) {
5375 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5376 return;
5377
5378 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5379 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5380 << FDecl << ArgType << ParamType;
5381
5382 if (NewAbsKind == 0)
5383 return;
5384
5385 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005386 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005387 return;
5388 }
5389
5390 // ArgValueKind != ParamValueKind
5391 // The wrong type of absolute value function was used. Attempt to find the
5392 // proper one.
5393 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5394 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5395 if (NewAbsKind == 0)
5396 return;
5397
5398 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5399 << FDecl << ParamValueKind << ArgValueKind;
5400
5401 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005402 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005403}
5404
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005405//===--- CHECK: Standard memory functions ---------------------------------===//
5406
Nico Weber0e6daef2013-12-26 23:38:39 +00005407/// \brief Takes the expression passed to the size_t parameter of functions
5408/// such as memcmp, strncat, etc and warns if it's a comparison.
5409///
5410/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5411static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5412 IdentifierInfo *FnName,
5413 SourceLocation FnLoc,
5414 SourceLocation RParenLoc) {
5415 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5416 if (!Size)
5417 return false;
5418
5419 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5420 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5421 return false;
5422
Nico Weber0e6daef2013-12-26 23:38:39 +00005423 SourceRange SizeRange = Size->getSourceRange();
5424 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5425 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005426 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005427 << FnName << FixItHint::CreateInsertion(
5428 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005429 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005430 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005431 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005432 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5433 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005434
5435 return true;
5436}
5437
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005438/// \brief Determine whether the given type is or contains a dynamic class type
5439/// (e.g., whether it has a vtable).
5440static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5441 bool &IsContained) {
5442 // Look through array types while ignoring qualifiers.
5443 const Type *Ty = T->getBaseElementTypeUnsafe();
5444 IsContained = false;
5445
5446 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5447 RD = RD ? RD->getDefinition() : nullptr;
5448 if (!RD)
5449 return nullptr;
5450
5451 if (RD->isDynamicClass())
5452 return RD;
5453
5454 // Check all the fields. If any bases were dynamic, the class is dynamic.
5455 // It's impossible for a class to transitively contain itself by value, so
5456 // infinite recursion is impossible.
5457 for (auto *FD : RD->fields()) {
5458 bool SubContained;
5459 if (const CXXRecordDecl *ContainedRD =
5460 getContainedDynamicClass(FD->getType(), SubContained)) {
5461 IsContained = true;
5462 return ContainedRD;
5463 }
5464 }
5465
5466 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005467}
5468
Chandler Carruth889ed862011-06-21 23:04:20 +00005469/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005470/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005471static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005472 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005473 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5474 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5475 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005476
Craig Topperc3ec1492014-05-26 06:22:03 +00005477 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005478}
5479
Chandler Carruth889ed862011-06-21 23:04:20 +00005480/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005481static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005482 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5483 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5484 if (SizeOf->getKind() == clang::UETT_SizeOf)
5485 return SizeOf->getTypeOfArgument();
5486
5487 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005488}
5489
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005490/// \brief Check for dangerous or invalid arguments to memset().
5491///
Chandler Carruthac687262011-06-03 06:23:57 +00005492/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005493/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5494/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005495///
5496/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005497void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005498 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005499 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005500 assert(BId != 0);
5501
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005502 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005503 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005504 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005505 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005506 return;
5507
Anna Zaks22122702012-01-17 00:37:07 +00005508 unsigned LastArg = (BId == Builtin::BImemset ||
5509 BId == Builtin::BIstrndup ? 1 : 2);
5510 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005511 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005512
Nico Weber0e6daef2013-12-26 23:38:39 +00005513 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5514 Call->getLocStart(), Call->getRParenLoc()))
5515 return;
5516
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005517 // We have special checking when the length is a sizeof expression.
5518 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5519 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5520 llvm::FoldingSetNodeID SizeOfArgID;
5521
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005522 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5523 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005524 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005525
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005526 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005527 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005528 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005529 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005530
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005531 // Never warn about void type pointers. This can be used to suppress
5532 // false positives.
5533 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005534 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005535
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005536 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5537 // actually comparing the expressions for equality. Because computing the
5538 // expression IDs can be expensive, we only do this if the diagnostic is
5539 // enabled.
5540 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005541 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5542 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005543 // We only compute IDs for expressions if the warning is enabled, and
5544 // cache the sizeof arg's ID.
5545 if (SizeOfArgID == llvm::FoldingSetNodeID())
5546 SizeOfArg->Profile(SizeOfArgID, Context, true);
5547 llvm::FoldingSetNodeID DestID;
5548 Dest->Profile(DestID, Context, true);
5549 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005550 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5551 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005552 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005553 StringRef ReadableName = FnName->getName();
5554
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005555 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005556 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005557 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005558 if (!PointeeTy->isIncompleteType() &&
5559 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005560 ActionIdx = 2; // If the pointee's size is sizeof(char),
5561 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005562
5563 // If the function is defined as a builtin macro, do not show macro
5564 // expansion.
5565 SourceLocation SL = SizeOfArg->getExprLoc();
5566 SourceRange DSR = Dest->getSourceRange();
5567 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005568 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005569
5570 if (SM.isMacroArgExpansion(SL)) {
5571 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5572 SL = SM.getSpellingLoc(SL);
5573 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5574 SM.getSpellingLoc(DSR.getEnd()));
5575 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5576 SM.getSpellingLoc(SSR.getEnd()));
5577 }
5578
Anna Zaksd08d9152012-05-30 23:14:52 +00005579 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005580 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005581 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005582 << PointeeTy
5583 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005584 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005585 << SSR);
5586 DiagRuntimeBehavior(SL, SizeOfArg,
5587 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5588 << ActionIdx
5589 << SSR);
5590
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005591 break;
5592 }
5593 }
5594
5595 // Also check for cases where the sizeof argument is the exact same
5596 // type as the memory argument, and where it points to a user-defined
5597 // record type.
5598 if (SizeOfArgTy != QualType()) {
5599 if (PointeeTy->isRecordType() &&
5600 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5601 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5602 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5603 << FnName << SizeOfArgTy << ArgIdx
5604 << PointeeTy << Dest->getSourceRange()
5605 << LenExpr->getSourceRange());
5606 break;
5607 }
Nico Weberc5e73862011-06-14 16:14:58 +00005608 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005609 } else if (DestTy->isArrayType()) {
5610 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005611 }
Nico Weberc5e73862011-06-14 16:14:58 +00005612
Nico Weberc44b35e2015-03-21 17:37:46 +00005613 if (PointeeTy == QualType())
5614 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005615
Nico Weberc44b35e2015-03-21 17:37:46 +00005616 // Always complain about dynamic classes.
5617 bool IsContained;
5618 if (const CXXRecordDecl *ContainedRD =
5619 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005620
Nico Weberc44b35e2015-03-21 17:37:46 +00005621 unsigned OperationType = 0;
5622 // "overwritten" if we're warning about the destination for any call
5623 // but memcmp; otherwise a verb appropriate to the call.
5624 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5625 if (BId == Builtin::BImemcpy)
5626 OperationType = 1;
5627 else if(BId == Builtin::BImemmove)
5628 OperationType = 2;
5629 else if (BId == Builtin::BImemcmp)
5630 OperationType = 3;
5631 }
5632
John McCall31168b02011-06-15 23:02:42 +00005633 DiagRuntimeBehavior(
5634 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005635 PDiag(diag::warn_dyn_class_memaccess)
5636 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5637 << FnName << IsContained << ContainedRD << OperationType
5638 << Call->getCallee()->getSourceRange());
5639 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5640 BId != Builtin::BImemset)
5641 DiagRuntimeBehavior(
5642 Dest->getExprLoc(), Dest,
5643 PDiag(diag::warn_arc_object_memaccess)
5644 << ArgIdx << FnName << PointeeTy
5645 << Call->getCallee()->getSourceRange());
5646 else
5647 continue;
5648
5649 DiagRuntimeBehavior(
5650 Dest->getExprLoc(), Dest,
5651 PDiag(diag::note_bad_memaccess_silence)
5652 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5653 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005654 }
5655}
5656
Ted Kremenek6865f772011-08-18 20:55:45 +00005657// A little helper routine: ignore addition and subtraction of integer literals.
5658// This intentionally does not ignore all integer constant expressions because
5659// we don't want to remove sizeof().
5660static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5661 Ex = Ex->IgnoreParenCasts();
5662
5663 for (;;) {
5664 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5665 if (!BO || !BO->isAdditiveOp())
5666 break;
5667
5668 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5669 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5670
5671 if (isa<IntegerLiteral>(RHS))
5672 Ex = LHS;
5673 else if (isa<IntegerLiteral>(LHS))
5674 Ex = RHS;
5675 else
5676 break;
5677 }
5678
5679 return Ex;
5680}
5681
Anna Zaks13b08572012-08-08 21:42:23 +00005682static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5683 ASTContext &Context) {
5684 // Only handle constant-sized or VLAs, but not flexible members.
5685 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5686 // Only issue the FIXIT for arrays of size > 1.
5687 if (CAT->getSize().getSExtValue() <= 1)
5688 return false;
5689 } else if (!Ty->isVariableArrayType()) {
5690 return false;
5691 }
5692 return true;
5693}
5694
Ted Kremenek6865f772011-08-18 20:55:45 +00005695// Warn if the user has made the 'size' argument to strlcpy or strlcat
5696// be the size of the source, instead of the destination.
5697void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5698 IdentifierInfo *FnName) {
5699
5700 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005701 unsigned NumArgs = Call->getNumArgs();
5702 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005703 return;
5704
5705 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5706 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005707 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005708
5709 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5710 Call->getLocStart(), Call->getRParenLoc()))
5711 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005712
5713 // Look for 'strlcpy(dst, x, sizeof(x))'
5714 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5715 CompareWithSrc = Ex;
5716 else {
5717 // Look for 'strlcpy(dst, x, strlen(x))'
5718 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005719 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5720 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005721 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5722 }
5723 }
5724
5725 if (!CompareWithSrc)
5726 return;
5727
5728 // Determine if the argument to sizeof/strlen is equal to the source
5729 // argument. In principle there's all kinds of things you could do
5730 // here, for instance creating an == expression and evaluating it with
5731 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5732 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5733 if (!SrcArgDRE)
5734 return;
5735
5736 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5737 if (!CompareWithSrcDRE ||
5738 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5739 return;
5740
5741 const Expr *OriginalSizeArg = Call->getArg(2);
5742 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5743 << OriginalSizeArg->getSourceRange() << FnName;
5744
5745 // Output a FIXIT hint if the destination is an array (rather than a
5746 // pointer to an array). This could be enhanced to handle some
5747 // pointers if we know the actual size, like if DstArg is 'array+2'
5748 // we could say 'sizeof(array)-2'.
5749 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005750 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005751 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005752
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005753 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005754 llvm::raw_svector_ostream OS(sizeString);
5755 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005756 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005757 OS << ")";
5758
5759 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5760 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5761 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005762}
5763
Anna Zaks314cd092012-02-01 19:08:57 +00005764/// Check if two expressions refer to the same declaration.
5765static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5766 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5767 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5768 return D1->getDecl() == D2->getDecl();
5769 return false;
5770}
5771
5772static const Expr *getStrlenExprArg(const Expr *E) {
5773 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5774 const FunctionDecl *FD = CE->getDirectCallee();
5775 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005776 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005777 return CE->getArg(0)->IgnoreParenCasts();
5778 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005779 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005780}
5781
5782// Warn on anti-patterns as the 'size' argument to strncat.
5783// The correct size argument should look like following:
5784// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5785void Sema::CheckStrncatArguments(const CallExpr *CE,
5786 IdentifierInfo *FnName) {
5787 // Don't crash if the user has the wrong number of arguments.
5788 if (CE->getNumArgs() < 3)
5789 return;
5790 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5791 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5792 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5793
Nico Weber0e6daef2013-12-26 23:38:39 +00005794 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5795 CE->getRParenLoc()))
5796 return;
5797
Anna Zaks314cd092012-02-01 19:08:57 +00005798 // Identify common expressions, which are wrongly used as the size argument
5799 // to strncat and may lead to buffer overflows.
5800 unsigned PatternType = 0;
5801 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5802 // - sizeof(dst)
5803 if (referToTheSameDecl(SizeOfArg, DstArg))
5804 PatternType = 1;
5805 // - sizeof(src)
5806 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5807 PatternType = 2;
5808 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5809 if (BE->getOpcode() == BO_Sub) {
5810 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5811 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5812 // - sizeof(dst) - strlen(dst)
5813 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5814 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5815 PatternType = 1;
5816 // - sizeof(src) - (anything)
5817 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5818 PatternType = 2;
5819 }
5820 }
5821
5822 if (PatternType == 0)
5823 return;
5824
Anna Zaks5069aa32012-02-03 01:27:37 +00005825 // Generate the diagnostic.
5826 SourceLocation SL = LenArg->getLocStart();
5827 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005828 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005829
5830 // If the function is defined as a builtin macro, do not show macro expansion.
5831 if (SM.isMacroArgExpansion(SL)) {
5832 SL = SM.getSpellingLoc(SL);
5833 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5834 SM.getSpellingLoc(SR.getEnd()));
5835 }
5836
Anna Zaks13b08572012-08-08 21:42:23 +00005837 // Check if the destination is an array (rather than a pointer to an array).
5838 QualType DstTy = DstArg->getType();
5839 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5840 Context);
5841 if (!isKnownSizeArray) {
5842 if (PatternType == 1)
5843 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5844 else
5845 Diag(SL, diag::warn_strncat_src_size) << SR;
5846 return;
5847 }
5848
Anna Zaks314cd092012-02-01 19:08:57 +00005849 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005850 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005851 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005852 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005853
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005854 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005855 llvm::raw_svector_ostream OS(sizeString);
5856 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005857 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005858 OS << ") - ";
5859 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005860 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005861 OS << ") - 1";
5862
Anna Zaks5069aa32012-02-03 01:27:37 +00005863 Diag(SL, diag::note_strncat_wrong_size)
5864 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005865}
5866
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005867//===--- CHECK: Return Address of Stack Variable --------------------------===//
5868
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005869static const Expr *EvalVal(const Expr *E,
5870 SmallVectorImpl<const DeclRefExpr *> &refVars,
5871 const Decl *ParentDecl);
5872static const Expr *EvalAddr(const Expr *E,
5873 SmallVectorImpl<const DeclRefExpr *> &refVars,
5874 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005875
5876/// CheckReturnStackAddr - Check if a return statement returns the address
5877/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005878static void
5879CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5880 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005881
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005882 const Expr *stackE = nullptr;
5883 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005884
5885 // Perform checking for returned stack addresses, local blocks,
5886 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005887 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005888 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005889 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005890 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005891 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005892 }
5893
Craig Topperc3ec1492014-05-26 06:22:03 +00005894 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005895 return; // Nothing suspicious was found.
5896
5897 SourceLocation diagLoc;
5898 SourceRange diagRange;
5899 if (refVars.empty()) {
5900 diagLoc = stackE->getLocStart();
5901 diagRange = stackE->getSourceRange();
5902 } else {
5903 // We followed through a reference variable. 'stackE' contains the
5904 // problematic expression but we will warn at the return statement pointing
5905 // at the reference variable. We will later display the "trail" of
5906 // reference variables using notes.
5907 diagLoc = refVars[0]->getLocStart();
5908 diagRange = refVars[0]->getSourceRange();
5909 }
5910
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005911 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
5912 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00005913 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005914 << DR->getDecl()->getDeclName() << diagRange;
5915 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005916 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005917 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005918 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005919 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005920 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5921 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005922 }
5923
5924 // Display the "trail" of reference variables that we followed until we
5925 // found the problematic expression using notes.
5926 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005927 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005928 // If this var binds to another reference var, show the range of the next
5929 // var, otherwise the var binds to the problematic expression, in which case
5930 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005931 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
5932 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005933 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5934 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005935 }
5936}
5937
5938/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5939/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005940/// to a location on the stack, a local block, an address of a label, or a
5941/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005942/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005943/// encounter a subexpression that (1) clearly does not lead to one of the
5944/// above problematic expressions (2) is something we cannot determine leads to
5945/// a problematic expression based on such local checking.
5946///
5947/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5948/// the expression that they point to. Such variables are added to the
5949/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005950///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005951/// EvalAddr processes expressions that are pointers that are used as
5952/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005953/// At the base case of the recursion is a check for the above problematic
5954/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005955///
5956/// This implementation handles:
5957///
5958/// * pointer-to-pointer casts
5959/// * implicit conversions from array references to pointers
5960/// * taking the address of fields
5961/// * arbitrary interplay between "&" and "*" operators
5962/// * pointer arithmetic from an address of a stack variable
5963/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005964static const Expr *EvalAddr(const Expr *E,
5965 SmallVectorImpl<const DeclRefExpr *> &refVars,
5966 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005967 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005968 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005969
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005970 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005971 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005972 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005973 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005974 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005975
Peter Collingbourne91147592011-04-15 00:35:48 +00005976 E = E->IgnoreParens();
5977
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005978 // Our "symbolic interpreter" is just a dispatch off the currently
5979 // viewed AST node. We then recursively traverse the AST by calling
5980 // EvalAddr and EvalVal appropriately.
5981 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005982 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005983 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005984
Richard Smith40f08eb2014-01-30 22:05:38 +00005985 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005986 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005987 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005988
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005989 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005990 // If this is a reference variable, follow through to the expression that
5991 // it points to.
5992 if (V->hasLocalStorage() &&
5993 V->getType()->isReferenceType() && V->hasInit()) {
5994 // Add the reference variable to the "trail".
5995 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005996 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005997 }
5998
Craig Topperc3ec1492014-05-26 06:22:03 +00005999 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006000 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006001
Chris Lattner934edb22007-12-28 05:31:15 +00006002 case Stmt::UnaryOperatorClass: {
6003 // The only unary operator that make sense to handle here
6004 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006005 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006006
John McCalle3027922010-08-25 11:45:40 +00006007 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006008 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006009 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006010 }
Mike Stump11289f42009-09-09 15:08:12 +00006011
Chris Lattner934edb22007-12-28 05:31:15 +00006012 case Stmt::BinaryOperatorClass: {
6013 // Handle pointer arithmetic. All other binary operators are not valid
6014 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006015 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006016 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006017
John McCalle3027922010-08-25 11:45:40 +00006018 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006019 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006020
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006021 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006022
6023 // Determine which argument is the real pointer base. It could be
6024 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006025 if (!Base->getType()->isPointerType())
6026 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006027
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006028 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006029 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006030 }
Steve Naroff2752a172008-09-10 19:17:48 +00006031
Chris Lattner934edb22007-12-28 05:31:15 +00006032 // For conditional operators we need to see if either the LHS or RHS are
6033 // valid DeclRefExpr*s. If one of them is valid, we return it.
6034 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006035 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006036
Chris Lattner934edb22007-12-28 05:31:15 +00006037 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006038 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006039 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006040 // In C++, we can have a throw-expression, which has 'void' type.
6041 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006042 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006043 return LHS;
6044 }
Chris Lattner934edb22007-12-28 05:31:15 +00006045
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006046 // In C++, we can have a throw-expression, which has 'void' type.
6047 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006048 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006049
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006050 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006051 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006052
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006053 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006054 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006055 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006056 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006057
6058 case Stmt::AddrLabelExprClass:
6059 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006060
John McCall28fc7092011-11-10 05:35:25 +00006061 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006062 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6063 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006064
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006065 // For casts, we need to handle conversions from arrays to
6066 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006067 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006068 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006069 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006070 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006071 case Stmt::CXXStaticCastExprClass:
6072 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006073 case Stmt::CXXConstCastExprClass:
6074 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006075 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006076 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006077 case CK_LValueToRValue:
6078 case CK_NoOp:
6079 case CK_BaseToDerived:
6080 case CK_DerivedToBase:
6081 case CK_UncheckedDerivedToBase:
6082 case CK_Dynamic:
6083 case CK_CPointerToObjCPointerCast:
6084 case CK_BlockPointerToObjCPointerCast:
6085 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006086 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006087
6088 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006089 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006090
Richard Trieudadefde2014-07-02 04:39:38 +00006091 case CK_BitCast:
6092 if (SubExpr->getType()->isAnyPointerType() ||
6093 SubExpr->getType()->isBlockPointerType() ||
6094 SubExpr->getType()->isObjCQualifiedIdType())
6095 return EvalAddr(SubExpr, refVars, ParentDecl);
6096 else
6097 return nullptr;
6098
Eli Friedman8195ad72012-02-23 23:04:32 +00006099 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006100 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006101 }
Chris Lattner934edb22007-12-28 05:31:15 +00006102 }
Mike Stump11289f42009-09-09 15:08:12 +00006103
Douglas Gregorfe314812011-06-21 17:03:29 +00006104 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006105 if (const Expr *Result =
6106 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6107 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006108 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006109 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006110
Chris Lattner934edb22007-12-28 05:31:15 +00006111 // Everything else: we simply don't reason about them.
6112 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006113 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006114 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006115}
Mike Stump11289f42009-09-09 15:08:12 +00006116
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006117/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6118/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006119static const Expr *EvalVal(const Expr *E,
6120 SmallVectorImpl<const DeclRefExpr *> &refVars,
6121 const Decl *ParentDecl) {
6122 do {
6123 // We should only be called for evaluating non-pointer expressions, or
6124 // expressions with a pointer type that are not used as references but
6125 // instead
6126 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006127
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006128 // Our "symbolic interpreter" is just a dispatch off the currently
6129 // viewed AST node. We then recursively traverse the AST by calling
6130 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006131
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006132 E = E->IgnoreParens();
6133 switch (E->getStmtClass()) {
6134 case Stmt::ImplicitCastExprClass: {
6135 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6136 if (IE->getValueKind() == VK_LValue) {
6137 E = IE->getSubExpr();
6138 continue;
6139 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006140 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006141 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006142
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006143 case Stmt::ExprWithCleanupsClass:
6144 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6145 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006146
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006147 case Stmt::DeclRefExprClass: {
6148 // When we hit a DeclRefExpr we are looking at code that refers to a
6149 // variable's name. If it's not a reference variable we check if it has
6150 // local storage within the function, and if so, return the expression.
6151 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6152
6153 // If we leave the immediate function, the lifetime isn't about to end.
6154 if (DR->refersToEnclosingVariableOrCapture())
6155 return nullptr;
6156
6157 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6158 // Check if it refers to itself, e.g. "int& i = i;".
6159 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006160 return DR;
6161
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006162 if (V->hasLocalStorage()) {
6163 if (!V->getType()->isReferenceType())
6164 return DR;
6165
6166 // Reference variable, follow through to the expression that
6167 // it points to.
6168 if (V->hasInit()) {
6169 // Add the reference variable to the "trail".
6170 refVars.push_back(DR);
6171 return EvalVal(V->getInit(), refVars, V);
6172 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006173 }
6174 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006175
6176 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006177 }
Mike Stump11289f42009-09-09 15:08:12 +00006178
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006179 case Stmt::UnaryOperatorClass: {
6180 // The only unary operator that make sense to handle here
6181 // is Deref. All others don't resolve to a "name." This includes
6182 // handling all sorts of rvalues passed to a unary operator.
6183 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006184
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006185 if (U->getOpcode() == UO_Deref)
6186 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006187
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006188 return nullptr;
6189 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006190
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006191 case Stmt::ArraySubscriptExprClass: {
6192 // Array subscripts are potential references to data on the stack. We
6193 // retrieve the DeclRefExpr* for the array variable if it indeed
6194 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006195 const auto *ASE = cast<ArraySubscriptExpr>(E);
6196 if (ASE->isTypeDependent())
6197 return nullptr;
6198 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006199 }
Mike Stump11289f42009-09-09 15:08:12 +00006200
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006201 case Stmt::OMPArraySectionExprClass: {
6202 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6203 ParentDecl);
6204 }
Mike Stump11289f42009-09-09 15:08:12 +00006205
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006206 case Stmt::ConditionalOperatorClass: {
6207 // For conditional operators we need to see if either the LHS or RHS are
6208 // non-NULL Expr's. If one is non-NULL, we return it.
6209 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006210
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006211 // Handle the GNU extension for missing LHS.
6212 if (const Expr *LHSExpr = C->getLHS()) {
6213 // In C++, we can have a throw-expression, which has 'void' type.
6214 if (!LHSExpr->getType()->isVoidType())
6215 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6216 return LHS;
6217 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006218
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006219 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006220 if (C->getRHS()->getType()->isVoidType())
6221 return nullptr;
6222
6223 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006224 }
6225
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006226 // Accesses to members are potential references to data on the stack.
6227 case Stmt::MemberExprClass: {
6228 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006229
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006230 // Check for indirect access. We only want direct field accesses.
6231 if (M->isArrow())
6232 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006233
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006234 // Check whether the member type is itself a reference, in which case
6235 // we're not going to refer to the member, but to what the member refers
6236 // to.
6237 if (M->getMemberDecl()->getType()->isReferenceType())
6238 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006239
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006240 return EvalVal(M->getBase(), refVars, ParentDecl);
6241 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006242
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006243 case Stmt::MaterializeTemporaryExprClass:
6244 if (const Expr *Result =
6245 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6246 refVars, ParentDecl))
6247 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006248 return E;
6249
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006250 default:
6251 // Check that we don't return or take the address of a reference to a
6252 // temporary. This is only useful in C++.
6253 if (!E->isTypeDependent() && E->isRValue())
6254 return E;
6255
6256 // Everything else: we simply don't reason about them.
6257 return nullptr;
6258 }
6259 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006260}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006261
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006262void
6263Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6264 SourceLocation ReturnLoc,
6265 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006266 const AttrVec *Attrs,
6267 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006268 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6269
6270 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006271 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6272 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006273 CheckNonNullExpr(*this, RetValExp))
6274 Diag(ReturnLoc, diag::warn_null_ret)
6275 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006276
6277 // C++11 [basic.stc.dynamic.allocation]p4:
6278 // If an allocation function declared with a non-throwing
6279 // exception-specification fails to allocate storage, it shall return
6280 // a null pointer. Any other allocation function that fails to allocate
6281 // storage shall indicate failure only by throwing an exception [...]
6282 if (FD) {
6283 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6284 if (Op == OO_New || Op == OO_Array_New) {
6285 const FunctionProtoType *Proto
6286 = FD->getType()->castAs<FunctionProtoType>();
6287 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6288 CheckNonNullExpr(*this, RetValExp))
6289 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6290 << FD << getLangOpts().CPlusPlus11;
6291 }
6292 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006293}
6294
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006295//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6296
6297/// Check for comparisons of floating point operands using != and ==.
6298/// Issue a warning if these are no self-comparisons, as they are not likely
6299/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006300void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006301 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6302 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006303
6304 // Special case: check for x == x (which is OK).
6305 // Do not emit warnings for such cases.
6306 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6307 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6308 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006309 return;
Mike Stump11289f42009-09-09 15:08:12 +00006310
Ted Kremenekeda40e22007-11-29 00:59:04 +00006311 // Special case: check for comparisons against literals that can be exactly
6312 // represented by APFloat. In such cases, do not emit a warning. This
6313 // is a heuristic: often comparison against such literals are used to
6314 // detect if a value in a variable has not changed. This clearly can
6315 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006316 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6317 if (FLL->isExact())
6318 return;
6319 } else
6320 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6321 if (FLR->isExact())
6322 return;
Mike Stump11289f42009-09-09 15:08:12 +00006323
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006324 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006325 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006326 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006327 return;
Mike Stump11289f42009-09-09 15:08:12 +00006328
David Blaikie1f4ff152012-07-16 20:47:22 +00006329 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006330 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006331 return;
Mike Stump11289f42009-09-09 15:08:12 +00006332
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006333 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006334 Diag(Loc, diag::warn_floatingpoint_eq)
6335 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006336}
John McCallca01b222010-01-04 23:21:16 +00006337
John McCall70aa5392010-01-06 05:24:50 +00006338//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6339//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006340
John McCall70aa5392010-01-06 05:24:50 +00006341namespace {
John McCallca01b222010-01-04 23:21:16 +00006342
John McCall70aa5392010-01-06 05:24:50 +00006343/// Structure recording the 'active' range of an integer-valued
6344/// expression.
6345struct IntRange {
6346 /// The number of bits active in the int.
6347 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006348
John McCall70aa5392010-01-06 05:24:50 +00006349 /// True if the int is known not to have negative values.
6350 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006351
John McCall70aa5392010-01-06 05:24:50 +00006352 IntRange(unsigned Width, bool NonNegative)
6353 : Width(Width), NonNegative(NonNegative)
6354 {}
John McCallca01b222010-01-04 23:21:16 +00006355
John McCall817d4af2010-11-10 23:38:19 +00006356 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006357 static IntRange forBoolType() {
6358 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006359 }
6360
John McCall817d4af2010-11-10 23:38:19 +00006361 /// Returns the range of an opaque value of the given integral type.
6362 static IntRange forValueOfType(ASTContext &C, QualType T) {
6363 return forValueOfCanonicalType(C,
6364 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006365 }
6366
John McCall817d4af2010-11-10 23:38:19 +00006367 /// Returns the range of an opaque value of a canonical integral type.
6368 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006369 assert(T->isCanonicalUnqualified());
6370
6371 if (const VectorType *VT = dyn_cast<VectorType>(T))
6372 T = VT->getElementType().getTypePtr();
6373 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6374 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006375 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6376 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006377
David Majnemer6a426652013-06-07 22:07:20 +00006378 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006379 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006380 EnumDecl *Enum = ET->getDecl();
6381 if (!Enum->isCompleteDefinition())
6382 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006383
David Majnemer6a426652013-06-07 22:07:20 +00006384 unsigned NumPositive = Enum->getNumPositiveBits();
6385 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006386
David Majnemer6a426652013-06-07 22:07:20 +00006387 if (NumNegative == 0)
6388 return IntRange(NumPositive, true/*NonNegative*/);
6389 else
6390 return IntRange(std::max(NumPositive + 1, NumNegative),
6391 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006392 }
John McCall70aa5392010-01-06 05:24:50 +00006393
6394 const BuiltinType *BT = cast<BuiltinType>(T);
6395 assert(BT->isInteger());
6396
6397 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6398 }
6399
John McCall817d4af2010-11-10 23:38:19 +00006400 /// Returns the "target" range of a canonical integral type, i.e.
6401 /// the range of values expressible in the type.
6402 ///
6403 /// This matches forValueOfCanonicalType except that enums have the
6404 /// full range of their type, not the range of their enumerators.
6405 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6406 assert(T->isCanonicalUnqualified());
6407
6408 if (const VectorType *VT = dyn_cast<VectorType>(T))
6409 T = VT->getElementType().getTypePtr();
6410 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6411 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006412 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6413 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006414 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006415 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006416
6417 const BuiltinType *BT = cast<BuiltinType>(T);
6418 assert(BT->isInteger());
6419
6420 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6421 }
6422
6423 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006424 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006425 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006426 L.NonNegative && R.NonNegative);
6427 }
6428
John McCall817d4af2010-11-10 23:38:19 +00006429 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006430 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006431 return IntRange(std::min(L.Width, R.Width),
6432 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006433 }
6434};
6435
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006436IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006437 if (value.isSigned() && value.isNegative())
6438 return IntRange(value.getMinSignedBits(), false);
6439
6440 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006441 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006442
6443 // isNonNegative() just checks the sign bit without considering
6444 // signedness.
6445 return IntRange(value.getActiveBits(), true);
6446}
6447
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006448IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6449 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006450 if (result.isInt())
6451 return GetValueRange(C, result.getInt(), MaxWidth);
6452
6453 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006454 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6455 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6456 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6457 R = IntRange::join(R, El);
6458 }
John McCall70aa5392010-01-06 05:24:50 +00006459 return R;
6460 }
6461
6462 if (result.isComplexInt()) {
6463 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6464 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6465 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006466 }
6467
6468 // This can happen with lossless casts to intptr_t of "based" lvalues.
6469 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006470 // FIXME: The only reason we need to pass the type in here is to get
6471 // the sign right on this one case. It would be nice if APValue
6472 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006473 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006474 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006475}
John McCall70aa5392010-01-06 05:24:50 +00006476
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006477QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006478 QualType Ty = E->getType();
6479 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6480 Ty = AtomicRHS->getValueType();
6481 return Ty;
6482}
6483
John McCall70aa5392010-01-06 05:24:50 +00006484/// Pseudo-evaluate the given integer expression, estimating the
6485/// range of values it might take.
6486///
6487/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006488IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006489 E = E->IgnoreParens();
6490
6491 // Try a full evaluation first.
6492 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006493 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006494 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006495
6496 // I think we only want to look through implicit casts here; if the
6497 // user has an explicit widening cast, we should treat the value as
6498 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006499 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006500 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006501 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6502
Eli Friedmane6d33952013-07-08 20:20:06 +00006503 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006504
George Burgess IVdf1ed002016-01-13 01:52:39 +00006505 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6506 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006507
John McCall70aa5392010-01-06 05:24:50 +00006508 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006509 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006510 return OutputTypeRange;
6511
6512 IntRange SubRange
6513 = GetExprRange(C, CE->getSubExpr(),
6514 std::min(MaxWidth, OutputTypeRange.Width));
6515
6516 // Bail out if the subexpr's range is as wide as the cast type.
6517 if (SubRange.Width >= OutputTypeRange.Width)
6518 return OutputTypeRange;
6519
6520 // Otherwise, we take the smaller width, and we're non-negative if
6521 // either the output type or the subexpr is.
6522 return IntRange(SubRange.Width,
6523 SubRange.NonNegative || OutputTypeRange.NonNegative);
6524 }
6525
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006526 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006527 // If we can fold the condition, just take that operand.
6528 bool CondResult;
6529 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6530 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6531 : CO->getFalseExpr(),
6532 MaxWidth);
6533
6534 // Otherwise, conservatively merge.
6535 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6536 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6537 return IntRange::join(L, R);
6538 }
6539
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006540 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006541 switch (BO->getOpcode()) {
6542
6543 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006544 case BO_LAnd:
6545 case BO_LOr:
6546 case BO_LT:
6547 case BO_GT:
6548 case BO_LE:
6549 case BO_GE:
6550 case BO_EQ:
6551 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006552 return IntRange::forBoolType();
6553
John McCallc3688382011-07-13 06:35:24 +00006554 // The type of the assignments is the type of the LHS, so the RHS
6555 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006556 case BO_MulAssign:
6557 case BO_DivAssign:
6558 case BO_RemAssign:
6559 case BO_AddAssign:
6560 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006561 case BO_XorAssign:
6562 case BO_OrAssign:
6563 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006564 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006565
John McCallc3688382011-07-13 06:35:24 +00006566 // Simple assignments just pass through the RHS, which will have
6567 // been coerced to the LHS type.
6568 case BO_Assign:
6569 // TODO: bitfields?
6570 return GetExprRange(C, BO->getRHS(), MaxWidth);
6571
John McCall70aa5392010-01-06 05:24:50 +00006572 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006573 case BO_PtrMemD:
6574 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006575 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006576
John McCall2ce81ad2010-01-06 22:07:33 +00006577 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006578 case BO_And:
6579 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006580 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6581 GetExprRange(C, BO->getRHS(), MaxWidth));
6582
John McCall70aa5392010-01-06 05:24:50 +00006583 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006584 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006585 // ...except that we want to treat '1 << (blah)' as logically
6586 // positive. It's an important idiom.
6587 if (IntegerLiteral *I
6588 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6589 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006590 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006591 return IntRange(R.Width, /*NonNegative*/ true);
6592 }
6593 }
6594 // fallthrough
6595
John McCalle3027922010-08-25 11:45:40 +00006596 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006597 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006598
John McCall2ce81ad2010-01-06 22:07:33 +00006599 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006600 case BO_Shr:
6601 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006602 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6603
6604 // If the shift amount is a positive constant, drop the width by
6605 // that much.
6606 llvm::APSInt shift;
6607 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6608 shift.isNonNegative()) {
6609 unsigned zext = shift.getZExtValue();
6610 if (zext >= L.Width)
6611 L.Width = (L.NonNegative ? 0 : 1);
6612 else
6613 L.Width -= zext;
6614 }
6615
6616 return L;
6617 }
6618
6619 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006620 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006621 return GetExprRange(C, BO->getRHS(), MaxWidth);
6622
John McCall2ce81ad2010-01-06 22:07:33 +00006623 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006624 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006625 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006626 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006627 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006628
John McCall51431812011-07-14 22:39:48 +00006629 // The width of a division result is mostly determined by the size
6630 // of the LHS.
6631 case BO_Div: {
6632 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006633 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006634 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6635
6636 // If the divisor is constant, use that.
6637 llvm::APSInt divisor;
6638 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6639 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6640 if (log2 >= L.Width)
6641 L.Width = (L.NonNegative ? 0 : 1);
6642 else
6643 L.Width = std::min(L.Width - log2, MaxWidth);
6644 return L;
6645 }
6646
6647 // Otherwise, just use the LHS's width.
6648 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6649 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6650 }
6651
6652 // The result of a remainder can't be larger than the result of
6653 // either side.
6654 case BO_Rem: {
6655 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006656 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006657 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6658 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6659
6660 IntRange meet = IntRange::meet(L, R);
6661 meet.Width = std::min(meet.Width, MaxWidth);
6662 return meet;
6663 }
6664
6665 // The default behavior is okay for these.
6666 case BO_Mul:
6667 case BO_Add:
6668 case BO_Xor:
6669 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006670 break;
6671 }
6672
John McCall51431812011-07-14 22:39:48 +00006673 // The default case is to treat the operation as if it were closed
6674 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006675 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6676 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6677 return IntRange::join(L, R);
6678 }
6679
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006680 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006681 switch (UO->getOpcode()) {
6682 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006683 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006684 return IntRange::forBoolType();
6685
6686 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006687 case UO_Deref:
6688 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006689 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006690
6691 default:
6692 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6693 }
6694 }
6695
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006696 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006697 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6698
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006699 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006700 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006701 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006702
Eli Friedmane6d33952013-07-08 20:20:06 +00006703 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006704}
John McCall263a48b2010-01-04 23:31:57 +00006705
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006706IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006707 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006708}
6709
John McCall263a48b2010-01-04 23:31:57 +00006710/// Checks whether the given value, which currently has the given
6711/// source semantics, has the same value when coerced through the
6712/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006713bool IsSameFloatAfterCast(const llvm::APFloat &value,
6714 const llvm::fltSemantics &Src,
6715 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006716 llvm::APFloat truncated = value;
6717
6718 bool ignored;
6719 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6720 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6721
6722 return truncated.bitwiseIsEqual(value);
6723}
6724
6725/// Checks whether the given value, which currently has the given
6726/// source semantics, has the same value when coerced through the
6727/// target semantics.
6728///
6729/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006730bool IsSameFloatAfterCast(const APValue &value,
6731 const llvm::fltSemantics &Src,
6732 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006733 if (value.isFloat())
6734 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6735
6736 if (value.isVector()) {
6737 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6738 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6739 return false;
6740 return true;
6741 }
6742
6743 assert(value.isComplexFloat());
6744 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6745 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6746}
6747
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006748void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006749
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006750bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006751 // Suppress cases where we are comparing against an enum constant.
6752 if (const DeclRefExpr *DR =
6753 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6754 if (isa<EnumConstantDecl>(DR->getDecl()))
6755 return false;
6756
6757 // Suppress cases where the '0' value is expanded from a macro.
6758 if (E->getLocStart().isMacroID())
6759 return false;
6760
John McCallcc7e5bf2010-05-06 08:58:33 +00006761 llvm::APSInt Value;
6762 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6763}
6764
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006765bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006766 // Strip off implicit integral promotions.
6767 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006768 if (ICE->getCastKind() != CK_IntegralCast &&
6769 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006770 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006771 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006772 }
6773
6774 return E->getType()->isEnumeralType();
6775}
6776
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006777void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006778 // Disable warning in template instantiations.
6779 if (!S.ActiveTemplateInstantiations.empty())
6780 return;
6781
John McCalle3027922010-08-25 11:45:40 +00006782 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006783 if (E->isValueDependent())
6784 return;
6785
John McCalle3027922010-08-25 11:45:40 +00006786 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006787 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006788 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006789 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006790 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006791 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006792 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006793 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006794 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006795 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006796 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006797 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006798 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006799 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006800 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006801 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6802 }
6803}
6804
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006805void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6806 Expr *Constant, Expr *Other,
6807 llvm::APSInt Value,
6808 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006809 // Disable warning in template instantiations.
6810 if (!S.ActiveTemplateInstantiations.empty())
6811 return;
6812
Richard Trieu0f097742014-04-04 04:13:47 +00006813 // TODO: Investigate using GetExprRange() to get tighter bounds
6814 // on the bit ranges.
6815 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006816 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006817 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006818 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6819 unsigned OtherWidth = OtherRange.Width;
6820
6821 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6822
Richard Trieu560910c2012-11-14 22:50:24 +00006823 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006824 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006825 return;
6826
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006827 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006828 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006829
Richard Trieu0f097742014-04-04 04:13:47 +00006830 // Used for diagnostic printout.
6831 enum {
6832 LiteralConstant = 0,
6833 CXXBoolLiteralTrue,
6834 CXXBoolLiteralFalse
6835 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006836
Richard Trieu0f097742014-04-04 04:13:47 +00006837 if (!OtherIsBooleanType) {
6838 QualType ConstantT = Constant->getType();
6839 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006840
Richard Trieu0f097742014-04-04 04:13:47 +00006841 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6842 return;
6843 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6844 "comparison with non-integer type");
6845
6846 bool ConstantSigned = ConstantT->isSignedIntegerType();
6847 bool CommonSigned = CommonT->isSignedIntegerType();
6848
6849 bool EqualityOnly = false;
6850
6851 if (CommonSigned) {
6852 // The common type is signed, therefore no signed to unsigned conversion.
6853 if (!OtherRange.NonNegative) {
6854 // Check that the constant is representable in type OtherT.
6855 if (ConstantSigned) {
6856 if (OtherWidth >= Value.getMinSignedBits())
6857 return;
6858 } else { // !ConstantSigned
6859 if (OtherWidth >= Value.getActiveBits() + 1)
6860 return;
6861 }
6862 } else { // !OtherSigned
6863 // Check that the constant is representable in type OtherT.
6864 // Negative values are out of range.
6865 if (ConstantSigned) {
6866 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6867 return;
6868 } else { // !ConstantSigned
6869 if (OtherWidth >= Value.getActiveBits())
6870 return;
6871 }
Richard Trieu560910c2012-11-14 22:50:24 +00006872 }
Richard Trieu0f097742014-04-04 04:13:47 +00006873 } else { // !CommonSigned
6874 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006875 if (OtherWidth >= Value.getActiveBits())
6876 return;
Craig Toppercf360162014-06-18 05:13:11 +00006877 } else { // OtherSigned
6878 assert(!ConstantSigned &&
6879 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006880 // Check to see if the constant is representable in OtherT.
6881 if (OtherWidth > Value.getActiveBits())
6882 return;
6883 // Check to see if the constant is equivalent to a negative value
6884 // cast to CommonT.
6885 if (S.Context.getIntWidth(ConstantT) ==
6886 S.Context.getIntWidth(CommonT) &&
6887 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6888 return;
6889 // The constant value rests between values that OtherT can represent
6890 // after conversion. Relational comparison still works, but equality
6891 // comparisons will be tautological.
6892 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006893 }
6894 }
Richard Trieu0f097742014-04-04 04:13:47 +00006895
6896 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6897
6898 if (op == BO_EQ || op == BO_NE) {
6899 IsTrue = op == BO_NE;
6900 } else if (EqualityOnly) {
6901 return;
6902 } else if (RhsConstant) {
6903 if (op == BO_GT || op == BO_GE)
6904 IsTrue = !PositiveConstant;
6905 else // op == BO_LT || op == BO_LE
6906 IsTrue = PositiveConstant;
6907 } else {
6908 if (op == BO_LT || op == BO_LE)
6909 IsTrue = !PositiveConstant;
6910 else // op == BO_GT || op == BO_GE
6911 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006912 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006913 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006914 // Other isKnownToHaveBooleanValue
6915 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6916 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6917 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6918
6919 static const struct LinkedConditions {
6920 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6921 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6922 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6923 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6924 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6925 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6926
6927 } TruthTable = {
6928 // Constant on LHS. | Constant on RHS. |
6929 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6930 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6931 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6932 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6933 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6934 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6935 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6936 };
6937
6938 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6939
6940 enum ConstantValue ConstVal = Zero;
6941 if (Value.isUnsigned() || Value.isNonNegative()) {
6942 if (Value == 0) {
6943 LiteralOrBoolConstant =
6944 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6945 ConstVal = Zero;
6946 } else if (Value == 1) {
6947 LiteralOrBoolConstant =
6948 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6949 ConstVal = One;
6950 } else {
6951 LiteralOrBoolConstant = LiteralConstant;
6952 ConstVal = GT_One;
6953 }
6954 } else {
6955 ConstVal = LT_Zero;
6956 }
6957
6958 CompareBoolWithConstantResult CmpRes;
6959
6960 switch (op) {
6961 case BO_LT:
6962 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6963 break;
6964 case BO_GT:
6965 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6966 break;
6967 case BO_LE:
6968 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6969 break;
6970 case BO_GE:
6971 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6972 break;
6973 case BO_EQ:
6974 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6975 break;
6976 case BO_NE:
6977 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6978 break;
6979 default:
6980 CmpRes = Unkwn;
6981 break;
6982 }
6983
6984 if (CmpRes == AFals) {
6985 IsTrue = false;
6986 } else if (CmpRes == ATrue) {
6987 IsTrue = true;
6988 } else {
6989 return;
6990 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006991 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006992
6993 // If this is a comparison to an enum constant, include that
6994 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006995 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006996 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6997 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6998
6999 SmallString<64> PrettySourceValue;
7000 llvm::raw_svector_ostream OS(PrettySourceValue);
7001 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00007002 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00007003 else
7004 OS << Value;
7005
Richard Trieu0f097742014-04-04 04:13:47 +00007006 S.DiagRuntimeBehavior(
7007 E->getOperatorLoc(), E,
7008 S.PDiag(diag::warn_out_of_range_compare)
7009 << OS.str() << LiteralOrBoolConstant
7010 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7011 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007012}
7013
John McCallcc7e5bf2010-05-06 08:58:33 +00007014/// Analyze the operands of the given comparison. Implements the
7015/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007016void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007017 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7018 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007019}
John McCall263a48b2010-01-04 23:31:57 +00007020
John McCallca01b222010-01-04 23:21:16 +00007021/// \brief Implements -Wsign-compare.
7022///
Richard Trieu82402a02011-09-15 21:56:47 +00007023/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007024void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007025 // The type the comparison is being performed in.
7026 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007027
7028 // Only analyze comparison operators where both sides have been converted to
7029 // the same type.
7030 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7031 return AnalyzeImpConvsInComparison(S, E);
7032
7033 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007034 if (E->isValueDependent())
7035 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007036
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007037 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7038 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007039
7040 bool IsComparisonConstant = false;
7041
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007042 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007043 // of 'true' or 'false'.
7044 if (T->isIntegralType(S.Context)) {
7045 llvm::APSInt RHSValue;
7046 bool IsRHSIntegralLiteral =
7047 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7048 llvm::APSInt LHSValue;
7049 bool IsLHSIntegralLiteral =
7050 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7051 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7052 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7053 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7054 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7055 else
7056 IsComparisonConstant =
7057 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007058 } else if (!T->hasUnsignedIntegerRepresentation())
7059 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007060
John McCallcc7e5bf2010-05-06 08:58:33 +00007061 // We don't do anything special if this isn't an unsigned integral
7062 // comparison: we're only interested in integral comparisons, and
7063 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007064 //
7065 // We also don't care about value-dependent expressions or expressions
7066 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007067 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007068 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007069
John McCallcc7e5bf2010-05-06 08:58:33 +00007070 // Check to see if one of the (unmodified) operands is of different
7071 // signedness.
7072 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007073 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7074 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007075 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007076 signedOperand = LHS;
7077 unsignedOperand = RHS;
7078 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7079 signedOperand = RHS;
7080 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007081 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007082 CheckTrivialUnsignedComparison(S, E);
7083 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007084 }
7085
John McCallcc7e5bf2010-05-06 08:58:33 +00007086 // Otherwise, calculate the effective range of the signed operand.
7087 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007088
John McCallcc7e5bf2010-05-06 08:58:33 +00007089 // Go ahead and analyze implicit conversions in the operands. Note
7090 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007091 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7092 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007093
John McCallcc7e5bf2010-05-06 08:58:33 +00007094 // If the signed range is non-negative, -Wsign-compare won't fire,
7095 // but we should still check for comparisons which are always true
7096 // or false.
7097 if (signedRange.NonNegative)
7098 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007099
7100 // For (in)equality comparisons, if the unsigned operand is a
7101 // constant which cannot collide with a overflowed signed operand,
7102 // then reinterpreting the signed operand as unsigned will not
7103 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007104 if (E->isEqualityOp()) {
7105 unsigned comparisonWidth = S.Context.getIntWidth(T);
7106 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007107
John McCallcc7e5bf2010-05-06 08:58:33 +00007108 // We should never be unable to prove that the unsigned operand is
7109 // non-negative.
7110 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7111
7112 if (unsignedRange.Width < comparisonWidth)
7113 return;
7114 }
7115
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007116 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7117 S.PDiag(diag::warn_mixed_sign_comparison)
7118 << LHS->getType() << RHS->getType()
7119 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007120}
7121
John McCall1f425642010-11-11 03:21:53 +00007122/// Analyzes an attempt to assign the given value to a bitfield.
7123///
7124/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007125bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7126 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007127 assert(Bitfield->isBitField());
7128 if (Bitfield->isInvalidDecl())
7129 return false;
7130
John McCalldeebbcf2010-11-11 05:33:51 +00007131 // White-list bool bitfields.
7132 if (Bitfield->getType()->isBooleanType())
7133 return false;
7134
Douglas Gregor789adec2011-02-04 13:09:01 +00007135 // Ignore value- or type-dependent expressions.
7136 if (Bitfield->getBitWidth()->isValueDependent() ||
7137 Bitfield->getBitWidth()->isTypeDependent() ||
7138 Init->isValueDependent() ||
7139 Init->isTypeDependent())
7140 return false;
7141
John McCall1f425642010-11-11 03:21:53 +00007142 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7143
Richard Smith5fab0c92011-12-28 19:48:30 +00007144 llvm::APSInt Value;
7145 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007146 return false;
7147
John McCall1f425642010-11-11 03:21:53 +00007148 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007149 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007150
7151 if (OriginalWidth <= FieldWidth)
7152 return false;
7153
Eli Friedmanc267a322012-01-26 23:11:39 +00007154 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007155 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007156 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007157
Eli Friedmanc267a322012-01-26 23:11:39 +00007158 // Check whether the stored value is equal to the original value.
7159 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007160 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007161 return false;
7162
Eli Friedmanc267a322012-01-26 23:11:39 +00007163 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007164 // therefore don't strictly fit into a signed bitfield of width 1.
7165 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007166 return false;
7167
John McCall1f425642010-11-11 03:21:53 +00007168 std::string PrettyValue = Value.toString(10);
7169 std::string PrettyTrunc = TruncatedValue.toString(10);
7170
7171 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7172 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7173 << Init->getSourceRange();
7174
7175 return true;
7176}
7177
John McCalld2a53122010-11-09 23:24:47 +00007178/// Analyze the given simple or compound assignment for warning-worthy
7179/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007180void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007181 // Just recurse on the LHS.
7182 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7183
7184 // We want to recurse on the RHS as normal unless we're assigning to
7185 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007186 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007187 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007188 E->getOperatorLoc())) {
7189 // Recurse, ignoring any implicit conversions on the RHS.
7190 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7191 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007192 }
7193 }
7194
7195 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7196}
7197
John McCall263a48b2010-01-04 23:31:57 +00007198/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007199void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7200 SourceLocation CContext, unsigned diag,
7201 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007202 if (pruneControlFlow) {
7203 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7204 S.PDiag(diag)
7205 << SourceType << T << E->getSourceRange()
7206 << SourceRange(CContext));
7207 return;
7208 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007209 S.Diag(E->getExprLoc(), diag)
7210 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7211}
7212
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007213/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007214void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7215 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007216 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007217}
7218
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007219/// Diagnose an implicit cast from a literal expression. Does not warn when the
7220/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007221void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7222 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007223 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007224 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007225 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007226 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7227 T->hasUnsignedIntegerRepresentation());
7228 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007229 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007230 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007231 return;
7232
Eli Friedman07185912013-08-29 23:44:43 +00007233 // FIXME: Force the precision of the source value down so we don't print
7234 // digits which are usually useless (we don't really care here if we
7235 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7236 // would automatically print the shortest representation, but it's a bit
7237 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007238 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007239 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7240 precision = (precision * 59 + 195) / 196;
7241 Value.toString(PrettySourceValue, precision);
7242
David Blaikie9b88cc02012-05-15 17:18:27 +00007243 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007244 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007245 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007246 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007247 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007248
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007249 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007250 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7251 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007252}
7253
John McCall18a2c2c2010-11-09 22:22:12 +00007254std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7255 if (!Range.Width) return "0";
7256
7257 llvm::APSInt ValueInRange = Value;
7258 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007259 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007260 return ValueInRange.toString(10);
7261}
7262
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007263bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007264 if (!isa<ImplicitCastExpr>(Ex))
7265 return false;
7266
7267 Expr *InnerE = Ex->IgnoreParenImpCasts();
7268 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7269 const Type *Source =
7270 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7271 if (Target->isDependentType())
7272 return false;
7273
7274 const BuiltinType *FloatCandidateBT =
7275 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7276 const Type *BoolCandidateType = ToBool ? Target : Source;
7277
7278 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7279 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7280}
7281
7282void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7283 SourceLocation CC) {
7284 unsigned NumArgs = TheCall->getNumArgs();
7285 for (unsigned i = 0; i < NumArgs; ++i) {
7286 Expr *CurrA = TheCall->getArg(i);
7287 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7288 continue;
7289
7290 bool IsSwapped = ((i > 0) &&
7291 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7292 IsSwapped |= ((i < (NumArgs - 1)) &&
7293 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7294 if (IsSwapped) {
7295 // Warn on this floating-point to bool conversion.
7296 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7297 CurrA->getType(), CC,
7298 diag::warn_impcast_floating_point_to_bool);
7299 }
7300 }
7301}
7302
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007303void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007304 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7305 E->getExprLoc()))
7306 return;
7307
Richard Trieu09d6b802016-01-08 23:35:06 +00007308 // Don't warn on functions which have return type nullptr_t.
7309 if (isa<CallExpr>(E))
7310 return;
7311
Richard Trieu5b993502014-10-15 03:42:06 +00007312 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7313 const Expr::NullPointerConstantKind NullKind =
7314 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7315 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7316 return;
7317
7318 // Return if target type is a safe conversion.
7319 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7320 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7321 return;
7322
7323 SourceLocation Loc = E->getSourceRange().getBegin();
7324
Richard Trieu0a5e1662016-02-13 00:58:53 +00007325 // Venture through the macro stacks to get to the source of macro arguments.
7326 // The new location is a better location than the complete location that was
7327 // passed in.
7328 while (S.SourceMgr.isMacroArgExpansion(Loc))
7329 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7330
7331 while (S.SourceMgr.isMacroArgExpansion(CC))
7332 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7333
Richard Trieu5b993502014-10-15 03:42:06 +00007334 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007335 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7336 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7337 Loc, S.SourceMgr, S.getLangOpts());
7338 if (MacroName == "NULL")
7339 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007340 }
7341
7342 // Only warn if the null and context location are in the same macro expansion.
7343 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7344 return;
7345
7346 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7347 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7348 << FixItHint::CreateReplacement(Loc,
7349 S.getFixItZeroLiteralForType(T, Loc));
7350}
7351
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007352void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7353 ObjCArrayLiteral *ArrayLiteral);
7354void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7355 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007356
7357/// Check a single element within a collection literal against the
7358/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007359void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7360 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007361 // Skip a bitcast to 'id' or qualified 'id'.
7362 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7363 if (ICE->getCastKind() == CK_BitCast &&
7364 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7365 Element = ICE->getSubExpr();
7366 }
7367
7368 QualType ElementType = Element->getType();
7369 ExprResult ElementResult(Element);
7370 if (ElementType->getAs<ObjCObjectPointerType>() &&
7371 S.CheckSingleAssignmentConstraints(TargetElementType,
7372 ElementResult,
7373 false, false)
7374 != Sema::Compatible) {
7375 S.Diag(Element->getLocStart(),
7376 diag::warn_objc_collection_literal_element)
7377 << ElementType << ElementKind << TargetElementType
7378 << Element->getSourceRange();
7379 }
7380
7381 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7382 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7383 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7384 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7385}
7386
7387/// Check an Objective-C array literal being converted to the given
7388/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007389void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7390 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007391 if (!S.NSArrayDecl)
7392 return;
7393
7394 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7395 if (!TargetObjCPtr)
7396 return;
7397
7398 if (TargetObjCPtr->isUnspecialized() ||
7399 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7400 != S.NSArrayDecl->getCanonicalDecl())
7401 return;
7402
7403 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7404 if (TypeArgs.size() != 1)
7405 return;
7406
7407 QualType TargetElementType = TypeArgs[0];
7408 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7409 checkObjCCollectionLiteralElement(S, TargetElementType,
7410 ArrayLiteral->getElement(I),
7411 0);
7412 }
7413}
7414
7415/// Check an Objective-C dictionary literal being converted to the given
7416/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007417void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7418 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007419 if (!S.NSDictionaryDecl)
7420 return;
7421
7422 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7423 if (!TargetObjCPtr)
7424 return;
7425
7426 if (TargetObjCPtr->isUnspecialized() ||
7427 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7428 != S.NSDictionaryDecl->getCanonicalDecl())
7429 return;
7430
7431 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7432 if (TypeArgs.size() != 2)
7433 return;
7434
7435 QualType TargetKeyType = TypeArgs[0];
7436 QualType TargetObjectType = TypeArgs[1];
7437 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7438 auto Element = DictionaryLiteral->getKeyValueElement(I);
7439 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7440 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7441 }
7442}
7443
Richard Trieufc404c72016-02-05 23:02:38 +00007444// Helper function to filter out cases for constant width constant conversion.
7445// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007446bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7447 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007448 // If initializing from a constant, and the constant starts with '0',
7449 // then it is a binary, octal, or hexadecimal. Allow these constants
7450 // to fill all the bits, even if there is a sign change.
7451 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7452 const char FirstLiteralCharacter =
7453 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7454 if (FirstLiteralCharacter == '0')
7455 return false;
7456 }
7457
7458 // If the CC location points to a '{', and the type is char, then assume
7459 // assume it is an array initialization.
7460 if (CC.isValid() && T->isCharType()) {
7461 const char FirstContextCharacter =
7462 S.getSourceManager().getCharacterData(CC)[0];
7463 if (FirstContextCharacter == '{')
7464 return false;
7465 }
7466
7467 return true;
7468}
7469
John McCallcc7e5bf2010-05-06 08:58:33 +00007470void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007471 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007472 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007473
John McCallcc7e5bf2010-05-06 08:58:33 +00007474 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7475 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7476 if (Source == Target) return;
7477 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007478
Chandler Carruthc22845a2011-07-26 05:40:03 +00007479 // If the conversion context location is invalid don't complain. We also
7480 // don't want to emit a warning if the issue occurs from the expansion of
7481 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7482 // delay this check as long as possible. Once we detect we are in that
7483 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007484 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007485 return;
7486
Richard Trieu021baa32011-09-23 20:10:00 +00007487 // Diagnose implicit casts to bool.
7488 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7489 if (isa<StringLiteral>(E))
7490 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007491 // and expressions, for instance, assert(0 && "error here"), are
7492 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007493 return DiagnoseImpCast(S, E, T, CC,
7494 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007495 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7496 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7497 // This covers the literal expressions that evaluate to Objective-C
7498 // objects.
7499 return DiagnoseImpCast(S, E, T, CC,
7500 diag::warn_impcast_objective_c_literal_to_bool);
7501 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007502 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7503 // Warn on pointer to bool conversion that is always true.
7504 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7505 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007506 }
Richard Trieu021baa32011-09-23 20:10:00 +00007507 }
John McCall263a48b2010-01-04 23:31:57 +00007508
Douglas Gregor5054cb02015-07-07 03:58:22 +00007509 // Check implicit casts from Objective-C collection literals to specialized
7510 // collection types, e.g., NSArray<NSString *> *.
7511 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7512 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7513 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7514 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7515
John McCall263a48b2010-01-04 23:31:57 +00007516 // Strip vector types.
7517 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007518 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007519 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007520 return;
John McCallacf0ee52010-10-08 02:01:28 +00007521 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007522 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007523
7524 // If the vector cast is cast between two vectors of the same size, it is
7525 // a bitcast, not a conversion.
7526 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7527 return;
John McCall263a48b2010-01-04 23:31:57 +00007528
7529 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7530 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7531 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007532 if (auto VecTy = dyn_cast<VectorType>(Target))
7533 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007534
7535 // Strip complex types.
7536 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007537 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007538 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007539 return;
7540
John McCallacf0ee52010-10-08 02:01:28 +00007541 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007542 }
John McCall263a48b2010-01-04 23:31:57 +00007543
7544 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7545 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7546 }
7547
7548 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7549 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7550
7551 // If the source is floating point...
7552 if (SourceBT && SourceBT->isFloatingPoint()) {
7553 // ...and the target is floating point...
7554 if (TargetBT && TargetBT->isFloatingPoint()) {
7555 // ...then warn if we're dropping FP rank.
7556
7557 // Builtin FP kinds are ordered by increasing FP rank.
7558 if (SourceBT->getKind() > TargetBT->getKind()) {
7559 // Don't warn about float constants that are precisely
7560 // representable in the target type.
7561 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007562 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007563 // Value might be a float, a float vector, or a float complex.
7564 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007565 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7566 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007567 return;
7568 }
7569
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007570 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007571 return;
7572
John McCallacf0ee52010-10-08 02:01:28 +00007573 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007574 }
7575 // ... or possibly if we're increasing rank, too
7576 else if (TargetBT->getKind() > SourceBT->getKind()) {
7577 if (S.SourceMgr.isInSystemMacro(CC))
7578 return;
7579
7580 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007581 }
7582 return;
7583 }
7584
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007585 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007586 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007587 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007588 return;
7589
Chandler Carruth22c7a792011-02-17 11:05:49 +00007590 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007591 // We also want to warn on, e.g., "int i = -1.234"
7592 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7593 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7594 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7595
Chandler Carruth016ef402011-04-10 08:36:24 +00007596 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7597 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007598 } else {
7599 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7600 }
7601 }
John McCall263a48b2010-01-04 23:31:57 +00007602
Richard Smith54894fd2015-12-30 01:06:52 +00007603 // Detect the case where a call result is converted from floating-point to
7604 // to bool, and the final argument to the call is converted from bool, to
7605 // discover this typo:
7606 //
7607 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7608 //
7609 // FIXME: This is an incredibly special case; is there some more general
7610 // way to detect this class of misplaced-parentheses bug?
7611 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007612 // Check last argument of function call to see if it is an
7613 // implicit cast from a type matching the type the result
7614 // is being cast to.
7615 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007616 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007617 Expr *LastA = CEx->getArg(NumArgs - 1);
7618 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007619 if (isa<ImplicitCastExpr>(LastA) &&
7620 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007621 // Warn on this floating-point to bool conversion
7622 DiagnoseImpCast(S, E, T, CC,
7623 diag::warn_impcast_floating_point_to_bool);
7624 }
7625 }
7626 }
John McCall263a48b2010-01-04 23:31:57 +00007627 return;
7628 }
7629
Richard Trieu5b993502014-10-15 03:42:06 +00007630 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007631
David Blaikie9366d2b2012-06-19 21:19:06 +00007632 if (!Source->isIntegerType() || !Target->isIntegerType())
7633 return;
7634
David Blaikie7555b6a2012-05-15 16:56:36 +00007635 // TODO: remove this early return once the false positives for constant->bool
7636 // in templates, macros, etc, are reduced or removed.
7637 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7638 return;
7639
John McCallcc7e5bf2010-05-06 08:58:33 +00007640 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007641 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007642
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007643 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007644 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007645 // TODO: this should happen for bitfield stores, too.
7646 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007647 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007648 if (S.SourceMgr.isInSystemMacro(CC))
7649 return;
7650
John McCall18a2c2c2010-11-09 22:22:12 +00007651 std::string PrettySourceValue = Value.toString(10);
7652 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007653
Ted Kremenek33ba9952011-10-22 02:37:33 +00007654 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7655 S.PDiag(diag::warn_impcast_integer_precision_constant)
7656 << PrettySourceValue << PrettyTargetValue
7657 << E->getType() << T << E->getSourceRange()
7658 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007659 return;
7660 }
7661
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007662 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7663 if (S.SourceMgr.isInSystemMacro(CC))
7664 return;
7665
David Blaikie9455da02012-04-12 22:40:54 +00007666 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007667 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7668 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007669 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007670 }
7671
Richard Trieudcb55572016-01-29 23:51:16 +00007672 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7673 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7674 // Warn when doing a signed to signed conversion, warn if the positive
7675 // source value is exactly the width of the target type, which will
7676 // cause a negative value to be stored.
7677
7678 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007679 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7680 !S.SourceMgr.isInSystemMacro(CC)) {
7681 if (isSameWidthConstantConversion(S, E, T, CC)) {
7682 std::string PrettySourceValue = Value.toString(10);
7683 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007684
Richard Trieufc404c72016-02-05 23:02:38 +00007685 S.DiagRuntimeBehavior(
7686 E->getExprLoc(), E,
7687 S.PDiag(diag::warn_impcast_integer_precision_constant)
7688 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7689 << E->getSourceRange() << clang::SourceRange(CC));
7690 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007691 }
7692 }
Richard Trieufc404c72016-02-05 23:02:38 +00007693
Richard Trieudcb55572016-01-29 23:51:16 +00007694 // Fall through for non-constants to give a sign conversion warning.
7695 }
7696
John McCallcc7e5bf2010-05-06 08:58:33 +00007697 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7698 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7699 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007700 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007701 return;
7702
John McCallcc7e5bf2010-05-06 08:58:33 +00007703 unsigned DiagID = diag::warn_impcast_integer_sign;
7704
7705 // Traditionally, gcc has warned about this under -Wsign-compare.
7706 // We also want to warn about it in -Wconversion.
7707 // So if -Wconversion is off, use a completely identical diagnostic
7708 // in the sign-compare group.
7709 // The conditional-checking code will
7710 if (ICContext) {
7711 DiagID = diag::warn_impcast_integer_sign_conditional;
7712 *ICContext = true;
7713 }
7714
John McCallacf0ee52010-10-08 02:01:28 +00007715 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007716 }
7717
Douglas Gregora78f1932011-02-22 02:45:07 +00007718 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007719 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7720 // type, to give us better diagnostics.
7721 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007722 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007723 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7724 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7725 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7726 SourceType = S.Context.getTypeDeclType(Enum);
7727 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7728 }
7729 }
7730
Douglas Gregora78f1932011-02-22 02:45:07 +00007731 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7732 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007733 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7734 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007735 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007736 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007737 return;
7738
Douglas Gregor364f7db2011-03-12 00:14:31 +00007739 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007740 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007741 }
John McCall263a48b2010-01-04 23:31:57 +00007742}
7743
David Blaikie18e9ac72012-05-15 21:57:38 +00007744void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7745 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007746
7747void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007748 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007749 E = E->IgnoreParenImpCasts();
7750
7751 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007752 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007753
John McCallacf0ee52010-10-08 02:01:28 +00007754 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007755 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007756 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007757}
7758
David Blaikie18e9ac72012-05-15 21:57:38 +00007759void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7760 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007761 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007762
7763 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007764 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7765 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007766
7767 // If -Wconversion would have warned about either of the candidates
7768 // for a signedness conversion to the context type...
7769 if (!Suspicious) return;
7770
7771 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007772 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007773 return;
7774
John McCallcc7e5bf2010-05-06 08:58:33 +00007775 // ...then check whether it would have warned about either of the
7776 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007777 if (E->getType() == T) return;
7778
7779 Suspicious = false;
7780 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7781 E->getType(), CC, &Suspicious);
7782 if (!Suspicious)
7783 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007784 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007785}
7786
Richard Trieu65724892014-11-15 06:37:39 +00007787/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7788/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007789void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007790 if (S.getLangOpts().Bool)
7791 return;
7792 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7793}
7794
John McCallcc7e5bf2010-05-06 08:58:33 +00007795/// AnalyzeImplicitConversions - Find and report any interesting
7796/// implicit conversions in the given expression. There are a couple
7797/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007798void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007799 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007800 Expr *E = OrigE->IgnoreParenImpCasts();
7801
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007802 if (E->isTypeDependent() || E->isValueDependent())
7803 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007804
John McCallcc7e5bf2010-05-06 08:58:33 +00007805 // For conditional operators, we analyze the arguments as if they
7806 // were being fed directly into the output.
7807 if (isa<ConditionalOperator>(E)) {
7808 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007809 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007810 return;
7811 }
7812
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007813 // Check implicit argument conversions for function calls.
7814 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7815 CheckImplicitArgumentConversions(S, Call, CC);
7816
John McCallcc7e5bf2010-05-06 08:58:33 +00007817 // Go ahead and check any implicit conversions we might have skipped.
7818 // The non-canonical typecheck is just an optimization;
7819 // CheckImplicitConversion will filter out dead implicit conversions.
7820 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007821 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007822
7823 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007824
7825 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7826 // The bound subexpressions in a PseudoObjectExpr are not reachable
7827 // as transitive children.
7828 // FIXME: Use a more uniform representation for this.
7829 for (auto *SE : POE->semantics())
7830 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7831 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007832 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007833
John McCallcc7e5bf2010-05-06 08:58:33 +00007834 // Skip past explicit casts.
7835 if (isa<ExplicitCastExpr>(E)) {
7836 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007837 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007838 }
7839
John McCalld2a53122010-11-09 23:24:47 +00007840 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7841 // Do a somewhat different check with comparison operators.
7842 if (BO->isComparisonOp())
7843 return AnalyzeComparison(S, BO);
7844
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007845 // And with simple assignments.
7846 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007847 return AnalyzeAssignment(S, BO);
7848 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007849
7850 // These break the otherwise-useful invariant below. Fortunately,
7851 // we don't really need to recurse into them, because any internal
7852 // expressions should have been analyzed already when they were
7853 // built into statements.
7854 if (isa<StmtExpr>(E)) return;
7855
7856 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007857 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007858
7859 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007860 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007861 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007862 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007863 for (Stmt *SubStmt : E->children()) {
7864 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007865 if (!ChildExpr)
7866 continue;
7867
Richard Trieu955231d2014-01-25 01:10:35 +00007868 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007869 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007870 // Ignore checking string literals that are in logical and operators.
7871 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007872 continue;
7873 AnalyzeImplicitConversions(S, ChildExpr, CC);
7874 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007875
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007876 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007877 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7878 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007879 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007880
7881 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7882 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007883 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007884 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007885
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007886 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7887 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007888 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007889}
7890
7891} // end anonymous namespace
7892
Richard Trieuc1888e02014-06-28 23:25:37 +00007893// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7894// Returns true when emitting a warning about taking the address of a reference.
7895static bool CheckForReference(Sema &SemaRef, const Expr *E,
7896 PartialDiagnostic PD) {
7897 E = E->IgnoreParenImpCasts();
7898
7899 const FunctionDecl *FD = nullptr;
7900
7901 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7902 if (!DRE->getDecl()->getType()->isReferenceType())
7903 return false;
7904 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7905 if (!M->getMemberDecl()->getType()->isReferenceType())
7906 return false;
7907 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007908 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007909 return false;
7910 FD = Call->getDirectCallee();
7911 } else {
7912 return false;
7913 }
7914
7915 SemaRef.Diag(E->getExprLoc(), PD);
7916
7917 // If possible, point to location of function.
7918 if (FD) {
7919 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7920 }
7921
7922 return true;
7923}
7924
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007925// Returns true if the SourceLocation is expanded from any macro body.
7926// Returns false if the SourceLocation is invalid, is from not in a macro
7927// expansion, or is from expanded from a top-level macro argument.
7928static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7929 if (Loc.isInvalid())
7930 return false;
7931
7932 while (Loc.isMacroID()) {
7933 if (SM.isMacroBodyExpansion(Loc))
7934 return true;
7935 Loc = SM.getImmediateMacroCallerLoc(Loc);
7936 }
7937
7938 return false;
7939}
7940
Richard Trieu3bb8b562014-02-26 02:36:06 +00007941/// \brief Diagnose pointers that are always non-null.
7942/// \param E the expression containing the pointer
7943/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7944/// compared to a null pointer
7945/// \param IsEqual True when the comparison is equal to a null pointer
7946/// \param Range Extra SourceRange to highlight in the diagnostic
7947void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7948 Expr::NullPointerConstantKind NullKind,
7949 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007950 if (!E)
7951 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007952
7953 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007954 if (E->getExprLoc().isMacroID()) {
7955 const SourceManager &SM = getSourceManager();
7956 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7957 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007958 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007959 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007960 E = E->IgnoreImpCasts();
7961
7962 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7963
Richard Trieuf7432752014-06-06 21:39:26 +00007964 if (isa<CXXThisExpr>(E)) {
7965 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7966 : diag::warn_this_bool_conversion;
7967 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7968 return;
7969 }
7970
Richard Trieu3bb8b562014-02-26 02:36:06 +00007971 bool IsAddressOf = false;
7972
7973 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7974 if (UO->getOpcode() != UO_AddrOf)
7975 return;
7976 IsAddressOf = true;
7977 E = UO->getSubExpr();
7978 }
7979
Richard Trieuc1888e02014-06-28 23:25:37 +00007980 if (IsAddressOf) {
7981 unsigned DiagID = IsCompare
7982 ? diag::warn_address_of_reference_null_compare
7983 : diag::warn_address_of_reference_bool_conversion;
7984 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7985 << IsEqual;
7986 if (CheckForReference(*this, E, PD)) {
7987 return;
7988 }
7989 }
7990
George Burgess IV850269a2015-12-08 22:02:00 +00007991 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7992 std::string Str;
7993 llvm::raw_string_ostream S(Str);
7994 E->printPretty(S, nullptr, getPrintingPolicy());
7995 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7996 : diag::warn_cast_nonnull_to_bool;
7997 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7998 << E->getSourceRange() << Range << IsEqual;
7999 };
8000
8001 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8002 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8003 if (auto *Callee = Call->getDirectCallee()) {
8004 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8005 ComplainAboutNonnullParamOrCall(false);
8006 return;
8007 }
8008 }
8009 }
8010
Richard Trieu3bb8b562014-02-26 02:36:06 +00008011 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00008012 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008013 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8014 D = R->getDecl();
8015 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8016 D = M->getMemberDecl();
8017 }
8018
8019 // Weak Decls can be null.
8020 if (!D || D->isWeak())
8021 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008022
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008023 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008024 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8025 if (getCurFunction() &&
8026 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8027 if (PV->hasAttr<NonNullAttr>()) {
8028 ComplainAboutNonnullParamOrCall(true);
8029 return;
8030 }
8031
8032 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8033 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8034 assert(ParamIter != FD->param_end());
8035 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8036
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008037 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8038 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008039 ComplainAboutNonnullParamOrCall(true);
8040 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008041 }
George Burgess IV850269a2015-12-08 22:02:00 +00008042
8043 for (unsigned ArgNo : NonNull->args()) {
8044 if (ArgNo == ParamNo) {
8045 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008046 return;
8047 }
George Burgess IV850269a2015-12-08 22:02:00 +00008048 }
8049 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008050 }
8051 }
George Burgess IV850269a2015-12-08 22:02:00 +00008052 }
8053
Richard Trieu3bb8b562014-02-26 02:36:06 +00008054 QualType T = D->getType();
8055 const bool IsArray = T->isArrayType();
8056 const bool IsFunction = T->isFunctionType();
8057
Richard Trieuc1888e02014-06-28 23:25:37 +00008058 // Address of function is used to silence the function warning.
8059 if (IsAddressOf && IsFunction) {
8060 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008061 }
8062
8063 // Found nothing.
8064 if (!IsAddressOf && !IsFunction && !IsArray)
8065 return;
8066
8067 // Pretty print the expression for the diagnostic.
8068 std::string Str;
8069 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008070 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008071
8072 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8073 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008074 enum {
8075 AddressOf,
8076 FunctionPointer,
8077 ArrayPointer
8078 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008079 if (IsAddressOf)
8080 DiagType = AddressOf;
8081 else if (IsFunction)
8082 DiagType = FunctionPointer;
8083 else if (IsArray)
8084 DiagType = ArrayPointer;
8085 else
8086 llvm_unreachable("Could not determine diagnostic.");
8087 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8088 << Range << IsEqual;
8089
8090 if (!IsFunction)
8091 return;
8092
8093 // Suggest '&' to silence the function warning.
8094 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8095 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8096
8097 // Check to see if '()' fixit should be emitted.
8098 QualType ReturnType;
8099 UnresolvedSet<4> NonTemplateOverloads;
8100 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8101 if (ReturnType.isNull())
8102 return;
8103
8104 if (IsCompare) {
8105 // There are two cases here. If there is null constant, the only suggest
8106 // for a pointer return type. If the null is 0, then suggest if the return
8107 // type is a pointer or an integer type.
8108 if (!ReturnType->isPointerType()) {
8109 if (NullKind == Expr::NPCK_ZeroExpression ||
8110 NullKind == Expr::NPCK_ZeroLiteral) {
8111 if (!ReturnType->isIntegerType())
8112 return;
8113 } else {
8114 return;
8115 }
8116 }
8117 } else { // !IsCompare
8118 // For function to bool, only suggest if the function pointer has bool
8119 // return type.
8120 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8121 return;
8122 }
8123 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008124 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008125}
8126
John McCallcc7e5bf2010-05-06 08:58:33 +00008127/// Diagnoses "dangerous" implicit conversions within the given
8128/// expression (which is a full expression). Implements -Wconversion
8129/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008130///
8131/// \param CC the "context" location of the implicit conversion, i.e.
8132/// the most location of the syntactic entity requiring the implicit
8133/// conversion
8134void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008135 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008136 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008137 return;
8138
8139 // Don't diagnose for value- or type-dependent expressions.
8140 if (E->isTypeDependent() || E->isValueDependent())
8141 return;
8142
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008143 // Check for array bounds violations in cases where the check isn't triggered
8144 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8145 // ArraySubscriptExpr is on the RHS of a variable initialization.
8146 CheckArrayAccess(E);
8147
John McCallacf0ee52010-10-08 02:01:28 +00008148 // This is not the right CC for (e.g.) a variable initialization.
8149 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008150}
8151
Richard Trieu65724892014-11-15 06:37:39 +00008152/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8153/// Input argument E is a logical expression.
8154void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8155 ::CheckBoolLikeConversion(*this, E, CC);
8156}
8157
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008158/// Diagnose when expression is an integer constant expression and its evaluation
8159/// results in integer overflow
8160void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008161 // Use a work list to deal with nested struct initializers.
8162 SmallVector<Expr *, 2> Exprs(1, E);
8163
8164 do {
8165 Expr *E = Exprs.pop_back_val();
8166
8167 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8168 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8169 continue;
8170 }
8171
8172 if (auto InitList = dyn_cast<InitListExpr>(E))
8173 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8174 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008175}
8176
Richard Smithc406cb72013-01-17 01:17:56 +00008177namespace {
8178/// \brief Visitor for expressions which looks for unsequenced operations on the
8179/// same object.
8180class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008181 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8182
Richard Smithc406cb72013-01-17 01:17:56 +00008183 /// \brief A tree of sequenced regions within an expression. Two regions are
8184 /// unsequenced if one is an ancestor or a descendent of the other. When we
8185 /// finish processing an expression with sequencing, such as a comma
8186 /// expression, we fold its tree nodes into its parent, since they are
8187 /// unsequenced with respect to nodes we will visit later.
8188 class SequenceTree {
8189 struct Value {
8190 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8191 unsigned Parent : 31;
8192 bool Merged : 1;
8193 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008194 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008195
8196 public:
8197 /// \brief A region within an expression which may be sequenced with respect
8198 /// to some other region.
8199 class Seq {
8200 explicit Seq(unsigned N) : Index(N) {}
8201 unsigned Index;
8202 friend class SequenceTree;
8203 public:
8204 Seq() : Index(0) {}
8205 };
8206
8207 SequenceTree() { Values.push_back(Value(0)); }
8208 Seq root() const { return Seq(0); }
8209
8210 /// \brief Create a new sequence of operations, which is an unsequenced
8211 /// subset of \p Parent. This sequence of operations is sequenced with
8212 /// respect to other children of \p Parent.
8213 Seq allocate(Seq Parent) {
8214 Values.push_back(Value(Parent.Index));
8215 return Seq(Values.size() - 1);
8216 }
8217
8218 /// \brief Merge a sequence of operations into its parent.
8219 void merge(Seq S) {
8220 Values[S.Index].Merged = true;
8221 }
8222
8223 /// \brief Determine whether two operations are unsequenced. This operation
8224 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8225 /// should have been merged into its parent as appropriate.
8226 bool isUnsequenced(Seq Cur, Seq Old) {
8227 unsigned C = representative(Cur.Index);
8228 unsigned Target = representative(Old.Index);
8229 while (C >= Target) {
8230 if (C == Target)
8231 return true;
8232 C = Values[C].Parent;
8233 }
8234 return false;
8235 }
8236
8237 private:
8238 /// \brief Pick a representative for a sequence.
8239 unsigned representative(unsigned K) {
8240 if (Values[K].Merged)
8241 // Perform path compression as we go.
8242 return Values[K].Parent = representative(Values[K].Parent);
8243 return K;
8244 }
8245 };
8246
8247 /// An object for which we can track unsequenced uses.
8248 typedef NamedDecl *Object;
8249
8250 /// Different flavors of object usage which we track. We only track the
8251 /// least-sequenced usage of each kind.
8252 enum UsageKind {
8253 /// A read of an object. Multiple unsequenced reads are OK.
8254 UK_Use,
8255 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008256 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008257 UK_ModAsValue,
8258 /// A modification of an object which is not sequenced before the value
8259 /// computation of the expression, such as n++.
8260 UK_ModAsSideEffect,
8261
8262 UK_Count = UK_ModAsSideEffect + 1
8263 };
8264
8265 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008266 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008267 Expr *Use;
8268 SequenceTree::Seq Seq;
8269 };
8270
8271 struct UsageInfo {
8272 UsageInfo() : Diagnosed(false) {}
8273 Usage Uses[UK_Count];
8274 /// Have we issued a diagnostic for this variable already?
8275 bool Diagnosed;
8276 };
8277 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8278
8279 Sema &SemaRef;
8280 /// Sequenced regions within the expression.
8281 SequenceTree Tree;
8282 /// Declaration modifications and references which we have seen.
8283 UsageInfoMap UsageMap;
8284 /// The region we are currently within.
8285 SequenceTree::Seq Region;
8286 /// Filled in with declarations which were modified as a side-effect
8287 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008288 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008289 /// Expressions to check later. We defer checking these to reduce
8290 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008291 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008292
8293 /// RAII object wrapping the visitation of a sequenced subexpression of an
8294 /// expression. At the end of this process, the side-effects of the evaluation
8295 /// become sequenced with respect to the value computation of the result, so
8296 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8297 /// UK_ModAsValue.
8298 struct SequencedSubexpression {
8299 SequencedSubexpression(SequenceChecker &Self)
8300 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8301 Self.ModAsSideEffect = &ModAsSideEffect;
8302 }
8303 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008304 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8305 MI != ME; ++MI) {
8306 UsageInfo &U = Self.UsageMap[MI->first];
8307 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8308 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8309 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008310 }
8311 Self.ModAsSideEffect = OldModAsSideEffect;
8312 }
8313
8314 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008315 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8316 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008317 };
8318
Richard Smith40238f02013-06-20 22:21:56 +00008319 /// RAII object wrapping the visitation of a subexpression which we might
8320 /// choose to evaluate as a constant. If any subexpression is evaluated and
8321 /// found to be non-constant, this allows us to suppress the evaluation of
8322 /// the outer expression.
8323 class EvaluationTracker {
8324 public:
8325 EvaluationTracker(SequenceChecker &Self)
8326 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8327 Self.EvalTracker = this;
8328 }
8329 ~EvaluationTracker() {
8330 Self.EvalTracker = Prev;
8331 if (Prev)
8332 Prev->EvalOK &= EvalOK;
8333 }
8334
8335 bool evaluate(const Expr *E, bool &Result) {
8336 if (!EvalOK || E->isValueDependent())
8337 return false;
8338 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8339 return EvalOK;
8340 }
8341
8342 private:
8343 SequenceChecker &Self;
8344 EvaluationTracker *Prev;
8345 bool EvalOK;
8346 } *EvalTracker;
8347
Richard Smithc406cb72013-01-17 01:17:56 +00008348 /// \brief Find the object which is produced by the specified expression,
8349 /// if any.
8350 Object getObject(Expr *E, bool Mod) const {
8351 E = E->IgnoreParenCasts();
8352 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8353 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8354 return getObject(UO->getSubExpr(), Mod);
8355 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8356 if (BO->getOpcode() == BO_Comma)
8357 return getObject(BO->getRHS(), Mod);
8358 if (Mod && BO->isAssignmentOp())
8359 return getObject(BO->getLHS(), Mod);
8360 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8361 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8362 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8363 return ME->getMemberDecl();
8364 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8365 // FIXME: If this is a reference, map through to its value.
8366 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008367 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008368 }
8369
8370 /// \brief Note that an object was modified or used by an expression.
8371 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8372 Usage &U = UI.Uses[UK];
8373 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8374 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8375 ModAsSideEffect->push_back(std::make_pair(O, U));
8376 U.Use = Ref;
8377 U.Seq = Region;
8378 }
8379 }
8380 /// \brief Check whether a modification or use conflicts with a prior usage.
8381 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8382 bool IsModMod) {
8383 if (UI.Diagnosed)
8384 return;
8385
8386 const Usage &U = UI.Uses[OtherKind];
8387 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8388 return;
8389
8390 Expr *Mod = U.Use;
8391 Expr *ModOrUse = Ref;
8392 if (OtherKind == UK_Use)
8393 std::swap(Mod, ModOrUse);
8394
8395 SemaRef.Diag(Mod->getExprLoc(),
8396 IsModMod ? diag::warn_unsequenced_mod_mod
8397 : diag::warn_unsequenced_mod_use)
8398 << O << SourceRange(ModOrUse->getExprLoc());
8399 UI.Diagnosed = true;
8400 }
8401
8402 void notePreUse(Object O, Expr *Use) {
8403 UsageInfo &U = UsageMap[O];
8404 // Uses conflict with other modifications.
8405 checkUsage(O, U, Use, UK_ModAsValue, false);
8406 }
8407 void notePostUse(Object O, Expr *Use) {
8408 UsageInfo &U = UsageMap[O];
8409 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8410 addUsage(U, O, Use, UK_Use);
8411 }
8412
8413 void notePreMod(Object O, Expr *Mod) {
8414 UsageInfo &U = UsageMap[O];
8415 // Modifications conflict with other modifications and with uses.
8416 checkUsage(O, U, Mod, UK_ModAsValue, true);
8417 checkUsage(O, U, Mod, UK_Use, false);
8418 }
8419 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8420 UsageInfo &U = UsageMap[O];
8421 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8422 addUsage(U, O, Use, UK);
8423 }
8424
8425public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008426 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008427 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8428 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008429 Visit(E);
8430 }
8431
8432 void VisitStmt(Stmt *S) {
8433 // Skip all statements which aren't expressions for now.
8434 }
8435
8436 void VisitExpr(Expr *E) {
8437 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008438 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008439 }
8440
8441 void VisitCastExpr(CastExpr *E) {
8442 Object O = Object();
8443 if (E->getCastKind() == CK_LValueToRValue)
8444 O = getObject(E->getSubExpr(), false);
8445
8446 if (O)
8447 notePreUse(O, E);
8448 VisitExpr(E);
8449 if (O)
8450 notePostUse(O, E);
8451 }
8452
8453 void VisitBinComma(BinaryOperator *BO) {
8454 // C++11 [expr.comma]p1:
8455 // Every value computation and side effect associated with the left
8456 // expression is sequenced before every value computation and side
8457 // effect associated with the right expression.
8458 SequenceTree::Seq LHS = Tree.allocate(Region);
8459 SequenceTree::Seq RHS = Tree.allocate(Region);
8460 SequenceTree::Seq OldRegion = Region;
8461
8462 {
8463 SequencedSubexpression SeqLHS(*this);
8464 Region = LHS;
8465 Visit(BO->getLHS());
8466 }
8467
8468 Region = RHS;
8469 Visit(BO->getRHS());
8470
8471 Region = OldRegion;
8472
8473 // Forget that LHS and RHS are sequenced. They are both unsequenced
8474 // with respect to other stuff.
8475 Tree.merge(LHS);
8476 Tree.merge(RHS);
8477 }
8478
8479 void VisitBinAssign(BinaryOperator *BO) {
8480 // The modification is sequenced after the value computation of the LHS
8481 // and RHS, so check it before inspecting the operands and update the
8482 // map afterwards.
8483 Object O = getObject(BO->getLHS(), true);
8484 if (!O)
8485 return VisitExpr(BO);
8486
8487 notePreMod(O, BO);
8488
8489 // C++11 [expr.ass]p7:
8490 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8491 // only once.
8492 //
8493 // Therefore, for a compound assignment operator, O is considered used
8494 // everywhere except within the evaluation of E1 itself.
8495 if (isa<CompoundAssignOperator>(BO))
8496 notePreUse(O, BO);
8497
8498 Visit(BO->getLHS());
8499
8500 if (isa<CompoundAssignOperator>(BO))
8501 notePostUse(O, BO);
8502
8503 Visit(BO->getRHS());
8504
Richard Smith83e37bee2013-06-26 23:16:51 +00008505 // C++11 [expr.ass]p1:
8506 // the assignment is sequenced [...] before the value computation of the
8507 // assignment expression.
8508 // C11 6.5.16/3 has no such rule.
8509 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8510 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008511 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008512
Richard Smithc406cb72013-01-17 01:17:56 +00008513 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8514 VisitBinAssign(CAO);
8515 }
8516
8517 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8518 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8519 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8520 Object O = getObject(UO->getSubExpr(), true);
8521 if (!O)
8522 return VisitExpr(UO);
8523
8524 notePreMod(O, UO);
8525 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008526 // C++11 [expr.pre.incr]p1:
8527 // the expression ++x is equivalent to x+=1
8528 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8529 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008530 }
8531
8532 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8533 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8534 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8535 Object O = getObject(UO->getSubExpr(), true);
8536 if (!O)
8537 return VisitExpr(UO);
8538
8539 notePreMod(O, UO);
8540 Visit(UO->getSubExpr());
8541 notePostMod(O, UO, UK_ModAsSideEffect);
8542 }
8543
8544 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8545 void VisitBinLOr(BinaryOperator *BO) {
8546 // The side-effects of the LHS of an '&&' are sequenced before the
8547 // value computation of the RHS, and hence before the value computation
8548 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8549 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008550 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008551 {
8552 SequencedSubexpression Sequenced(*this);
8553 Visit(BO->getLHS());
8554 }
8555
8556 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008557 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008558 if (!Result)
8559 Visit(BO->getRHS());
8560 } else {
8561 // Check for unsequenced operations in the RHS, treating it as an
8562 // entirely separate evaluation.
8563 //
8564 // FIXME: If there are operations in the RHS which are unsequenced
8565 // with respect to operations outside the RHS, and those operations
8566 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008567 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008568 }
Richard Smithc406cb72013-01-17 01:17:56 +00008569 }
8570 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008571 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008572 {
8573 SequencedSubexpression Sequenced(*this);
8574 Visit(BO->getLHS());
8575 }
8576
8577 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008578 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008579 if (Result)
8580 Visit(BO->getRHS());
8581 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008582 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008583 }
Richard Smithc406cb72013-01-17 01:17:56 +00008584 }
8585
8586 // Only visit the condition, unless we can be sure which subexpression will
8587 // be chosen.
8588 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008589 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008590 {
8591 SequencedSubexpression Sequenced(*this);
8592 Visit(CO->getCond());
8593 }
Richard Smithc406cb72013-01-17 01:17:56 +00008594
8595 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008596 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008597 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008598 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008599 WorkList.push_back(CO->getTrueExpr());
8600 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008601 }
Richard Smithc406cb72013-01-17 01:17:56 +00008602 }
8603
Richard Smithe3dbfe02013-06-30 10:40:20 +00008604 void VisitCallExpr(CallExpr *CE) {
8605 // C++11 [intro.execution]p15:
8606 // When calling a function [...], every value computation and side effect
8607 // associated with any argument expression, or with the postfix expression
8608 // designating the called function, is sequenced before execution of every
8609 // expression or statement in the body of the function [and thus before
8610 // the value computation of its result].
8611 SequencedSubexpression Sequenced(*this);
8612 Base::VisitCallExpr(CE);
8613
8614 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8615 }
8616
Richard Smithc406cb72013-01-17 01:17:56 +00008617 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008618 // This is a call, so all subexpressions are sequenced before the result.
8619 SequencedSubexpression Sequenced(*this);
8620
Richard Smithc406cb72013-01-17 01:17:56 +00008621 if (!CCE->isListInitialization())
8622 return VisitExpr(CCE);
8623
8624 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008625 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008626 SequenceTree::Seq Parent = Region;
8627 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8628 E = CCE->arg_end();
8629 I != E; ++I) {
8630 Region = Tree.allocate(Parent);
8631 Elts.push_back(Region);
8632 Visit(*I);
8633 }
8634
8635 // Forget that the initializers are sequenced.
8636 Region = Parent;
8637 for (unsigned I = 0; I < Elts.size(); ++I)
8638 Tree.merge(Elts[I]);
8639 }
8640
8641 void VisitInitListExpr(InitListExpr *ILE) {
8642 if (!SemaRef.getLangOpts().CPlusPlus11)
8643 return VisitExpr(ILE);
8644
8645 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008646 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008647 SequenceTree::Seq Parent = Region;
8648 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8649 Expr *E = ILE->getInit(I);
8650 if (!E) continue;
8651 Region = Tree.allocate(Parent);
8652 Elts.push_back(Region);
8653 Visit(E);
8654 }
8655
8656 // Forget that the initializers are sequenced.
8657 Region = Parent;
8658 for (unsigned I = 0; I < Elts.size(); ++I)
8659 Tree.merge(Elts[I]);
8660 }
8661};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008662} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008663
8664void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008665 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008666 WorkList.push_back(E);
8667 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008668 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008669 SequenceChecker(*this, Item, WorkList);
8670 }
Richard Smithc406cb72013-01-17 01:17:56 +00008671}
8672
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008673void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8674 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008675 CheckImplicitConversions(E, CheckLoc);
8676 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008677 if (!IsConstexpr && !E->isValueDependent())
8678 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008679}
8680
John McCall1f425642010-11-11 03:21:53 +00008681void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8682 FieldDecl *BitField,
8683 Expr *Init) {
8684 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8685}
8686
David Majnemer61a5bbf2015-04-07 22:08:51 +00008687static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8688 SourceLocation Loc) {
8689 if (!PType->isVariablyModifiedType())
8690 return;
8691 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8692 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8693 return;
8694 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008695 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8696 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8697 return;
8698 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008699 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8700 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8701 return;
8702 }
8703
8704 const ArrayType *AT = S.Context.getAsArrayType(PType);
8705 if (!AT)
8706 return;
8707
8708 if (AT->getSizeModifier() != ArrayType::Star) {
8709 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8710 return;
8711 }
8712
8713 S.Diag(Loc, diag::err_array_star_in_function_definition);
8714}
8715
Mike Stump0c2ec772010-01-21 03:59:47 +00008716/// CheckParmsForFunctionDef - Check that the parameters of the given
8717/// function are appropriate for the definition of a function. This
8718/// takes care of any checks that cannot be performed on the
8719/// declaration itself, e.g., that the types of each of the function
8720/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008721bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8722 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008723 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008724 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008725 for (; P != PEnd; ++P) {
8726 ParmVarDecl *Param = *P;
8727
Mike Stump0c2ec772010-01-21 03:59:47 +00008728 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8729 // function declarator that is part of a function definition of
8730 // that function shall not have incomplete type.
8731 //
8732 // This is also C++ [dcl.fct]p6.
8733 if (!Param->isInvalidDecl() &&
8734 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008735 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008736 Param->setInvalidDecl();
8737 HasInvalidParm = true;
8738 }
8739
8740 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8741 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008742 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008743 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008744 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008745 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008746 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008747
8748 // C99 6.7.5.3p12:
8749 // If the function declarator is not part of a definition of that
8750 // function, parameters may have incomplete type and may use the [*]
8751 // notation in their sequences of declarator specifiers to specify
8752 // variable length array types.
8753 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008754 // FIXME: This diagnostic should point the '[*]' if source-location
8755 // information is added for it.
8756 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008757
8758 // MSVC destroys objects passed by value in the callee. Therefore a
8759 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008760 // object's destructor. However, we don't perform any direct access check
8761 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008762 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8763 .getCXXABI()
8764 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008765 if (!Param->isInvalidDecl()) {
8766 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8767 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8768 if (!ClassDecl->isInvalidDecl() &&
8769 !ClassDecl->hasIrrelevantDestructor() &&
8770 !ClassDecl->isDependentContext()) {
8771 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8772 MarkFunctionReferenced(Param->getLocation(), Destructor);
8773 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8774 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008775 }
8776 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008777 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008778
8779 // Parameters with the pass_object_size attribute only need to be marked
8780 // constant at function definitions. Because we lack information about
8781 // whether we're on a declaration or definition when we're instantiating the
8782 // attribute, we need to check for constness here.
8783 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8784 if (!Param->getType().isConstQualified())
8785 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8786 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008787 }
8788
8789 return HasInvalidParm;
8790}
John McCall2b5c1b22010-08-12 21:44:57 +00008791
8792/// CheckCastAlign - Implements -Wcast-align, which warns when a
8793/// pointer cast increases the alignment requirements.
8794void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8795 // This is actually a lot of work to potentially be doing on every
8796 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008797 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008798 return;
8799
8800 // Ignore dependent types.
8801 if (T->isDependentType() || Op->getType()->isDependentType())
8802 return;
8803
8804 // Require that the destination be a pointer type.
8805 const PointerType *DestPtr = T->getAs<PointerType>();
8806 if (!DestPtr) return;
8807
8808 // If the destination has alignment 1, we're done.
8809 QualType DestPointee = DestPtr->getPointeeType();
8810 if (DestPointee->isIncompleteType()) return;
8811 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8812 if (DestAlign.isOne()) return;
8813
8814 // Require that the source be a pointer type.
8815 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8816 if (!SrcPtr) return;
8817 QualType SrcPointee = SrcPtr->getPointeeType();
8818
8819 // Whitelist casts from cv void*. We already implicitly
8820 // whitelisted casts to cv void*, since they have alignment 1.
8821 // Also whitelist casts involving incomplete types, which implicitly
8822 // includes 'void'.
8823 if (SrcPointee->isIncompleteType()) return;
8824
8825 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8826 if (SrcAlign >= DestAlign) return;
8827
8828 Diag(TRange.getBegin(), diag::warn_cast_align)
8829 << Op->getType() << T
8830 << static_cast<unsigned>(SrcAlign.getQuantity())
8831 << static_cast<unsigned>(DestAlign.getQuantity())
8832 << TRange << Op->getSourceRange();
8833}
8834
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008835static const Type* getElementType(const Expr *BaseExpr) {
8836 const Type* EltType = BaseExpr->getType().getTypePtr();
8837 if (EltType->isAnyPointerType())
8838 return EltType->getPointeeType().getTypePtr();
8839 else if (EltType->isArrayType())
8840 return EltType->getBaseElementTypeUnsafe();
8841 return EltType;
8842}
8843
Chandler Carruth28389f02011-08-05 09:10:50 +00008844/// \brief Check whether this array fits the idiom of a size-one tail padded
8845/// array member of a struct.
8846///
8847/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8848/// commonly used to emulate flexible arrays in C89 code.
8849static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8850 const NamedDecl *ND) {
8851 if (Size != 1 || !ND) return false;
8852
8853 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8854 if (!FD) return false;
8855
8856 // Don't consider sizes resulting from macro expansions or template argument
8857 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008858
8859 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008860 while (TInfo) {
8861 TypeLoc TL = TInfo->getTypeLoc();
8862 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008863 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8864 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008865 TInfo = TDL->getTypeSourceInfo();
8866 continue;
8867 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008868 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8869 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008870 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8871 return false;
8872 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008873 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008874 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008875
8876 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008877 if (!RD) return false;
8878 if (RD->isUnion()) return false;
8879 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8880 if (!CRD->isStandardLayout()) return false;
8881 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008882
Benjamin Kramer8c543672011-08-06 03:04:42 +00008883 // See if this is the last field decl in the record.
8884 const Decl *D = FD;
8885 while ((D = D->getNextDeclInContext()))
8886 if (isa<FieldDecl>(D))
8887 return false;
8888 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008889}
8890
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008891void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008892 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008893 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008894 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008895 if (IndexExpr->isValueDependent())
8896 return;
8897
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008898 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008899 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008900 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008901 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008902 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008903 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008904
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008905 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008906 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008907 return;
Richard Smith13f67182011-12-16 19:31:14 +00008908 if (IndexNegated)
8909 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008910
Craig Topperc3ec1492014-05-26 06:22:03 +00008911 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008912 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8913 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008914 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008915 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008916
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008917 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008918 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008919 if (!size.isStrictlyPositive())
8920 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008921
8922 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008923 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008924 // Make sure we're comparing apples to apples when comparing index to size
8925 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8926 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008927 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008928 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008929 if (ptrarith_typesize != array_typesize) {
8930 // There's a cast to a different size type involved
8931 uint64_t ratio = array_typesize / ptrarith_typesize;
8932 // TODO: Be smarter about handling cases where array_typesize is not a
8933 // multiple of ptrarith_typesize
8934 if (ptrarith_typesize * ratio == array_typesize)
8935 size *= llvm::APInt(size.getBitWidth(), ratio);
8936 }
8937 }
8938
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008939 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008940 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008941 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008942 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008943
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008944 // For array subscripting the index must be less than size, but for pointer
8945 // arithmetic also allow the index (offset) to be equal to size since
8946 // computing the next address after the end of the array is legal and
8947 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008948 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008949 return;
8950
8951 // Also don't warn for arrays of size 1 which are members of some
8952 // structure. These are often used to approximate flexible arrays in C89
8953 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008954 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008955 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008956
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008957 // Suppress the warning if the subscript expression (as identified by the
8958 // ']' location) and the index expression are both from macro expansions
8959 // within a system header.
8960 if (ASE) {
8961 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8962 ASE->getRBracketLoc());
8963 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8964 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8965 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008966 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008967 return;
8968 }
8969 }
8970
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008971 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008972 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008973 DiagID = diag::warn_array_index_exceeds_bounds;
8974
8975 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8976 PDiag(DiagID) << index.toString(10, true)
8977 << size.toString(10, true)
8978 << (unsigned)size.getLimitedValue(~0U)
8979 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008980 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008981 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008982 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008983 DiagID = diag::warn_ptr_arith_precedes_bounds;
8984 if (index.isNegative()) index = -index;
8985 }
8986
8987 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8988 PDiag(DiagID) << index.toString(10, true)
8989 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008990 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008991
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008992 if (!ND) {
8993 // Try harder to find a NamedDecl to point at in the note.
8994 while (const ArraySubscriptExpr *ASE =
8995 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8996 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8997 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8998 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8999 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9000 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9001 }
9002
Chandler Carruth1af88f12011-02-17 21:10:52 +00009003 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009004 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9005 PDiag(diag::note_array_index_out_of_bounds)
9006 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00009007}
9008
Ted Kremenekdf26df72011-03-01 18:41:00 +00009009void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009010 int AllowOnePastEnd = 0;
9011 while (expr) {
9012 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00009013 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009014 case Stmt::ArraySubscriptExprClass: {
9015 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009016 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009017 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009018 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009019 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009020 case Stmt::OMPArraySectionExprClass: {
9021 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9022 if (ASE->getLowerBound())
9023 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9024 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9025 return;
9026 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009027 case Stmt::UnaryOperatorClass: {
9028 // Only unwrap the * and & unary operators
9029 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9030 expr = UO->getSubExpr();
9031 switch (UO->getOpcode()) {
9032 case UO_AddrOf:
9033 AllowOnePastEnd++;
9034 break;
9035 case UO_Deref:
9036 AllowOnePastEnd--;
9037 break;
9038 default:
9039 return;
9040 }
9041 break;
9042 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009043 case Stmt::ConditionalOperatorClass: {
9044 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9045 if (const Expr *lhs = cond->getLHS())
9046 CheckArrayAccess(lhs);
9047 if (const Expr *rhs = cond->getRHS())
9048 CheckArrayAccess(rhs);
9049 return;
9050 }
9051 default:
9052 return;
9053 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009054 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009055}
John McCall31168b02011-06-15 23:02:42 +00009056
9057//===--- CHECK: Objective-C retain cycles ----------------------------------//
9058
9059namespace {
9060 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009061 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009062 VarDecl *Variable;
9063 SourceRange Range;
9064 SourceLocation Loc;
9065 bool Indirect;
9066
9067 void setLocsFrom(Expr *e) {
9068 Loc = e->getExprLoc();
9069 Range = e->getSourceRange();
9070 }
9071 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009072} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009073
9074/// Consider whether capturing the given variable can possibly lead to
9075/// a retain cycle.
9076static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009077 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009078 // lifetime. In MRR, it's captured strongly if the variable is
9079 // __block and has an appropriate type.
9080 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9081 return false;
9082
9083 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009084 if (ref)
9085 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009086 return true;
9087}
9088
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009089static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009090 while (true) {
9091 e = e->IgnoreParens();
9092 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9093 switch (cast->getCastKind()) {
9094 case CK_BitCast:
9095 case CK_LValueBitCast:
9096 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009097 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009098 e = cast->getSubExpr();
9099 continue;
9100
John McCall31168b02011-06-15 23:02:42 +00009101 default:
9102 return false;
9103 }
9104 }
9105
9106 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9107 ObjCIvarDecl *ivar = ref->getDecl();
9108 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9109 return false;
9110
9111 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009112 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009113 return false;
9114
9115 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9116 owner.Indirect = true;
9117 return true;
9118 }
9119
9120 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9121 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9122 if (!var) return false;
9123 return considerVariable(var, ref, owner);
9124 }
9125
John McCall31168b02011-06-15 23:02:42 +00009126 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9127 if (member->isArrow()) return false;
9128
9129 // Don't count this as an indirect ownership.
9130 e = member->getBase();
9131 continue;
9132 }
9133
John McCallfe96e0b2011-11-06 09:01:30 +00009134 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9135 // Only pay attention to pseudo-objects on property references.
9136 ObjCPropertyRefExpr *pre
9137 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9138 ->IgnoreParens());
9139 if (!pre) return false;
9140 if (pre->isImplicitProperty()) return false;
9141 ObjCPropertyDecl *property = pre->getExplicitProperty();
9142 if (!property->isRetaining() &&
9143 !(property->getPropertyIvarDecl() &&
9144 property->getPropertyIvarDecl()->getType()
9145 .getObjCLifetime() == Qualifiers::OCL_Strong))
9146 return false;
9147
9148 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009149 if (pre->isSuperReceiver()) {
9150 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9151 if (!owner.Variable)
9152 return false;
9153 owner.Loc = pre->getLocation();
9154 owner.Range = pre->getSourceRange();
9155 return true;
9156 }
John McCallfe96e0b2011-11-06 09:01:30 +00009157 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9158 ->getSourceExpr());
9159 continue;
9160 }
9161
John McCall31168b02011-06-15 23:02:42 +00009162 // Array ivars?
9163
9164 return false;
9165 }
9166}
9167
9168namespace {
9169 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9170 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9171 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009172 Context(Context), Variable(variable), Capturer(nullptr),
9173 VarWillBeReased(false) {}
9174 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009175 VarDecl *Variable;
9176 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009177 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009178
9179 void VisitDeclRefExpr(DeclRefExpr *ref) {
9180 if (ref->getDecl() == Variable && !Capturer)
9181 Capturer = ref;
9182 }
9183
John McCall31168b02011-06-15 23:02:42 +00009184 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9185 if (Capturer) return;
9186 Visit(ref->getBase());
9187 if (Capturer && ref->isFreeIvar())
9188 Capturer = ref;
9189 }
9190
9191 void VisitBlockExpr(BlockExpr *block) {
9192 // Look inside nested blocks
9193 if (block->getBlockDecl()->capturesVariable(Variable))
9194 Visit(block->getBlockDecl()->getBody());
9195 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009196
9197 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9198 if (Capturer) return;
9199 if (OVE->getSourceExpr())
9200 Visit(OVE->getSourceExpr());
9201 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009202 void VisitBinaryOperator(BinaryOperator *BinOp) {
9203 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9204 return;
9205 Expr *LHS = BinOp->getLHS();
9206 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9207 if (DRE->getDecl() != Variable)
9208 return;
9209 if (Expr *RHS = BinOp->getRHS()) {
9210 RHS = RHS->IgnoreParenCasts();
9211 llvm::APSInt Value;
9212 VarWillBeReased =
9213 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9214 }
9215 }
9216 }
John McCall31168b02011-06-15 23:02:42 +00009217 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009218} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009219
9220/// Check whether the given argument is a block which captures a
9221/// variable.
9222static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9223 assert(owner.Variable && owner.Loc.isValid());
9224
9225 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009226
9227 // Look through [^{...} copy] and Block_copy(^{...}).
9228 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9229 Selector Cmd = ME->getSelector();
9230 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9231 e = ME->getInstanceReceiver();
9232 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009233 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009234 e = e->IgnoreParenCasts();
9235 }
9236 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9237 if (CE->getNumArgs() == 1) {
9238 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009239 if (Fn) {
9240 const IdentifierInfo *FnI = Fn->getIdentifier();
9241 if (FnI && FnI->isStr("_Block_copy")) {
9242 e = CE->getArg(0)->IgnoreParenCasts();
9243 }
9244 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009245 }
9246 }
9247
John McCall31168b02011-06-15 23:02:42 +00009248 BlockExpr *block = dyn_cast<BlockExpr>(e);
9249 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009250 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009251
9252 FindCaptureVisitor visitor(S.Context, owner.Variable);
9253 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009254 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009255}
9256
9257static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9258 RetainCycleOwner &owner) {
9259 assert(capturer);
9260 assert(owner.Variable && owner.Loc.isValid());
9261
9262 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9263 << owner.Variable << capturer->getSourceRange();
9264 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9265 << owner.Indirect << owner.Range;
9266}
9267
9268/// Check for a keyword selector that starts with the word 'add' or
9269/// 'set'.
9270static bool isSetterLikeSelector(Selector sel) {
9271 if (sel.isUnarySelector()) return false;
9272
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009273 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009274 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009275 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009276 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009277 else if (str.startswith("add")) {
9278 // Specially whitelist 'addOperationWithBlock:'.
9279 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9280 return false;
9281 str = str.substr(3);
9282 }
John McCall31168b02011-06-15 23:02:42 +00009283 else
9284 return false;
9285
9286 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009287 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009288}
9289
Benjamin Kramer3a743452015-03-09 15:03:32 +00009290static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9291 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009292 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9293 Message->getReceiverInterface(),
9294 NSAPI::ClassId_NSMutableArray);
9295 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009296 return None;
9297 }
9298
9299 Selector Sel = Message->getSelector();
9300
9301 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9302 S.NSAPIObj->getNSArrayMethodKind(Sel);
9303 if (!MKOpt) {
9304 return None;
9305 }
9306
9307 NSAPI::NSArrayMethodKind MK = *MKOpt;
9308
9309 switch (MK) {
9310 case NSAPI::NSMutableArr_addObject:
9311 case NSAPI::NSMutableArr_insertObjectAtIndex:
9312 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9313 return 0;
9314 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9315 return 1;
9316
9317 default:
9318 return None;
9319 }
9320
9321 return None;
9322}
9323
9324static
9325Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9326 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009327 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9328 Message->getReceiverInterface(),
9329 NSAPI::ClassId_NSMutableDictionary);
9330 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009331 return None;
9332 }
9333
9334 Selector Sel = Message->getSelector();
9335
9336 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9337 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9338 if (!MKOpt) {
9339 return None;
9340 }
9341
9342 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9343
9344 switch (MK) {
9345 case NSAPI::NSMutableDict_setObjectForKey:
9346 case NSAPI::NSMutableDict_setValueForKey:
9347 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9348 return 0;
9349
9350 default:
9351 return None;
9352 }
9353
9354 return None;
9355}
9356
9357static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009358 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9359 Message->getReceiverInterface(),
9360 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009361
Alex Denisov5dfac812015-08-06 04:51:14 +00009362 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9363 Message->getReceiverInterface(),
9364 NSAPI::ClassId_NSMutableOrderedSet);
9365 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009366 return None;
9367 }
9368
9369 Selector Sel = Message->getSelector();
9370
9371 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9372 if (!MKOpt) {
9373 return None;
9374 }
9375
9376 NSAPI::NSSetMethodKind MK = *MKOpt;
9377
9378 switch (MK) {
9379 case NSAPI::NSMutableSet_addObject:
9380 case NSAPI::NSOrderedSet_setObjectAtIndex:
9381 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9382 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9383 return 0;
9384 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9385 return 1;
9386 }
9387
9388 return None;
9389}
9390
9391void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9392 if (!Message->isInstanceMessage()) {
9393 return;
9394 }
9395
9396 Optional<int> ArgOpt;
9397
9398 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9399 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9400 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9401 return;
9402 }
9403
9404 int ArgIndex = *ArgOpt;
9405
Alex Denisove1d882c2015-03-04 17:55:52 +00009406 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9407 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9408 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9409 }
9410
Alex Denisov5dfac812015-08-06 04:51:14 +00009411 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009412 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009413 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009414 Diag(Message->getSourceRange().getBegin(),
9415 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009416 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009417 }
9418 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009419 } else {
9420 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9421
9422 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9423 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9424 }
9425
9426 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9427 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9428 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9429 ValueDecl *Decl = ReceiverRE->getDecl();
9430 Diag(Message->getSourceRange().getBegin(),
9431 diag::warn_objc_circular_container)
9432 << Decl->getName() << Decl->getName();
9433 if (!ArgRE->isObjCSelfExpr()) {
9434 Diag(Decl->getLocation(),
9435 diag::note_objc_circular_container_declared_here)
9436 << Decl->getName();
9437 }
9438 }
9439 }
9440 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9441 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9442 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9443 ObjCIvarDecl *Decl = IvarRE->getDecl();
9444 Diag(Message->getSourceRange().getBegin(),
9445 diag::warn_objc_circular_container)
9446 << Decl->getName() << Decl->getName();
9447 Diag(Decl->getLocation(),
9448 diag::note_objc_circular_container_declared_here)
9449 << Decl->getName();
9450 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009451 }
9452 }
9453 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009454}
9455
John McCall31168b02011-06-15 23:02:42 +00009456/// Check a message send to see if it's likely to cause a retain cycle.
9457void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9458 // Only check instance methods whose selector looks like a setter.
9459 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9460 return;
9461
9462 // Try to find a variable that the receiver is strongly owned by.
9463 RetainCycleOwner owner;
9464 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009465 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009466 return;
9467 } else {
9468 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9469 owner.Variable = getCurMethodDecl()->getSelfDecl();
9470 owner.Loc = msg->getSuperLoc();
9471 owner.Range = msg->getSuperLoc();
9472 }
9473
9474 // Check whether the receiver is captured by any of the arguments.
9475 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9476 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9477 return diagnoseRetainCycle(*this, capturer, owner);
9478}
9479
9480/// Check a property assign to see if it's likely to cause a retain cycle.
9481void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9482 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009483 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009484 return;
9485
9486 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9487 diagnoseRetainCycle(*this, capturer, owner);
9488}
9489
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009490void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9491 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009492 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009493 return;
9494
9495 // Because we don't have an expression for the variable, we have to set the
9496 // location explicitly here.
9497 Owner.Loc = Var->getLocation();
9498 Owner.Range = Var->getSourceRange();
9499
9500 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9501 diagnoseRetainCycle(*this, Capturer, Owner);
9502}
9503
Ted Kremenek9304da92012-12-21 08:04:28 +00009504static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9505 Expr *RHS, bool isProperty) {
9506 // Check if RHS is an Objective-C object literal, which also can get
9507 // immediately zapped in a weak reference. Note that we explicitly
9508 // allow ObjCStringLiterals, since those are designed to never really die.
9509 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009510
Ted Kremenek64873352012-12-21 22:46:35 +00009511 // This enum needs to match with the 'select' in
9512 // warn_objc_arc_literal_assign (off-by-1).
9513 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9514 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9515 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009516
9517 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009518 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009519 << (isProperty ? 0 : 1)
9520 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009521
9522 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009523}
9524
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009525static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9526 Qualifiers::ObjCLifetime LT,
9527 Expr *RHS, bool isProperty) {
9528 // Strip off any implicit cast added to get to the one ARC-specific.
9529 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9530 if (cast->getCastKind() == CK_ARCConsumeObject) {
9531 S.Diag(Loc, diag::warn_arc_retained_assign)
9532 << (LT == Qualifiers::OCL_ExplicitNone)
9533 << (isProperty ? 0 : 1)
9534 << RHS->getSourceRange();
9535 return true;
9536 }
9537 RHS = cast->getSubExpr();
9538 }
9539
9540 if (LT == Qualifiers::OCL_Weak &&
9541 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9542 return true;
9543
9544 return false;
9545}
9546
Ted Kremenekb36234d2012-12-21 08:04:20 +00009547bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9548 QualType LHS, Expr *RHS) {
9549 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9550
9551 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9552 return false;
9553
9554 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9555 return true;
9556
9557 return false;
9558}
9559
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009560void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9561 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009562 QualType LHSType;
9563 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009564 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009565 ObjCPropertyRefExpr *PRE
9566 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9567 if (PRE && !PRE->isImplicitProperty()) {
9568 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9569 if (PD)
9570 LHSType = PD->getType();
9571 }
9572
9573 if (LHSType.isNull())
9574 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009575
9576 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9577
9578 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009579 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009580 getCurFunction()->markSafeWeakUse(LHS);
9581 }
9582
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009583 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9584 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009585
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009586 // FIXME. Check for other life times.
9587 if (LT != Qualifiers::OCL_None)
9588 return;
9589
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009590 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009591 if (PRE->isImplicitProperty())
9592 return;
9593 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9594 if (!PD)
9595 return;
9596
Bill Wendling44426052012-12-20 19:22:21 +00009597 unsigned Attributes = PD->getPropertyAttributes();
9598 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009599 // when 'assign' attribute was not explicitly specified
9600 // by user, ignore it and rely on property type itself
9601 // for lifetime info.
9602 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9603 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9604 LHSType->isObjCRetainableType())
9605 return;
9606
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009607 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009608 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009609 Diag(Loc, diag::warn_arc_retained_property_assign)
9610 << RHS->getSourceRange();
9611 return;
9612 }
9613 RHS = cast->getSubExpr();
9614 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009615 }
Bill Wendling44426052012-12-20 19:22:21 +00009616 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009617 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9618 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009619 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009620 }
9621}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009622
9623//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9624
9625namespace {
9626bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9627 SourceLocation StmtLoc,
9628 const NullStmt *Body) {
9629 // Do not warn if the body is a macro that expands to nothing, e.g:
9630 //
9631 // #define CALL(x)
9632 // if (condition)
9633 // CALL(0);
9634 //
9635 if (Body->hasLeadingEmptyMacro())
9636 return false;
9637
9638 // Get line numbers of statement and body.
9639 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009640 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009641 &StmtLineInvalid);
9642 if (StmtLineInvalid)
9643 return false;
9644
9645 bool BodyLineInvalid;
9646 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9647 &BodyLineInvalid);
9648 if (BodyLineInvalid)
9649 return false;
9650
9651 // Warn if null statement and body are on the same line.
9652 if (StmtLine != BodyLine)
9653 return false;
9654
9655 return true;
9656}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009657} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009658
9659void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9660 const Stmt *Body,
9661 unsigned DiagID) {
9662 // Since this is a syntactic check, don't emit diagnostic for template
9663 // instantiations, this just adds noise.
9664 if (CurrentInstantiationScope)
9665 return;
9666
9667 // The body should be a null statement.
9668 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9669 if (!NBody)
9670 return;
9671
9672 // Do the usual checks.
9673 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9674 return;
9675
9676 Diag(NBody->getSemiLoc(), DiagID);
9677 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9678}
9679
9680void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9681 const Stmt *PossibleBody) {
9682 assert(!CurrentInstantiationScope); // Ensured by caller
9683
9684 SourceLocation StmtLoc;
9685 const Stmt *Body;
9686 unsigned DiagID;
9687 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9688 StmtLoc = FS->getRParenLoc();
9689 Body = FS->getBody();
9690 DiagID = diag::warn_empty_for_body;
9691 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9692 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9693 Body = WS->getBody();
9694 DiagID = diag::warn_empty_while_body;
9695 } else
9696 return; // Neither `for' nor `while'.
9697
9698 // The body should be a null statement.
9699 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9700 if (!NBody)
9701 return;
9702
9703 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009704 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009705 return;
9706
9707 // Do the usual checks.
9708 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9709 return;
9710
9711 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9712 // noise level low, emit diagnostics only if for/while is followed by a
9713 // CompoundStmt, e.g.:
9714 // for (int i = 0; i < n; i++);
9715 // {
9716 // a(i);
9717 // }
9718 // or if for/while is followed by a statement with more indentation
9719 // than for/while itself:
9720 // for (int i = 0; i < n; i++);
9721 // a(i);
9722 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9723 if (!ProbableTypo) {
9724 bool BodyColInvalid;
9725 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9726 PossibleBody->getLocStart(),
9727 &BodyColInvalid);
9728 if (BodyColInvalid)
9729 return;
9730
9731 bool StmtColInvalid;
9732 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9733 S->getLocStart(),
9734 &StmtColInvalid);
9735 if (StmtColInvalid)
9736 return;
9737
9738 if (BodyCol > StmtCol)
9739 ProbableTypo = true;
9740 }
9741
9742 if (ProbableTypo) {
9743 Diag(NBody->getSemiLoc(), DiagID);
9744 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9745 }
9746}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009747
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009748//===--- CHECK: Warn on self move with std::move. -------------------------===//
9749
9750/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9751void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9752 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009753 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9754 return;
9755
9756 if (!ActiveTemplateInstantiations.empty())
9757 return;
9758
9759 // Strip parens and casts away.
9760 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9761 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9762
9763 // Check for a call expression
9764 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9765 if (!CE || CE->getNumArgs() != 1)
9766 return;
9767
9768 // Check for a call to std::move
9769 const FunctionDecl *FD = CE->getDirectCallee();
9770 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9771 !FD->getIdentifier()->isStr("move"))
9772 return;
9773
9774 // Get argument from std::move
9775 RHSExpr = CE->getArg(0);
9776
9777 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9778 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9779
9780 // Two DeclRefExpr's, check that the decls are the same.
9781 if (LHSDeclRef && RHSDeclRef) {
9782 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9783 return;
9784 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9785 RHSDeclRef->getDecl()->getCanonicalDecl())
9786 return;
9787
9788 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9789 << LHSExpr->getSourceRange()
9790 << RHSExpr->getSourceRange();
9791 return;
9792 }
9793
9794 // Member variables require a different approach to check for self moves.
9795 // MemberExpr's are the same if every nested MemberExpr refers to the same
9796 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9797 // the base Expr's are CXXThisExpr's.
9798 const Expr *LHSBase = LHSExpr;
9799 const Expr *RHSBase = RHSExpr;
9800 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9801 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9802 if (!LHSME || !RHSME)
9803 return;
9804
9805 while (LHSME && RHSME) {
9806 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9807 RHSME->getMemberDecl()->getCanonicalDecl())
9808 return;
9809
9810 LHSBase = LHSME->getBase();
9811 RHSBase = RHSME->getBase();
9812 LHSME = dyn_cast<MemberExpr>(LHSBase);
9813 RHSME = dyn_cast<MemberExpr>(RHSBase);
9814 }
9815
9816 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9817 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9818 if (LHSDeclRef && RHSDeclRef) {
9819 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9820 return;
9821 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9822 RHSDeclRef->getDecl()->getCanonicalDecl())
9823 return;
9824
9825 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9826 << LHSExpr->getSourceRange()
9827 << RHSExpr->getSourceRange();
9828 return;
9829 }
9830
9831 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9832 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9833 << LHSExpr->getSourceRange()
9834 << RHSExpr->getSourceRange();
9835}
9836
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009837//===--- Layout compatibility ----------------------------------------------//
9838
9839namespace {
9840
9841bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9842
9843/// \brief Check if two enumeration types are layout-compatible.
9844bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9845 // C++11 [dcl.enum] p8:
9846 // Two enumeration types are layout-compatible if they have the same
9847 // underlying type.
9848 return ED1->isComplete() && ED2->isComplete() &&
9849 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9850}
9851
9852/// \brief Check if two fields are layout-compatible.
9853bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9854 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9855 return false;
9856
9857 if (Field1->isBitField() != Field2->isBitField())
9858 return false;
9859
9860 if (Field1->isBitField()) {
9861 // Make sure that the bit-fields are the same length.
9862 unsigned Bits1 = Field1->getBitWidthValue(C);
9863 unsigned Bits2 = Field2->getBitWidthValue(C);
9864
9865 if (Bits1 != Bits2)
9866 return false;
9867 }
9868
9869 return true;
9870}
9871
9872/// \brief Check if two standard-layout structs are layout-compatible.
9873/// (C++11 [class.mem] p17)
9874bool isLayoutCompatibleStruct(ASTContext &C,
9875 RecordDecl *RD1,
9876 RecordDecl *RD2) {
9877 // If both records are C++ classes, check that base classes match.
9878 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9879 // If one of records is a CXXRecordDecl we are in C++ mode,
9880 // thus the other one is a CXXRecordDecl, too.
9881 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9882 // Check number of base classes.
9883 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9884 return false;
9885
9886 // Check the base classes.
9887 for (CXXRecordDecl::base_class_const_iterator
9888 Base1 = D1CXX->bases_begin(),
9889 BaseEnd1 = D1CXX->bases_end(),
9890 Base2 = D2CXX->bases_begin();
9891 Base1 != BaseEnd1;
9892 ++Base1, ++Base2) {
9893 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9894 return false;
9895 }
9896 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9897 // If only RD2 is a C++ class, it should have zero base classes.
9898 if (D2CXX->getNumBases() > 0)
9899 return false;
9900 }
9901
9902 // Check the fields.
9903 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9904 Field2End = RD2->field_end(),
9905 Field1 = RD1->field_begin(),
9906 Field1End = RD1->field_end();
9907 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9908 if (!isLayoutCompatible(C, *Field1, *Field2))
9909 return false;
9910 }
9911 if (Field1 != Field1End || Field2 != Field2End)
9912 return false;
9913
9914 return true;
9915}
9916
9917/// \brief Check if two standard-layout unions are layout-compatible.
9918/// (C++11 [class.mem] p18)
9919bool isLayoutCompatibleUnion(ASTContext &C,
9920 RecordDecl *RD1,
9921 RecordDecl *RD2) {
9922 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009923 for (auto *Field2 : RD2->fields())
9924 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009925
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009926 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009927 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9928 I = UnmatchedFields.begin(),
9929 E = UnmatchedFields.end();
9930
9931 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009932 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009933 bool Result = UnmatchedFields.erase(*I);
9934 (void) Result;
9935 assert(Result);
9936 break;
9937 }
9938 }
9939 if (I == E)
9940 return false;
9941 }
9942
9943 return UnmatchedFields.empty();
9944}
9945
9946bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9947 if (RD1->isUnion() != RD2->isUnion())
9948 return false;
9949
9950 if (RD1->isUnion())
9951 return isLayoutCompatibleUnion(C, RD1, RD2);
9952 else
9953 return isLayoutCompatibleStruct(C, RD1, RD2);
9954}
9955
9956/// \brief Check if two types are layout-compatible in C++11 sense.
9957bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9958 if (T1.isNull() || T2.isNull())
9959 return false;
9960
9961 // C++11 [basic.types] p11:
9962 // If two types T1 and T2 are the same type, then T1 and T2 are
9963 // layout-compatible types.
9964 if (C.hasSameType(T1, T2))
9965 return true;
9966
9967 T1 = T1.getCanonicalType().getUnqualifiedType();
9968 T2 = T2.getCanonicalType().getUnqualifiedType();
9969
9970 const Type::TypeClass TC1 = T1->getTypeClass();
9971 const Type::TypeClass TC2 = T2->getTypeClass();
9972
9973 if (TC1 != TC2)
9974 return false;
9975
9976 if (TC1 == Type::Enum) {
9977 return isLayoutCompatible(C,
9978 cast<EnumType>(T1)->getDecl(),
9979 cast<EnumType>(T2)->getDecl());
9980 } else if (TC1 == Type::Record) {
9981 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9982 return false;
9983
9984 return isLayoutCompatible(C,
9985 cast<RecordType>(T1)->getDecl(),
9986 cast<RecordType>(T2)->getDecl());
9987 }
9988
9989 return false;
9990}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009991} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009992
9993//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9994
9995namespace {
9996/// \brief Given a type tag expression find the type tag itself.
9997///
9998/// \param TypeExpr Type tag expression, as it appears in user's code.
9999///
10000/// \param VD Declaration of an identifier that appears in a type tag.
10001///
10002/// \param MagicValue Type tag magic value.
10003bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10004 const ValueDecl **VD, uint64_t *MagicValue) {
10005 while(true) {
10006 if (!TypeExpr)
10007 return false;
10008
10009 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10010
10011 switch (TypeExpr->getStmtClass()) {
10012 case Stmt::UnaryOperatorClass: {
10013 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10014 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10015 TypeExpr = UO->getSubExpr();
10016 continue;
10017 }
10018 return false;
10019 }
10020
10021 case Stmt::DeclRefExprClass: {
10022 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10023 *VD = DRE->getDecl();
10024 return true;
10025 }
10026
10027 case Stmt::IntegerLiteralClass: {
10028 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10029 llvm::APInt MagicValueAPInt = IL->getValue();
10030 if (MagicValueAPInt.getActiveBits() <= 64) {
10031 *MagicValue = MagicValueAPInt.getZExtValue();
10032 return true;
10033 } else
10034 return false;
10035 }
10036
10037 case Stmt::BinaryConditionalOperatorClass:
10038 case Stmt::ConditionalOperatorClass: {
10039 const AbstractConditionalOperator *ACO =
10040 cast<AbstractConditionalOperator>(TypeExpr);
10041 bool Result;
10042 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10043 if (Result)
10044 TypeExpr = ACO->getTrueExpr();
10045 else
10046 TypeExpr = ACO->getFalseExpr();
10047 continue;
10048 }
10049 return false;
10050 }
10051
10052 case Stmt::BinaryOperatorClass: {
10053 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10054 if (BO->getOpcode() == BO_Comma) {
10055 TypeExpr = BO->getRHS();
10056 continue;
10057 }
10058 return false;
10059 }
10060
10061 default:
10062 return false;
10063 }
10064 }
10065}
10066
10067/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10068///
10069/// \param TypeExpr Expression that specifies a type tag.
10070///
10071/// \param MagicValues Registered magic values.
10072///
10073/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10074/// kind.
10075///
10076/// \param TypeInfo Information about the corresponding C type.
10077///
10078/// \returns true if the corresponding C type was found.
10079bool GetMatchingCType(
10080 const IdentifierInfo *ArgumentKind,
10081 const Expr *TypeExpr, const ASTContext &Ctx,
10082 const llvm::DenseMap<Sema::TypeTagMagicValue,
10083 Sema::TypeTagData> *MagicValues,
10084 bool &FoundWrongKind,
10085 Sema::TypeTagData &TypeInfo) {
10086 FoundWrongKind = false;
10087
10088 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010089 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010090
10091 uint64_t MagicValue;
10092
10093 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10094 return false;
10095
10096 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010097 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010098 if (I->getArgumentKind() != ArgumentKind) {
10099 FoundWrongKind = true;
10100 return false;
10101 }
10102 TypeInfo.Type = I->getMatchingCType();
10103 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10104 TypeInfo.MustBeNull = I->getMustBeNull();
10105 return true;
10106 }
10107 return false;
10108 }
10109
10110 if (!MagicValues)
10111 return false;
10112
10113 llvm::DenseMap<Sema::TypeTagMagicValue,
10114 Sema::TypeTagData>::const_iterator I =
10115 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10116 if (I == MagicValues->end())
10117 return false;
10118
10119 TypeInfo = I->second;
10120 return true;
10121}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010122} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010123
10124void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10125 uint64_t MagicValue, QualType Type,
10126 bool LayoutCompatible,
10127 bool MustBeNull) {
10128 if (!TypeTagForDatatypeMagicValues)
10129 TypeTagForDatatypeMagicValues.reset(
10130 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10131
10132 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10133 (*TypeTagForDatatypeMagicValues)[Magic] =
10134 TypeTagData(Type, LayoutCompatible, MustBeNull);
10135}
10136
10137namespace {
10138bool IsSameCharType(QualType T1, QualType T2) {
10139 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10140 if (!BT1)
10141 return false;
10142
10143 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10144 if (!BT2)
10145 return false;
10146
10147 BuiltinType::Kind T1Kind = BT1->getKind();
10148 BuiltinType::Kind T2Kind = BT2->getKind();
10149
10150 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10151 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10152 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10153 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10154}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010155} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010156
10157void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10158 const Expr * const *ExprArgs) {
10159 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10160 bool IsPointerAttr = Attr->getIsPointer();
10161
10162 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10163 bool FoundWrongKind;
10164 TypeTagData TypeInfo;
10165 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10166 TypeTagForDatatypeMagicValues.get(),
10167 FoundWrongKind, TypeInfo)) {
10168 if (FoundWrongKind)
10169 Diag(TypeTagExpr->getExprLoc(),
10170 diag::warn_type_tag_for_datatype_wrong_kind)
10171 << TypeTagExpr->getSourceRange();
10172 return;
10173 }
10174
10175 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10176 if (IsPointerAttr) {
10177 // Skip implicit cast of pointer to `void *' (as a function argument).
10178 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010179 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010180 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010181 ArgumentExpr = ICE->getSubExpr();
10182 }
10183 QualType ArgumentType = ArgumentExpr->getType();
10184
10185 // Passing a `void*' pointer shouldn't trigger a warning.
10186 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10187 return;
10188
10189 if (TypeInfo.MustBeNull) {
10190 // Type tag with matching void type requires a null pointer.
10191 if (!ArgumentExpr->isNullPointerConstant(Context,
10192 Expr::NPC_ValueDependentIsNotNull)) {
10193 Diag(ArgumentExpr->getExprLoc(),
10194 diag::warn_type_safety_null_pointer_required)
10195 << ArgumentKind->getName()
10196 << ArgumentExpr->getSourceRange()
10197 << TypeTagExpr->getSourceRange();
10198 }
10199 return;
10200 }
10201
10202 QualType RequiredType = TypeInfo.Type;
10203 if (IsPointerAttr)
10204 RequiredType = Context.getPointerType(RequiredType);
10205
10206 bool mismatch = false;
10207 if (!TypeInfo.LayoutCompatible) {
10208 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10209
10210 // C++11 [basic.fundamental] p1:
10211 // Plain char, signed char, and unsigned char are three distinct types.
10212 //
10213 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10214 // char' depending on the current char signedness mode.
10215 if (mismatch)
10216 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10217 RequiredType->getPointeeType())) ||
10218 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10219 mismatch = false;
10220 } else
10221 if (IsPointerAttr)
10222 mismatch = !isLayoutCompatible(Context,
10223 ArgumentType->getPointeeType(),
10224 RequiredType->getPointeeType());
10225 else
10226 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10227
10228 if (mismatch)
10229 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010230 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010231 << TypeInfo.LayoutCompatible << RequiredType
10232 << ArgumentExpr->getSourceRange()
10233 << TypeTagExpr->getSourceRange();
10234}