blob: 44b3a18d707865f9cb716d7857f2782069a13609 [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) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001310 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001311 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001312 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001313 case X86::BI__builtin_ms_va_start:
1314 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001315 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001316 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001317 case X86::BI__builtin_ia32_vpermil2pd:
1318 case X86::BI__builtin_ia32_vpermil2pd256:
1319 case X86::BI__builtin_ia32_vpermil2ps:
1320 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001321 case X86::BI__builtin_ia32_cmpb128_mask:
1322 case X86::BI__builtin_ia32_cmpw128_mask:
1323 case X86::BI__builtin_ia32_cmpd128_mask:
1324 case X86::BI__builtin_ia32_cmpq128_mask:
1325 case X86::BI__builtin_ia32_cmpb256_mask:
1326 case X86::BI__builtin_ia32_cmpw256_mask:
1327 case X86::BI__builtin_ia32_cmpd256_mask:
1328 case X86::BI__builtin_ia32_cmpq256_mask:
1329 case X86::BI__builtin_ia32_cmpb512_mask:
1330 case X86::BI__builtin_ia32_cmpw512_mask:
1331 case X86::BI__builtin_ia32_cmpd512_mask:
1332 case X86::BI__builtin_ia32_cmpq512_mask:
1333 case X86::BI__builtin_ia32_ucmpb128_mask:
1334 case X86::BI__builtin_ia32_ucmpw128_mask:
1335 case X86::BI__builtin_ia32_ucmpd128_mask:
1336 case X86::BI__builtin_ia32_ucmpq128_mask:
1337 case X86::BI__builtin_ia32_ucmpb256_mask:
1338 case X86::BI__builtin_ia32_ucmpw256_mask:
1339 case X86::BI__builtin_ia32_ucmpd256_mask:
1340 case X86::BI__builtin_ia32_ucmpq256_mask:
1341 case X86::BI__builtin_ia32_ucmpb512_mask:
1342 case X86::BI__builtin_ia32_ucmpw512_mask:
1343 case X86::BI__builtin_ia32_ucmpd512_mask:
1344 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001345 case X86::BI__builtin_ia32_roundps:
1346 case X86::BI__builtin_ia32_roundpd:
1347 case X86::BI__builtin_ia32_roundps256:
1348 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1349 case X86::BI__builtin_ia32_roundss:
1350 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1351 case X86::BI__builtin_ia32_cmpps:
1352 case X86::BI__builtin_ia32_cmpss:
1353 case X86::BI__builtin_ia32_cmppd:
1354 case X86::BI__builtin_ia32_cmpsd:
1355 case X86::BI__builtin_ia32_cmpps256:
1356 case X86::BI__builtin_ia32_cmppd256:
1357 case X86::BI__builtin_ia32_cmpps512_mask:
1358 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001359 case X86::BI__builtin_ia32_vpcomub:
1360 case X86::BI__builtin_ia32_vpcomuw:
1361 case X86::BI__builtin_ia32_vpcomud:
1362 case X86::BI__builtin_ia32_vpcomuq:
1363 case X86::BI__builtin_ia32_vpcomb:
1364 case X86::BI__builtin_ia32_vpcomw:
1365 case X86::BI__builtin_ia32_vpcomd:
1366 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001367 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001368 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001369}
1370
Richard Smith55ce3522012-06-25 20:30:08 +00001371/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1372/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1373/// Returns true when the format fits the function and the FormatStringInfo has
1374/// been populated.
1375bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1376 FormatStringInfo *FSI) {
1377 FSI->HasVAListArg = Format->getFirstArg() == 0;
1378 FSI->FormatIdx = Format->getFormatIdx() - 1;
1379 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001380
Richard Smith55ce3522012-06-25 20:30:08 +00001381 // The way the format attribute works in GCC, the implicit this argument
1382 // of member functions is counted. However, it doesn't appear in our own
1383 // lists, so decrement format_idx in that case.
1384 if (IsCXXMember) {
1385 if(FSI->FormatIdx == 0)
1386 return false;
1387 --FSI->FormatIdx;
1388 if (FSI->FirstDataArg != 0)
1389 --FSI->FirstDataArg;
1390 }
1391 return true;
1392}
Mike Stump11289f42009-09-09 15:08:12 +00001393
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001394/// Checks if a the given expression evaluates to null.
1395///
1396/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001397static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001398 // If the expression has non-null type, it doesn't evaluate to null.
1399 if (auto nullability
1400 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1401 if (*nullability == NullabilityKind::NonNull)
1402 return false;
1403 }
1404
Ted Kremeneka146db32014-01-17 06:24:47 +00001405 // As a special case, transparent unions initialized with zero are
1406 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001407 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001408 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1409 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001410 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001411 if (const InitListExpr *ILE =
1412 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001413 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001414 }
1415
1416 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001417 return (!Expr->isValueDependent() &&
1418 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1419 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001420}
1421
1422static void CheckNonNullArgument(Sema &S,
1423 const Expr *ArgExpr,
1424 SourceLocation CallSiteLoc) {
1425 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001426 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1427 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001428}
1429
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001430bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1431 FormatStringInfo FSI;
1432 if ((GetFormatStringType(Format) == FST_NSString) &&
1433 getFormatStringInfo(Format, false, &FSI)) {
1434 Idx = FSI.FormatIdx;
1435 return true;
1436 }
1437 return false;
1438}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001439/// \brief Diagnose use of %s directive in an NSString which is being passed
1440/// as formatting string to formatting method.
1441static void
1442DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1443 const NamedDecl *FDecl,
1444 Expr **Args,
1445 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001446 unsigned Idx = 0;
1447 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001448 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1449 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001450 Idx = 2;
1451 Format = true;
1452 }
1453 else
1454 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1455 if (S.GetFormatNSStringIdx(I, Idx)) {
1456 Format = true;
1457 break;
1458 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001459 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001460 if (!Format || NumArgs <= Idx)
1461 return;
1462 const Expr *FormatExpr = Args[Idx];
1463 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1464 FormatExpr = CSCE->getSubExpr();
1465 const StringLiteral *FormatString;
1466 if (const ObjCStringLiteral *OSL =
1467 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1468 FormatString = OSL->getString();
1469 else
1470 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1471 if (!FormatString)
1472 return;
1473 if (S.FormatStringHasSArg(FormatString)) {
1474 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1475 << "%s" << 1 << 1;
1476 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1477 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001478 }
1479}
1480
Douglas Gregorb4866e82015-06-19 18:13:19 +00001481/// Determine whether the given type has a non-null nullability annotation.
1482static bool isNonNullType(ASTContext &ctx, QualType type) {
1483 if (auto nullability = type->getNullability(ctx))
1484 return *nullability == NullabilityKind::NonNull;
1485
1486 return false;
1487}
1488
Ted Kremenek2bc73332014-01-17 06:24:43 +00001489static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001490 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001491 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001492 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001493 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001494 assert((FDecl || Proto) && "Need a function declaration or prototype");
1495
Ted Kremenek9aedc152014-01-17 06:24:56 +00001496 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001497 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001498 if (FDecl) {
1499 // Handle the nonnull attribute on the function/method declaration itself.
1500 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1501 if (!NonNull->args_size()) {
1502 // Easy case: all pointer arguments are nonnull.
1503 for (const auto *Arg : Args)
1504 if (S.isValidPointerAttrType(Arg->getType()))
1505 CheckNonNullArgument(S, Arg, CallSiteLoc);
1506 return;
1507 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001508
Douglas Gregorb4866e82015-06-19 18:13:19 +00001509 for (unsigned Val : NonNull->args()) {
1510 if (Val >= Args.size())
1511 continue;
1512 if (NonNullArgs.empty())
1513 NonNullArgs.resize(Args.size());
1514 NonNullArgs.set(Val);
1515 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001516 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001517 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001518
Douglas Gregorb4866e82015-06-19 18:13:19 +00001519 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1520 // Handle the nonnull attribute on the parameters of the
1521 // function/method.
1522 ArrayRef<ParmVarDecl*> parms;
1523 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1524 parms = FD->parameters();
1525 else
1526 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1527
1528 unsigned ParamIndex = 0;
1529 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1530 I != E; ++I, ++ParamIndex) {
1531 const ParmVarDecl *PVD = *I;
1532 if (PVD->hasAttr<NonNullAttr>() ||
1533 isNonNullType(S.Context, PVD->getType())) {
1534 if (NonNullArgs.empty())
1535 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001536
Douglas Gregorb4866e82015-06-19 18:13:19 +00001537 NonNullArgs.set(ParamIndex);
1538 }
1539 }
1540 } else {
1541 // If we have a non-function, non-method declaration but no
1542 // function prototype, try to dig out the function prototype.
1543 if (!Proto) {
1544 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1545 QualType type = VD->getType().getNonReferenceType();
1546 if (auto pointerType = type->getAs<PointerType>())
1547 type = pointerType->getPointeeType();
1548 else if (auto blockType = type->getAs<BlockPointerType>())
1549 type = blockType->getPointeeType();
1550 // FIXME: data member pointers?
1551
1552 // Dig out the function prototype, if there is one.
1553 Proto = type->getAs<FunctionProtoType>();
1554 }
1555 }
1556
1557 // Fill in non-null argument information from the nullability
1558 // information on the parameter types (if we have them).
1559 if (Proto) {
1560 unsigned Index = 0;
1561 for (auto paramType : Proto->getParamTypes()) {
1562 if (isNonNullType(S.Context, paramType)) {
1563 if (NonNullArgs.empty())
1564 NonNullArgs.resize(Args.size());
1565
1566 NonNullArgs.set(Index);
1567 }
1568
1569 ++Index;
1570 }
1571 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001572 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001573
Douglas Gregorb4866e82015-06-19 18:13:19 +00001574 // Check for non-null arguments.
1575 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1576 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001577 if (NonNullArgs[ArgIndex])
1578 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001579 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001580}
1581
Richard Smith55ce3522012-06-25 20:30:08 +00001582/// Handles the checks for format strings, non-POD arguments to vararg
1583/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001584void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1585 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001586 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001587 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001588 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001589 if (CurContext->isDependentContext())
1590 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001591
Ted Kremenekb8176da2010-09-09 04:33:05 +00001592 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001593 llvm::SmallBitVector CheckedVarArgs;
1594 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001595 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001596 // Only create vector if there are format attributes.
1597 CheckedVarArgs.resize(Args.size());
1598
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001599 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001600 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001601 }
Richard Smithd7293d72013-08-05 18:49:43 +00001602 }
Richard Smith55ce3522012-06-25 20:30:08 +00001603
1604 // Refuse POD arguments that weren't caught by the format string
1605 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001606 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001607 unsigned NumParams = Proto ? Proto->getNumParams()
1608 : FDecl && isa<FunctionDecl>(FDecl)
1609 ? cast<FunctionDecl>(FDecl)->getNumParams()
1610 : FDecl && isa<ObjCMethodDecl>(FDecl)
1611 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1612 : 0;
1613
Alp Toker9cacbab2014-01-20 20:26:09 +00001614 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001615 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001616 if (const Expr *Arg = Args[ArgIdx]) {
1617 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1618 checkVariadicArgument(Arg, CallType);
1619 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001620 }
Richard Smithd7293d72013-08-05 18:49:43 +00001621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
Douglas Gregorb4866e82015-06-19 18:13:19 +00001623 if (FDecl || Proto) {
1624 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001625
Richard Trieu41bc0992013-06-22 00:20:41 +00001626 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001627 if (FDecl) {
1628 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1629 CheckArgumentWithTypeTag(I, Args.data());
1630 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001631 }
Richard Smith55ce3522012-06-25 20:30:08 +00001632}
1633
1634/// CheckConstructorCall - Check a constructor call for correctness and safety
1635/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001636void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1637 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001638 const FunctionProtoType *Proto,
1639 SourceLocation Loc) {
1640 VariadicCallType CallType =
1641 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001642 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1643 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001644}
1645
1646/// CheckFunctionCall - Check a direct function call for various correctness
1647/// and safety properties not strictly enforced by the C type system.
1648bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1649 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001650 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1651 isa<CXXMethodDecl>(FDecl);
1652 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1653 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001654 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1655 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001656 Expr** Args = TheCall->getArgs();
1657 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001658 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001659 // If this is a call to a member operator, hide the first argument
1660 // from checkCall.
1661 // FIXME: Our choice of AST representation here is less than ideal.
1662 ++Args;
1663 --NumArgs;
1664 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001665 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001666 IsMemberFunction, TheCall->getRParenLoc(),
1667 TheCall->getCallee()->getSourceRange(), CallType);
1668
1669 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1670 // None of the checks below are needed for functions that don't have
1671 // simple names (e.g., C++ conversion functions).
1672 if (!FnInfo)
1673 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001674
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001675 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001676 if (getLangOpts().ObjC1)
1677 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001678
Anna Zaks22122702012-01-17 00:37:07 +00001679 unsigned CMId = FDecl->getMemoryFunctionKind();
1680 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001681 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001682
Anna Zaks201d4892012-01-13 21:52:01 +00001683 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001684 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001685 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001686 else if (CMId == Builtin::BIstrncat)
1687 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001688 else
Anna Zaks22122702012-01-17 00:37:07 +00001689 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001690
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001691 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001692}
1693
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001694bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001695 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001696 VariadicCallType CallType =
1697 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001698
Douglas Gregorb4866e82015-06-19 18:13:19 +00001699 checkCall(Method, nullptr, Args,
1700 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1701 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001702
1703 return false;
1704}
1705
Richard Trieu664c4c62013-06-20 21:03:13 +00001706bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1707 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001708 QualType Ty;
1709 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001710 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001711 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001712 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001713 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001714 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001715
Douglas Gregorb4866e82015-06-19 18:13:19 +00001716 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1717 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001718 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001719
Richard Trieu664c4c62013-06-20 21:03:13 +00001720 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001721 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001722 CallType = VariadicDoesNotApply;
1723 } else if (Ty->isBlockPointerType()) {
1724 CallType = VariadicBlock;
1725 } else { // Ty->isFunctionPointerType()
1726 CallType = VariadicFunction;
1727 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001728
Douglas Gregorb4866e82015-06-19 18:13:19 +00001729 checkCall(NDecl, Proto,
1730 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1731 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001732 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001733
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001734 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001735}
1736
Richard Trieu41bc0992013-06-22 00:20:41 +00001737/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1738/// such as function pointers returned from functions.
1739bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001740 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001741 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001742 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001743 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001744 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001745 TheCall->getCallee()->getSourceRange(), CallType);
1746
1747 return false;
1748}
1749
Tim Northovere94a34c2014-03-11 10:49:14 +00001750static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1751 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1752 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1753 return false;
1754
1755 switch (Op) {
1756 case AtomicExpr::AO__c11_atomic_init:
1757 llvm_unreachable("There is no ordering argument for an init");
1758
1759 case AtomicExpr::AO__c11_atomic_load:
1760 case AtomicExpr::AO__atomic_load_n:
1761 case AtomicExpr::AO__atomic_load:
1762 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1763 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1764
1765 case AtomicExpr::AO__c11_atomic_store:
1766 case AtomicExpr::AO__atomic_store:
1767 case AtomicExpr::AO__atomic_store_n:
1768 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1769 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1770 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1771
1772 default:
1773 return true;
1774 }
1775}
1776
Richard Smithfeea8832012-04-12 05:08:17 +00001777ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1778 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001779 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1780 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001781
Richard Smithfeea8832012-04-12 05:08:17 +00001782 // All these operations take one of the following forms:
1783 enum {
1784 // C __c11_atomic_init(A *, C)
1785 Init,
1786 // C __c11_atomic_load(A *, int)
1787 Load,
1788 // void __atomic_load(A *, CP, int)
1789 Copy,
1790 // C __c11_atomic_add(A *, M, int)
1791 Arithmetic,
1792 // C __atomic_exchange_n(A *, CP, int)
1793 Xchg,
1794 // void __atomic_exchange(A *, C *, CP, int)
1795 GNUXchg,
1796 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1797 C11CmpXchg,
1798 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1799 GNUCmpXchg
1800 } Form = Init;
1801 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1802 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1803 // where:
1804 // C is an appropriate type,
1805 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1806 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1807 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1808 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001809
Gabor Horvath98bd0982015-03-16 09:59:54 +00001810 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1811 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1812 AtomicExpr::AO__atomic_load,
1813 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001814 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1815 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1816 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1817 Op == AtomicExpr::AO__atomic_store_n ||
1818 Op == AtomicExpr::AO__atomic_exchange_n ||
1819 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1820 bool IsAddSub = false;
1821
1822 switch (Op) {
1823 case AtomicExpr::AO__c11_atomic_init:
1824 Form = Init;
1825 break;
1826
1827 case AtomicExpr::AO__c11_atomic_load:
1828 case AtomicExpr::AO__atomic_load_n:
1829 Form = Load;
1830 break;
1831
1832 case AtomicExpr::AO__c11_atomic_store:
1833 case AtomicExpr::AO__atomic_load:
1834 case AtomicExpr::AO__atomic_store:
1835 case AtomicExpr::AO__atomic_store_n:
1836 Form = Copy;
1837 break;
1838
1839 case AtomicExpr::AO__c11_atomic_fetch_add:
1840 case AtomicExpr::AO__c11_atomic_fetch_sub:
1841 case AtomicExpr::AO__atomic_fetch_add:
1842 case AtomicExpr::AO__atomic_fetch_sub:
1843 case AtomicExpr::AO__atomic_add_fetch:
1844 case AtomicExpr::AO__atomic_sub_fetch:
1845 IsAddSub = true;
1846 // Fall through.
1847 case AtomicExpr::AO__c11_atomic_fetch_and:
1848 case AtomicExpr::AO__c11_atomic_fetch_or:
1849 case AtomicExpr::AO__c11_atomic_fetch_xor:
1850 case AtomicExpr::AO__atomic_fetch_and:
1851 case AtomicExpr::AO__atomic_fetch_or:
1852 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001853 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001854 case AtomicExpr::AO__atomic_and_fetch:
1855 case AtomicExpr::AO__atomic_or_fetch:
1856 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001857 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001858 Form = Arithmetic;
1859 break;
1860
1861 case AtomicExpr::AO__c11_atomic_exchange:
1862 case AtomicExpr::AO__atomic_exchange_n:
1863 Form = Xchg;
1864 break;
1865
1866 case AtomicExpr::AO__atomic_exchange:
1867 Form = GNUXchg;
1868 break;
1869
1870 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1871 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1872 Form = C11CmpXchg;
1873 break;
1874
1875 case AtomicExpr::AO__atomic_compare_exchange:
1876 case AtomicExpr::AO__atomic_compare_exchange_n:
1877 Form = GNUCmpXchg;
1878 break;
1879 }
1880
1881 // Check we have the right number of arguments.
1882 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001883 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001884 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001885 << TheCall->getCallee()->getSourceRange();
1886 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001887 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1888 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001889 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001890 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001891 << TheCall->getCallee()->getSourceRange();
1892 return ExprError();
1893 }
1894
Richard Smithfeea8832012-04-12 05:08:17 +00001895 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001896 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001897 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1898 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1899 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001900 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001901 << Ptr->getType() << Ptr->getSourceRange();
1902 return ExprError();
1903 }
1904
Richard Smithfeea8832012-04-12 05:08:17 +00001905 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1906 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1907 QualType ValType = AtomTy; // 'C'
1908 if (IsC11) {
1909 if (!AtomTy->isAtomicType()) {
1910 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1911 << Ptr->getType() << Ptr->getSourceRange();
1912 return ExprError();
1913 }
Richard Smithe00921a2012-09-15 06:09:58 +00001914 if (AtomTy.isConstQualified()) {
1915 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1916 << Ptr->getType() << Ptr->getSourceRange();
1917 return ExprError();
1918 }
Richard Smithfeea8832012-04-12 05:08:17 +00001919 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001920 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1921 if (ValType.isConstQualified()) {
1922 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1923 << Ptr->getType() << Ptr->getSourceRange();
1924 return ExprError();
1925 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001926 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001927
Richard Smithfeea8832012-04-12 05:08:17 +00001928 // For an arithmetic operation, the implied arithmetic must be well-formed.
1929 if (Form == Arithmetic) {
1930 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1931 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1932 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1933 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1934 return ExprError();
1935 }
1936 if (!IsAddSub && !ValType->isIntegerType()) {
1937 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1938 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1939 return ExprError();
1940 }
David Majnemere85cff82015-01-28 05:48:06 +00001941 if (IsC11 && ValType->isPointerType() &&
1942 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1943 diag::err_incomplete_type)) {
1944 return ExprError();
1945 }
Richard Smithfeea8832012-04-12 05:08:17 +00001946 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1947 // For __atomic_*_n operations, the value type must be a scalar integral or
1948 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001949 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001950 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1951 return ExprError();
1952 }
1953
Eli Friedmanaa769812013-09-11 03:49:34 +00001954 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1955 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001956 // For GNU atomics, require a trivially-copyable type. This is not part of
1957 // the GNU atomics specification, but we enforce it for sanity.
1958 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001959 << Ptr->getType() << Ptr->getSourceRange();
1960 return ExprError();
1961 }
1962
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001963 switch (ValType.getObjCLifetime()) {
1964 case Qualifiers::OCL_None:
1965 case Qualifiers::OCL_ExplicitNone:
1966 // okay
1967 break;
1968
1969 case Qualifiers::OCL_Weak:
1970 case Qualifiers::OCL_Strong:
1971 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001972 // FIXME: Can this happen? By this point, ValType should be known
1973 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001974 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1975 << ValType << Ptr->getSourceRange();
1976 return ExprError();
1977 }
1978
David Majnemerc6eb6502015-06-03 00:26:35 +00001979 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1980 // volatile-ness of the pointee-type inject itself into the result or the
1981 // other operands.
1982 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001983 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001984 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001985 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001986 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001987 ResultType = Context.BoolTy;
1988
Richard Smithfeea8832012-04-12 05:08:17 +00001989 // The type of a parameter passed 'by value'. In the GNU atomics, such
1990 // arguments are actually passed as pointers.
1991 QualType ByValType = ValType; // 'CP'
1992 if (!IsC11 && !IsN)
1993 ByValType = Ptr->getType();
1994
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001995 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1996 // but not the second argument. We need to manually remove possible const
1997 // qualifiers.
1998
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001999 // The first argument --- the pointer --- has a fixed type; we
2000 // deduce the types of the rest of the arguments accordingly. Walk
2001 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002002 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002003 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002004 if (i < NumVals[Form] + 1) {
2005 switch (i) {
2006 case 1:
2007 // The second argument is the non-atomic operand. For arithmetic, this
2008 // is always passed by value, and for a compare_exchange it is always
2009 // passed by address. For the rest, GNU uses by-address and C11 uses
2010 // by-value.
2011 assert(Form != Load);
2012 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2013 Ty = ValType;
2014 else if (Form == Copy || Form == Xchg)
2015 Ty = ByValType;
2016 else if (Form == Arithmetic)
2017 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002018 else {
2019 Expr *ValArg = TheCall->getArg(i);
2020 unsigned AS = 0;
2021 // Keep address space of non-atomic pointer type.
2022 if (const PointerType *PtrTy =
2023 ValArg->getType()->getAs<PointerType>()) {
2024 AS = PtrTy->getPointeeType().getAddressSpace();
2025 }
2026 Ty = Context.getPointerType(
2027 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2028 }
Richard Smithfeea8832012-04-12 05:08:17 +00002029 break;
2030 case 2:
2031 // The third argument to compare_exchange / GNU exchange is a
2032 // (pointer to a) desired value.
2033 Ty = ByValType;
2034 break;
2035 case 3:
2036 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2037 Ty = Context.BoolTy;
2038 break;
2039 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002040 } else {
2041 // The order(s) are always converted to int.
2042 Ty = Context.IntTy;
2043 }
Richard Smithfeea8832012-04-12 05:08:17 +00002044
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002045 InitializedEntity Entity =
2046 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002047 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002048 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2049 if (Arg.isInvalid())
2050 return true;
2051 TheCall->setArg(i, Arg.get());
2052 }
2053
Richard Smithfeea8832012-04-12 05:08:17 +00002054 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002055 SmallVector<Expr*, 5> SubExprs;
2056 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002057 switch (Form) {
2058 case Init:
2059 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002060 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002061 break;
2062 case Load:
2063 SubExprs.push_back(TheCall->getArg(1)); // Order
2064 break;
2065 case Copy:
2066 case Arithmetic:
2067 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002068 SubExprs.push_back(TheCall->getArg(2)); // Order
2069 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002070 break;
2071 case GNUXchg:
2072 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2073 SubExprs.push_back(TheCall->getArg(3)); // Order
2074 SubExprs.push_back(TheCall->getArg(1)); // Val1
2075 SubExprs.push_back(TheCall->getArg(2)); // Val2
2076 break;
2077 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002078 SubExprs.push_back(TheCall->getArg(3)); // Order
2079 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002080 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002081 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002082 break;
2083 case GNUCmpXchg:
2084 SubExprs.push_back(TheCall->getArg(4)); // Order
2085 SubExprs.push_back(TheCall->getArg(1)); // Val1
2086 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2087 SubExprs.push_back(TheCall->getArg(2)); // Val2
2088 SubExprs.push_back(TheCall->getArg(3)); // Weak
2089 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002090 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002091
2092 if (SubExprs.size() >= 2 && Form != Init) {
2093 llvm::APSInt Result(32);
2094 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2095 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002096 Diag(SubExprs[1]->getLocStart(),
2097 diag::warn_atomic_op_has_invalid_memory_order)
2098 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002099 }
2100
Fariborz Jahanian615de762013-05-28 17:37:39 +00002101 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2102 SubExprs, ResultType, Op,
2103 TheCall->getRParenLoc());
2104
2105 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2106 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2107 Context.AtomicUsesUnsupportedLibcall(AE))
2108 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2109 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002110
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002111 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002112}
2113
John McCall29ad95b2011-08-27 01:09:30 +00002114/// checkBuiltinArgument - Given a call to a builtin function, perform
2115/// normal type-checking on the given argument, updating the call in
2116/// place. This is useful when a builtin function requires custom
2117/// type-checking for some of its arguments but not necessarily all of
2118/// them.
2119///
2120/// Returns true on error.
2121static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2122 FunctionDecl *Fn = E->getDirectCallee();
2123 assert(Fn && "builtin call without direct callee!");
2124
2125 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2126 InitializedEntity Entity =
2127 InitializedEntity::InitializeParameter(S.Context, Param);
2128
2129 ExprResult Arg = E->getArg(0);
2130 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2131 if (Arg.isInvalid())
2132 return true;
2133
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002134 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002135 return false;
2136}
2137
Chris Lattnerdc046542009-05-08 06:58:22 +00002138/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2139/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2140/// type of its first argument. The main ActOnCallExpr routines have already
2141/// promoted the types of arguments because all of these calls are prototyped as
2142/// void(...).
2143///
2144/// This function goes through and does final semantic checking for these
2145/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002146ExprResult
2147Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002148 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002149 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2150 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2151
2152 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002153 if (TheCall->getNumArgs() < 1) {
2154 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2155 << 0 << 1 << TheCall->getNumArgs()
2156 << TheCall->getCallee()->getSourceRange();
2157 return ExprError();
2158 }
Mike Stump11289f42009-09-09 15:08:12 +00002159
Chris Lattnerdc046542009-05-08 06:58:22 +00002160 // Inspect the first argument of the atomic builtin. This should always be
2161 // a pointer type, whose element is an integral scalar or pointer type.
2162 // Because it is a pointer type, we don't have to worry about any implicit
2163 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002164 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002165 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002166 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2167 if (FirstArgResult.isInvalid())
2168 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002169 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002170 TheCall->setArg(0, FirstArg);
2171
John McCall31168b02011-06-15 23:02:42 +00002172 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2173 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002174 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2175 << FirstArg->getType() << FirstArg->getSourceRange();
2176 return ExprError();
2177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
John McCall31168b02011-06-15 23:02:42 +00002179 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002180 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002181 !ValType->isBlockPointerType()) {
2182 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2183 << FirstArg->getType() << FirstArg->getSourceRange();
2184 return ExprError();
2185 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002186
John McCall31168b02011-06-15 23:02:42 +00002187 switch (ValType.getObjCLifetime()) {
2188 case Qualifiers::OCL_None:
2189 case Qualifiers::OCL_ExplicitNone:
2190 // okay
2191 break;
2192
2193 case Qualifiers::OCL_Weak:
2194 case Qualifiers::OCL_Strong:
2195 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002196 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002197 << ValType << FirstArg->getSourceRange();
2198 return ExprError();
2199 }
2200
John McCallb50451a2011-10-05 07:41:44 +00002201 // Strip any qualifiers off ValType.
2202 ValType = ValType.getUnqualifiedType();
2203
Chandler Carruth3973af72010-07-18 20:54:12 +00002204 // The majority of builtins return a value, but a few have special return
2205 // types, so allow them to override appropriately below.
2206 QualType ResultType = ValType;
2207
Chris Lattnerdc046542009-05-08 06:58:22 +00002208 // We need to figure out which concrete builtin this maps onto. For example,
2209 // __sync_fetch_and_add with a 2 byte object turns into
2210 // __sync_fetch_and_add_2.
2211#define BUILTIN_ROW(x) \
2212 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2213 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002214
Chris Lattnerdc046542009-05-08 06:58:22 +00002215 static const unsigned BuiltinIndices[][5] = {
2216 BUILTIN_ROW(__sync_fetch_and_add),
2217 BUILTIN_ROW(__sync_fetch_and_sub),
2218 BUILTIN_ROW(__sync_fetch_and_or),
2219 BUILTIN_ROW(__sync_fetch_and_and),
2220 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002221 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattnerdc046542009-05-08 06:58:22 +00002223 BUILTIN_ROW(__sync_add_and_fetch),
2224 BUILTIN_ROW(__sync_sub_and_fetch),
2225 BUILTIN_ROW(__sync_and_and_fetch),
2226 BUILTIN_ROW(__sync_or_and_fetch),
2227 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002228 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002229
Chris Lattnerdc046542009-05-08 06:58:22 +00002230 BUILTIN_ROW(__sync_val_compare_and_swap),
2231 BUILTIN_ROW(__sync_bool_compare_and_swap),
2232 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002233 BUILTIN_ROW(__sync_lock_release),
2234 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002235 };
Mike Stump11289f42009-09-09 15:08:12 +00002236#undef BUILTIN_ROW
2237
Chris Lattnerdc046542009-05-08 06:58:22 +00002238 // Determine the index of the size.
2239 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002240 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002241 case 1: SizeIndex = 0; break;
2242 case 2: SizeIndex = 1; break;
2243 case 4: SizeIndex = 2; break;
2244 case 8: SizeIndex = 3; break;
2245 case 16: SizeIndex = 4; break;
2246 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002247 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2248 << FirstArg->getType() << FirstArg->getSourceRange();
2249 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002250 }
Mike Stump11289f42009-09-09 15:08:12 +00002251
Chris Lattnerdc046542009-05-08 06:58:22 +00002252 // Each of these builtins has one pointer argument, followed by some number of
2253 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2254 // that we ignore. Find out which row of BuiltinIndices to read from as well
2255 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002256 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002257 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002258 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002259 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002260 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002261 case Builtin::BI__sync_fetch_and_add:
2262 case Builtin::BI__sync_fetch_and_add_1:
2263 case Builtin::BI__sync_fetch_and_add_2:
2264 case Builtin::BI__sync_fetch_and_add_4:
2265 case Builtin::BI__sync_fetch_and_add_8:
2266 case Builtin::BI__sync_fetch_and_add_16:
2267 BuiltinIndex = 0;
2268 break;
2269
2270 case Builtin::BI__sync_fetch_and_sub:
2271 case Builtin::BI__sync_fetch_and_sub_1:
2272 case Builtin::BI__sync_fetch_and_sub_2:
2273 case Builtin::BI__sync_fetch_and_sub_4:
2274 case Builtin::BI__sync_fetch_and_sub_8:
2275 case Builtin::BI__sync_fetch_and_sub_16:
2276 BuiltinIndex = 1;
2277 break;
2278
2279 case Builtin::BI__sync_fetch_and_or:
2280 case Builtin::BI__sync_fetch_and_or_1:
2281 case Builtin::BI__sync_fetch_and_or_2:
2282 case Builtin::BI__sync_fetch_and_or_4:
2283 case Builtin::BI__sync_fetch_and_or_8:
2284 case Builtin::BI__sync_fetch_and_or_16:
2285 BuiltinIndex = 2;
2286 break;
2287
2288 case Builtin::BI__sync_fetch_and_and:
2289 case Builtin::BI__sync_fetch_and_and_1:
2290 case Builtin::BI__sync_fetch_and_and_2:
2291 case Builtin::BI__sync_fetch_and_and_4:
2292 case Builtin::BI__sync_fetch_and_and_8:
2293 case Builtin::BI__sync_fetch_and_and_16:
2294 BuiltinIndex = 3;
2295 break;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Douglas Gregor73722482011-11-28 16:30:08 +00002297 case Builtin::BI__sync_fetch_and_xor:
2298 case Builtin::BI__sync_fetch_and_xor_1:
2299 case Builtin::BI__sync_fetch_and_xor_2:
2300 case Builtin::BI__sync_fetch_and_xor_4:
2301 case Builtin::BI__sync_fetch_and_xor_8:
2302 case Builtin::BI__sync_fetch_and_xor_16:
2303 BuiltinIndex = 4;
2304 break;
2305
Hal Finkeld2208b52014-10-02 20:53:50 +00002306 case Builtin::BI__sync_fetch_and_nand:
2307 case Builtin::BI__sync_fetch_and_nand_1:
2308 case Builtin::BI__sync_fetch_and_nand_2:
2309 case Builtin::BI__sync_fetch_and_nand_4:
2310 case Builtin::BI__sync_fetch_and_nand_8:
2311 case Builtin::BI__sync_fetch_and_nand_16:
2312 BuiltinIndex = 5;
2313 WarnAboutSemanticsChange = true;
2314 break;
2315
Douglas Gregor73722482011-11-28 16:30:08 +00002316 case Builtin::BI__sync_add_and_fetch:
2317 case Builtin::BI__sync_add_and_fetch_1:
2318 case Builtin::BI__sync_add_and_fetch_2:
2319 case Builtin::BI__sync_add_and_fetch_4:
2320 case Builtin::BI__sync_add_and_fetch_8:
2321 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002322 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002323 break;
2324
2325 case Builtin::BI__sync_sub_and_fetch:
2326 case Builtin::BI__sync_sub_and_fetch_1:
2327 case Builtin::BI__sync_sub_and_fetch_2:
2328 case Builtin::BI__sync_sub_and_fetch_4:
2329 case Builtin::BI__sync_sub_and_fetch_8:
2330 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002331 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002332 break;
2333
2334 case Builtin::BI__sync_and_and_fetch:
2335 case Builtin::BI__sync_and_and_fetch_1:
2336 case Builtin::BI__sync_and_and_fetch_2:
2337 case Builtin::BI__sync_and_and_fetch_4:
2338 case Builtin::BI__sync_and_and_fetch_8:
2339 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002340 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002341 break;
2342
2343 case Builtin::BI__sync_or_and_fetch:
2344 case Builtin::BI__sync_or_and_fetch_1:
2345 case Builtin::BI__sync_or_and_fetch_2:
2346 case Builtin::BI__sync_or_and_fetch_4:
2347 case Builtin::BI__sync_or_and_fetch_8:
2348 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002349 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002350 break;
2351
2352 case Builtin::BI__sync_xor_and_fetch:
2353 case Builtin::BI__sync_xor_and_fetch_1:
2354 case Builtin::BI__sync_xor_and_fetch_2:
2355 case Builtin::BI__sync_xor_and_fetch_4:
2356 case Builtin::BI__sync_xor_and_fetch_8:
2357 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002358 BuiltinIndex = 10;
2359 break;
2360
2361 case Builtin::BI__sync_nand_and_fetch:
2362 case Builtin::BI__sync_nand_and_fetch_1:
2363 case Builtin::BI__sync_nand_and_fetch_2:
2364 case Builtin::BI__sync_nand_and_fetch_4:
2365 case Builtin::BI__sync_nand_and_fetch_8:
2366 case Builtin::BI__sync_nand_and_fetch_16:
2367 BuiltinIndex = 11;
2368 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002369 break;
Mike Stump11289f42009-09-09 15:08:12 +00002370
Chris Lattnerdc046542009-05-08 06:58:22 +00002371 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002372 case Builtin::BI__sync_val_compare_and_swap_1:
2373 case Builtin::BI__sync_val_compare_and_swap_2:
2374 case Builtin::BI__sync_val_compare_and_swap_4:
2375 case Builtin::BI__sync_val_compare_and_swap_8:
2376 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002377 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002378 NumFixed = 2;
2379 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002380
Chris Lattnerdc046542009-05-08 06:58:22 +00002381 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002382 case Builtin::BI__sync_bool_compare_and_swap_1:
2383 case Builtin::BI__sync_bool_compare_and_swap_2:
2384 case Builtin::BI__sync_bool_compare_and_swap_4:
2385 case Builtin::BI__sync_bool_compare_and_swap_8:
2386 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002387 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002388 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002389 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002390 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002391
2392 case Builtin::BI__sync_lock_test_and_set:
2393 case Builtin::BI__sync_lock_test_and_set_1:
2394 case Builtin::BI__sync_lock_test_and_set_2:
2395 case Builtin::BI__sync_lock_test_and_set_4:
2396 case Builtin::BI__sync_lock_test_and_set_8:
2397 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002398 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002399 break;
2400
Chris Lattnerdc046542009-05-08 06:58:22 +00002401 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002402 case Builtin::BI__sync_lock_release_1:
2403 case Builtin::BI__sync_lock_release_2:
2404 case Builtin::BI__sync_lock_release_4:
2405 case Builtin::BI__sync_lock_release_8:
2406 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002407 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002408 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002409 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002410 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002411
2412 case Builtin::BI__sync_swap:
2413 case Builtin::BI__sync_swap_1:
2414 case Builtin::BI__sync_swap_2:
2415 case Builtin::BI__sync_swap_4:
2416 case Builtin::BI__sync_swap_8:
2417 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002418 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002419 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
Chris Lattnerdc046542009-05-08 06:58:22 +00002422 // Now that we know how many fixed arguments we expect, first check that we
2423 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002424 if (TheCall->getNumArgs() < 1+NumFixed) {
2425 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2426 << 0 << 1+NumFixed << TheCall->getNumArgs()
2427 << TheCall->getCallee()->getSourceRange();
2428 return ExprError();
2429 }
Mike Stump11289f42009-09-09 15:08:12 +00002430
Hal Finkeld2208b52014-10-02 20:53:50 +00002431 if (WarnAboutSemanticsChange) {
2432 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2433 << TheCall->getCallee()->getSourceRange();
2434 }
2435
Chris Lattner5b9241b2009-05-08 15:36:58 +00002436 // Get the decl for the concrete builtin from this, we can tell what the
2437 // concrete integer type we should convert to is.
2438 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002439 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002440 FunctionDecl *NewBuiltinDecl;
2441 if (NewBuiltinID == BuiltinID)
2442 NewBuiltinDecl = FDecl;
2443 else {
2444 // Perform builtin lookup to avoid redeclaring it.
2445 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2446 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2447 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2448 assert(Res.getFoundDecl());
2449 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002450 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002451 return ExprError();
2452 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002453
John McCallcf142162010-08-07 06:22:56 +00002454 // The first argument --- the pointer --- has a fixed type; we
2455 // deduce the types of the rest of the arguments accordingly. Walk
2456 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002457 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002458 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002459
Chris Lattnerdc046542009-05-08 06:58:22 +00002460 // GCC does an implicit conversion to the pointer or integer ValType. This
2461 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002462 // Initialize the argument.
2463 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2464 ValType, /*consume*/ false);
2465 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002466 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002467 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002468
Chris Lattnerdc046542009-05-08 06:58:22 +00002469 // Okay, we have something that *can* be converted to the right type. Check
2470 // to see if there is a potentially weird extension going on here. This can
2471 // happen when you do an atomic operation on something like an char* and
2472 // pass in 42. The 42 gets converted to char. This is even more strange
2473 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002474 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002475 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002476 }
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002478 ASTContext& Context = this->getASTContext();
2479
2480 // Create a new DeclRefExpr to refer to the new decl.
2481 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2482 Context,
2483 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002484 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002485 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002486 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002487 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002488 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002489 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002490
Chris Lattnerdc046542009-05-08 06:58:22 +00002491 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002492 // FIXME: This loses syntactic information.
2493 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2494 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2495 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002496 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002497
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002498 // Change the result type of the call to match the original value type. This
2499 // is arbitrary, but the codegen for these builtins ins design to handle it
2500 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002501 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002502
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002503 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002504}
2505
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002506/// SemaBuiltinNontemporalOverloaded - We have a call to
2507/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2508/// overloaded function based on the pointer type of its last argument.
2509///
2510/// This function goes through and does final semantic checking for these
2511/// builtins.
2512ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2513 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2514 DeclRefExpr *DRE =
2515 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2516 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2517 unsigned BuiltinID = FDecl->getBuiltinID();
2518 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2519 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2520 "Unexpected nontemporal load/store builtin!");
2521 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2522 unsigned numArgs = isStore ? 2 : 1;
2523
2524 // Ensure that we have the proper number of arguments.
2525 if (checkArgCount(*this, TheCall, numArgs))
2526 return ExprError();
2527
2528 // Inspect the last argument of the nontemporal builtin. This should always
2529 // be a pointer type, from which we imply the type of the memory access.
2530 // Because it is a pointer type, we don't have to worry about any implicit
2531 // casts here.
2532 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2533 ExprResult PointerArgResult =
2534 DefaultFunctionArrayLvalueConversion(PointerArg);
2535
2536 if (PointerArgResult.isInvalid())
2537 return ExprError();
2538 PointerArg = PointerArgResult.get();
2539 TheCall->setArg(numArgs - 1, PointerArg);
2540
2541 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2542 if (!pointerType) {
2543 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2544 << PointerArg->getType() << PointerArg->getSourceRange();
2545 return ExprError();
2546 }
2547
2548 QualType ValType = pointerType->getPointeeType();
2549
2550 // Strip any qualifiers off ValType.
2551 ValType = ValType.getUnqualifiedType();
2552 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2553 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2554 !ValType->isVectorType()) {
2555 Diag(DRE->getLocStart(),
2556 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2557 << PointerArg->getType() << PointerArg->getSourceRange();
2558 return ExprError();
2559 }
2560
2561 if (!isStore) {
2562 TheCall->setType(ValType);
2563 return TheCallResult;
2564 }
2565
2566 ExprResult ValArg = TheCall->getArg(0);
2567 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2568 Context, ValType, /*consume*/ false);
2569 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2570 if (ValArg.isInvalid())
2571 return ExprError();
2572
2573 TheCall->setArg(0, ValArg.get());
2574 TheCall->setType(Context.VoidTy);
2575 return TheCallResult;
2576}
2577
Chris Lattner6436fb62009-02-18 06:01:06 +00002578/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002579/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002580/// Note: It might also make sense to do the UTF-16 conversion here (would
2581/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002582bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002583 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002584 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2585
Douglas Gregorfb65e592011-07-27 05:40:30 +00002586 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002587 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2588 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002589 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002592 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002593 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002594 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002595 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002596 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002597 UTF16 *ToPtr = &ToBuf[0];
2598
2599 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2600 &ToPtr, ToPtr + NumBytes,
2601 strictConversion);
2602 // Check for conversion failure.
2603 if (Result != conversionOK)
2604 Diag(Arg->getLocStart(),
2605 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2606 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002607 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002608}
2609
Charles Davisc7d5c942015-09-17 20:55:33 +00002610/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2611/// for validity. Emit an error and return true on failure; return false
2612/// on success.
2613bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002614 Expr *Fn = TheCall->getCallee();
2615 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002616 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002617 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002618 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2619 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002620 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002621 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002622 return true;
2623 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002624
2625 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002626 return Diag(TheCall->getLocEnd(),
2627 diag::err_typecheck_call_too_few_args_at_least)
2628 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002629 }
2630
John McCall29ad95b2011-08-27 01:09:30 +00002631 // Type-check the first argument normally.
2632 if (checkBuiltinArgument(*this, TheCall, 0))
2633 return true;
2634
Chris Lattnere202e6a2007-12-20 00:05:45 +00002635 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002636 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002637 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002638 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002639 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002640 else if (FunctionDecl *FD = getCurFunctionDecl())
2641 isVariadic = FD->isVariadic();
2642 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002643 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002644
Chris Lattnere202e6a2007-12-20 00:05:45 +00002645 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002646 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2647 return true;
2648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
Chris Lattner43be2e62007-12-19 23:59:04 +00002650 // Verify that the second argument to the builtin is the last argument of the
2651 // current function or method.
2652 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002653 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002654
Nico Weber9eea7642013-05-24 23:31:57 +00002655 // These are valid if SecondArgIsLastNamedArgument is false after the next
2656 // block.
2657 QualType Type;
2658 SourceLocation ParamLoc;
2659
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002660 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2661 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002662 // FIXME: This isn't correct for methods (results in bogus warning).
2663 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002664 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002665 if (CurBlock)
2666 LastArg = *(CurBlock->TheDecl->param_end()-1);
2667 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002668 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002669 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002670 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002671 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002672
2673 Type = PV->getType();
2674 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002675 }
2676 }
Mike Stump11289f42009-09-09 15:08:12 +00002677
Chris Lattner43be2e62007-12-19 23:59:04 +00002678 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002679 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002680 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002681 else if (Type->isReferenceType()) {
2682 Diag(Arg->getLocStart(),
2683 diag::warn_va_start_of_reference_type_is_undefined);
2684 Diag(ParamLoc, diag::note_parameter_type) << Type;
2685 }
2686
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002687 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002688 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002689}
Chris Lattner43be2e62007-12-19 23:59:04 +00002690
Charles Davisc7d5c942015-09-17 20:55:33 +00002691/// Check the arguments to '__builtin_va_start' for validity, and that
2692/// it was called from a function of the native ABI.
2693/// Emit an error and return true on failure; return false on success.
2694bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2695 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2696 // On x64 Windows, don't allow this in System V ABI functions.
2697 // (Yes, that means there's no corresponding way to support variadic
2698 // System V ABI functions on Windows.)
2699 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2700 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2701 clang::CallingConv CC = CC_C;
2702 if (const FunctionDecl *FD = getCurFunctionDecl())
2703 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2704 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2705 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2706 return Diag(TheCall->getCallee()->getLocStart(),
2707 diag::err_va_start_used_in_wrong_abi_function)
2708 << (OS != llvm::Triple::Win32);
2709 }
2710 return SemaBuiltinVAStartImpl(TheCall);
2711}
2712
2713/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2714/// it was called from a Win64 ABI function.
2715/// Emit an error and return true on failure; return false on success.
2716bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2717 // This only makes sense for x86-64.
2718 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2719 Expr *Callee = TheCall->getCallee();
2720 if (TT.getArch() != llvm::Triple::x86_64)
2721 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2722 // Don't allow this in System V ABI functions.
2723 clang::CallingConv CC = CC_C;
2724 if (const FunctionDecl *FD = getCurFunctionDecl())
2725 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2726 if (CC == CC_X86_64SysV ||
2727 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2728 return Diag(Callee->getLocStart(),
2729 diag::err_ms_va_start_used_in_sysv_function);
2730 return SemaBuiltinVAStartImpl(TheCall);
2731}
2732
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002733bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2734 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2735 // const char *named_addr);
2736
2737 Expr *Func = Call->getCallee();
2738
2739 if (Call->getNumArgs() < 3)
2740 return Diag(Call->getLocEnd(),
2741 diag::err_typecheck_call_too_few_args_at_least)
2742 << 0 /*function call*/ << 3 << Call->getNumArgs();
2743
2744 // Determine whether the current function is variadic or not.
2745 bool IsVariadic;
2746 if (BlockScopeInfo *CurBlock = getCurBlock())
2747 IsVariadic = CurBlock->TheDecl->isVariadic();
2748 else if (FunctionDecl *FD = getCurFunctionDecl())
2749 IsVariadic = FD->isVariadic();
2750 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2751 IsVariadic = MD->isVariadic();
2752 else
2753 llvm_unreachable("unexpected statement type");
2754
2755 if (!IsVariadic) {
2756 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2757 return true;
2758 }
2759
2760 // Type-check the first argument normally.
2761 if (checkBuiltinArgument(*this, Call, 0))
2762 return true;
2763
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002764 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002765 unsigned ArgNo;
2766 QualType Type;
2767 } ArgumentTypes[] = {
2768 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2769 { 2, Context.getSizeType() },
2770 };
2771
2772 for (const auto &AT : ArgumentTypes) {
2773 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2774 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2775 continue;
2776 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2777 << Arg->getType() << AT.Type << 1 /* different class */
2778 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2779 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2780 }
2781
2782 return false;
2783}
2784
Chris Lattner2da14fb2007-12-20 00:26:33 +00002785/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2786/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002787bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2788 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002789 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002790 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002791 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002792 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002793 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002794 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002795 << SourceRange(TheCall->getArg(2)->getLocStart(),
2796 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002797
John Wiegley01296292011-04-08 18:41:53 +00002798 ExprResult OrigArg0 = TheCall->getArg(0);
2799 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002800
Chris Lattner2da14fb2007-12-20 00:26:33 +00002801 // Do standard promotions between the two arguments, returning their common
2802 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002803 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002804 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2805 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002806
2807 // Make sure any conversions are pushed back into the call; this is
2808 // type safe since unordered compare builtins are declared as "_Bool
2809 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002810 TheCall->setArg(0, OrigArg0.get());
2811 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002812
John Wiegley01296292011-04-08 18:41:53 +00002813 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002814 return false;
2815
Chris Lattner2da14fb2007-12-20 00:26:33 +00002816 // If the common type isn't a real floating type, then the arguments were
2817 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002818 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002819 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002820 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002821 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2822 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002823
Chris Lattner2da14fb2007-12-20 00:26:33 +00002824 return false;
2825}
2826
Benjamin Kramer634fc102010-02-15 22:42:31 +00002827/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2828/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002829/// to check everything. We expect the last argument to be a floating point
2830/// value.
2831bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2832 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002833 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002834 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002835 if (TheCall->getNumArgs() > NumArgs)
2836 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002837 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002838 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002839 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002840 (*(TheCall->arg_end()-1))->getLocEnd());
2841
Benjamin Kramer64aae502010-02-16 10:07:31 +00002842 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002843
Eli Friedman7e4faac2009-08-31 20:06:00 +00002844 if (OrigArg->isTypeDependent())
2845 return false;
2846
Chris Lattner68784ef2010-05-06 05:50:07 +00002847 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002848 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002849 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002850 diag::err_typecheck_call_invalid_unary_fp)
2851 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002852
Chris Lattner68784ef2010-05-06 05:50:07 +00002853 // If this is an implicit conversion from float -> double, remove it.
2854 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2855 Expr *CastArg = Cast->getSubExpr();
2856 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2857 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2858 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002859 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002860 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002861 }
2862 }
2863
Eli Friedman7e4faac2009-08-31 20:06:00 +00002864 return false;
2865}
2866
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002867/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2868// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002869ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002870 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002871 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002872 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002873 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2874 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002875
Nate Begemana0110022010-06-08 00:16:34 +00002876 // Determine which of the following types of shufflevector we're checking:
2877 // 1) unary, vector mask: (lhs, mask)
2878 // 2) binary, vector mask: (lhs, rhs, mask)
2879 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2880 QualType resType = TheCall->getArg(0)->getType();
2881 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002882
Douglas Gregorc25f7662009-05-19 22:10:17 +00002883 if (!TheCall->getArg(0)->isTypeDependent() &&
2884 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002885 QualType LHSType = TheCall->getArg(0)->getType();
2886 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002887
Craig Topperbaca3892013-07-29 06:47:04 +00002888 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2889 return ExprError(Diag(TheCall->getLocStart(),
2890 diag::err_shufflevector_non_vector)
2891 << SourceRange(TheCall->getArg(0)->getLocStart(),
2892 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002893
Nate Begemana0110022010-06-08 00:16:34 +00002894 numElements = LHSType->getAs<VectorType>()->getNumElements();
2895 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002896
Nate Begemana0110022010-06-08 00:16:34 +00002897 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2898 // with mask. If so, verify that RHS is an integer vector type with the
2899 // same number of elts as lhs.
2900 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002901 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002902 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002903 return ExprError(Diag(TheCall->getLocStart(),
2904 diag::err_shufflevector_incompatible_vector)
2905 << SourceRange(TheCall->getArg(1)->getLocStart(),
2906 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002907 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002908 return ExprError(Diag(TheCall->getLocStart(),
2909 diag::err_shufflevector_incompatible_vector)
2910 << SourceRange(TheCall->getArg(0)->getLocStart(),
2911 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002912 } else if (numElements != numResElements) {
2913 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002914 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002915 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002916 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002917 }
2918
2919 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002920 if (TheCall->getArg(i)->isTypeDependent() ||
2921 TheCall->getArg(i)->isValueDependent())
2922 continue;
2923
Nate Begemana0110022010-06-08 00:16:34 +00002924 llvm::APSInt Result(32);
2925 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2926 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002927 diag::err_shufflevector_nonconstant_argument)
2928 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002929
Craig Topper50ad5b72013-08-03 17:40:38 +00002930 // Allow -1 which will be translated to undef in the IR.
2931 if (Result.isSigned() && Result.isAllOnesValue())
2932 continue;
2933
Chris Lattner7ab824e2008-08-10 02:05:13 +00002934 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002935 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002936 diag::err_shufflevector_argument_too_large)
2937 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002938 }
2939
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002940 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002941
Chris Lattner7ab824e2008-08-10 02:05:13 +00002942 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002943 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002944 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002945 }
2946
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002947 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2948 TheCall->getCallee()->getLocStart(),
2949 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002950}
Chris Lattner43be2e62007-12-19 23:59:04 +00002951
Hal Finkelc4d7c822013-09-18 03:29:45 +00002952/// SemaConvertVectorExpr - Handle __builtin_convertvector
2953ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2954 SourceLocation BuiltinLoc,
2955 SourceLocation RParenLoc) {
2956 ExprValueKind VK = VK_RValue;
2957 ExprObjectKind OK = OK_Ordinary;
2958 QualType DstTy = TInfo->getType();
2959 QualType SrcTy = E->getType();
2960
2961 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2962 return ExprError(Diag(BuiltinLoc,
2963 diag::err_convertvector_non_vector)
2964 << E->getSourceRange());
2965 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2966 return ExprError(Diag(BuiltinLoc,
2967 diag::err_convertvector_non_vector_type));
2968
2969 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2970 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2971 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2972 if (SrcElts != DstElts)
2973 return ExprError(Diag(BuiltinLoc,
2974 diag::err_convertvector_incompatible_vector)
2975 << E->getSourceRange());
2976 }
2977
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002978 return new (Context)
2979 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002980}
2981
Daniel Dunbarb7257262008-07-21 22:59:13 +00002982/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2983// This is declared to take (const void*, ...) and can take two
2984// optional constant int args.
2985bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002986 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002987
Chris Lattner3b054132008-11-19 05:08:23 +00002988 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002989 return Diag(TheCall->getLocEnd(),
2990 diag::err_typecheck_call_too_many_args_at_most)
2991 << 0 /*function call*/ << 3 << NumArgs
2992 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002993
2994 // Argument 0 is checked for us and the remaining arguments must be
2995 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002996 for (unsigned i = 1; i != NumArgs; ++i)
2997 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002998 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002999
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003000 return false;
3001}
3002
Hal Finkelf0417332014-07-17 14:25:55 +00003003/// SemaBuiltinAssume - Handle __assume (MS Extension).
3004// __assume does not evaluate its arguments, and should warn if its argument
3005// has side effects.
3006bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3007 Expr *Arg = TheCall->getArg(0);
3008 if (Arg->isInstantiationDependent()) return false;
3009
3010 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003011 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003012 << Arg->getSourceRange()
3013 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3014
3015 return false;
3016}
3017
3018/// Handle __builtin_assume_aligned. This is declared
3019/// as (const void*, size_t, ...) and can take one optional constant int arg.
3020bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3021 unsigned NumArgs = TheCall->getNumArgs();
3022
3023 if (NumArgs > 3)
3024 return Diag(TheCall->getLocEnd(),
3025 diag::err_typecheck_call_too_many_args_at_most)
3026 << 0 /*function call*/ << 3 << NumArgs
3027 << TheCall->getSourceRange();
3028
3029 // The alignment must be a constant integer.
3030 Expr *Arg = TheCall->getArg(1);
3031
3032 // We can't check the value of a dependent argument.
3033 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3034 llvm::APSInt Result;
3035 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3036 return true;
3037
3038 if (!Result.isPowerOf2())
3039 return Diag(TheCall->getLocStart(),
3040 diag::err_alignment_not_power_of_two)
3041 << Arg->getSourceRange();
3042 }
3043
3044 if (NumArgs > 2) {
3045 ExprResult Arg(TheCall->getArg(2));
3046 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3047 Context.getSizeType(), false);
3048 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3049 if (Arg.isInvalid()) return true;
3050 TheCall->setArg(2, Arg.get());
3051 }
Hal Finkelf0417332014-07-17 14:25:55 +00003052
3053 return false;
3054}
3055
Eric Christopher8d0c6212010-04-17 02:26:23 +00003056/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3057/// TheCall is a constant expression.
3058bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3059 llvm::APSInt &Result) {
3060 Expr *Arg = TheCall->getArg(ArgNum);
3061 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3062 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3063
3064 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3065
3066 if (!Arg->isIntegerConstantExpr(Result, Context))
3067 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003068 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003069
Chris Lattnerd545ad12009-09-23 06:06:36 +00003070 return false;
3071}
3072
Richard Sandiford28940af2014-04-16 08:47:51 +00003073/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3074/// TheCall is a constant expression in the range [Low, High].
3075bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3076 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003077 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003078
3079 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003080 Expr *Arg = TheCall->getArg(ArgNum);
3081 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003082 return false;
3083
Eric Christopher8d0c6212010-04-17 02:26:23 +00003084 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003085 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003086 return true;
3087
Richard Sandiford28940af2014-04-16 08:47:51 +00003088 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003089 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003090 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003091
3092 return false;
3093}
3094
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003095/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3096/// TheCall is an ARM/AArch64 special register string literal.
3097bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3098 int ArgNum, unsigned ExpectedFieldNum,
3099 bool AllowName) {
3100 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3101 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3102 BuiltinID == ARM::BI__builtin_arm_rsr ||
3103 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3104 BuiltinID == ARM::BI__builtin_arm_wsr ||
3105 BuiltinID == ARM::BI__builtin_arm_wsrp;
3106 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3107 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3108 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3109 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3110 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3111 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3112 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3113
3114 // We can't check the value of a dependent argument.
3115 Expr *Arg = TheCall->getArg(ArgNum);
3116 if (Arg->isTypeDependent() || Arg->isValueDependent())
3117 return false;
3118
3119 // Check if the argument is a string literal.
3120 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3121 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3122 << Arg->getSourceRange();
3123
3124 // Check the type of special register given.
3125 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3126 SmallVector<StringRef, 6> Fields;
3127 Reg.split(Fields, ":");
3128
3129 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3130 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3131 << Arg->getSourceRange();
3132
3133 // If the string is the name of a register then we cannot check that it is
3134 // valid here but if the string is of one the forms described in ACLE then we
3135 // can check that the supplied fields are integers and within the valid
3136 // ranges.
3137 if (Fields.size() > 1) {
3138 bool FiveFields = Fields.size() == 5;
3139
3140 bool ValidString = true;
3141 if (IsARMBuiltin) {
3142 ValidString &= Fields[0].startswith_lower("cp") ||
3143 Fields[0].startswith_lower("p");
3144 if (ValidString)
3145 Fields[0] =
3146 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3147
3148 ValidString &= Fields[2].startswith_lower("c");
3149 if (ValidString)
3150 Fields[2] = Fields[2].drop_front(1);
3151
3152 if (FiveFields) {
3153 ValidString &= Fields[3].startswith_lower("c");
3154 if (ValidString)
3155 Fields[3] = Fields[3].drop_front(1);
3156 }
3157 }
3158
3159 SmallVector<int, 5> Ranges;
3160 if (FiveFields)
3161 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3162 else
3163 Ranges.append({15, 7, 15});
3164
3165 for (unsigned i=0; i<Fields.size(); ++i) {
3166 int IntField;
3167 ValidString &= !Fields[i].getAsInteger(10, IntField);
3168 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3169 }
3170
3171 if (!ValidString)
3172 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3173 << Arg->getSourceRange();
3174
3175 } else if (IsAArch64Builtin && Fields.size() == 1) {
3176 // If the register name is one of those that appear in the condition below
3177 // and the special register builtin being used is one of the write builtins,
3178 // then we require that the argument provided for writing to the register
3179 // is an integer constant expression. This is because it will be lowered to
3180 // an MSR (immediate) instruction, so we need to know the immediate at
3181 // compile time.
3182 if (TheCall->getNumArgs() != 2)
3183 return false;
3184
3185 std::string RegLower = Reg.lower();
3186 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3187 RegLower != "pan" && RegLower != "uao")
3188 return false;
3189
3190 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3191 }
3192
3193 return false;
3194}
3195
Eli Friedmanc97d0142009-05-03 06:04:26 +00003196/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003197/// This checks that the target supports __builtin_longjmp and
3198/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003199bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003200 if (!Context.getTargetInfo().hasSjLjLowering())
3201 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3202 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3203
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003204 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003205 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003206
Eric Christopher8d0c6212010-04-17 02:26:23 +00003207 // TODO: This is less than ideal. Overload this to take a value.
3208 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3209 return true;
3210
3211 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003212 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3213 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3214
3215 return false;
3216}
3217
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003218/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3219/// This checks that the target supports __builtin_setjmp.
3220bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3221 if (!Context.getTargetInfo().hasSjLjLowering())
3222 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3223 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3224 return false;
3225}
3226
Richard Smithd7293d72013-08-05 18:49:43 +00003227namespace {
3228enum StringLiteralCheckType {
3229 SLCT_NotALiteral,
3230 SLCT_UncheckedLiteral,
3231 SLCT_CheckedLiteral
3232};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003233} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003234
Richard Smith55ce3522012-06-25 20:30:08 +00003235// Determine if an expression is a string literal or constant string.
3236// If this function returns false on the arguments to a function expecting a
3237// format string, we will usually need to emit a warning.
3238// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003239static StringLiteralCheckType
3240checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3241 bool HasVAListArg, unsigned format_idx,
3242 unsigned firstDataArg, Sema::FormatStringType Type,
3243 Sema::VariadicCallType CallType, bool InFunctionCall,
3244 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003245 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003246 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003247 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003248
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003249 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003250
Richard Smithd7293d72013-08-05 18:49:43 +00003251 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003252 // Technically -Wformat-nonliteral does not warn about this case.
3253 // The behavior of printf and friends in this case is implementation
3254 // dependent. Ideally if the format string cannot be null then
3255 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003256 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003257
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003258 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003259 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003260 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003261 // The expression is a literal if both sub-expressions were, and it was
3262 // completely checked only if both sub-expressions were checked.
3263 const AbstractConditionalOperator *C =
3264 cast<AbstractConditionalOperator>(E);
3265 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003266 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003267 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003268 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003269 if (Left == SLCT_NotALiteral)
3270 return SLCT_NotALiteral;
3271 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003272 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003273 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003274 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003275 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003276 }
3277
3278 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003279 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3280 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003281 }
3282
John McCallc07a0c72011-02-17 10:25:35 +00003283 case Stmt::OpaqueValueExprClass:
3284 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3285 E = src;
3286 goto tryAgain;
3287 }
Richard Smith55ce3522012-06-25 20:30:08 +00003288 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003289
Ted Kremeneka8890832011-02-24 23:03:04 +00003290 case Stmt::PredefinedExprClass:
3291 // While __func__, etc., are technically not string literals, they
3292 // cannot contain format specifiers and thus are not a security
3293 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003294 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003295
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003296 case Stmt::DeclRefExprClass: {
3297 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003298
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003299 // As an exception, do not flag errors for variables binding to
3300 // const string literals.
3301 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3302 bool isConstant = false;
3303 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003304
Richard Smithd7293d72013-08-05 18:49:43 +00003305 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3306 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003307 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003308 isConstant = T.isConstant(S.Context) &&
3309 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003310 } else if (T->isObjCObjectPointerType()) {
3311 // In ObjC, there is usually no "const ObjectPointer" type,
3312 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003313 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003314 }
Mike Stump11289f42009-09-09 15:08:12 +00003315
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003316 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003317 if (const Expr *Init = VD->getAnyInitializer()) {
3318 // Look through initializers like const char c[] = { "foo" }
3319 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3320 if (InitList->isStringLiteralInit())
3321 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3322 }
Richard Smithd7293d72013-08-05 18:49:43 +00003323 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003324 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003325 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003326 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003327 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003328 }
Mike Stump11289f42009-09-09 15:08:12 +00003329
Anders Carlssonb012ca92009-06-28 19:55:58 +00003330 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3331 // special check to see if the format string is a function parameter
3332 // of the function calling the printf function. If the function
3333 // has an attribute indicating it is a printf-like function, then we
3334 // should suppress warnings concerning non-literals being used in a call
3335 // to a vprintf function. For example:
3336 //
3337 // void
3338 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3339 // va_list ap;
3340 // va_start(ap, fmt);
3341 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3342 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003343 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003344 if (HasVAListArg) {
3345 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3346 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3347 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003348 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003349 // adjust for implicit parameter
3350 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3351 if (MD->isInstance())
3352 ++PVIndex;
3353 // We also check if the formats are compatible.
3354 // We can't pass a 'scanf' string to a 'printf' function.
3355 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003356 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003357 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003358 }
3359 }
3360 }
3361 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003362 }
Mike Stump11289f42009-09-09 15:08:12 +00003363
Richard Smith55ce3522012-06-25 20:30:08 +00003364 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003365 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003366
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003367 case Stmt::CallExprClass:
3368 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003369 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003370 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3371 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3372 unsigned ArgIndex = FA->getFormatIdx();
3373 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3374 if (MD->isInstance())
3375 --ArgIndex;
3376 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003377
Richard Smithd7293d72013-08-05 18:49:43 +00003378 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003379 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003380 Type, CallType, InFunctionCall,
3381 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003382 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3383 unsigned BuiltinID = FD->getBuiltinID();
3384 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3385 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3386 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003387 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003388 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003389 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003390 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003391 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003392 }
3393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Richard Smith55ce3522012-06-25 20:30:08 +00003395 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003396 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003397 case Stmt::ObjCStringLiteralClass:
3398 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003399 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003401 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003402 StrE = ObjCFExpr->getString();
3403 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003404 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003405
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003406 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003407 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3408 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003409 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003410 }
Mike Stump11289f42009-09-09 15:08:12 +00003411
Richard Smith55ce3522012-06-25 20:30:08 +00003412 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003413 }
Mike Stump11289f42009-09-09 15:08:12 +00003414
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003415 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003416 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003417 }
3418}
3419
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003420Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003421 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003422 .Case("scanf", FST_Scanf)
3423 .Cases("printf", "printf0", FST_Printf)
3424 .Cases("NSString", "CFString", FST_NSString)
3425 .Case("strftime", FST_Strftime)
3426 .Case("strfmon", FST_Strfmon)
3427 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003428 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003429 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003430 .Default(FST_Unknown);
3431}
3432
Jordan Rose3e0ec582012-07-19 18:10:23 +00003433/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003434/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003435/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003436bool Sema::CheckFormatArguments(const FormatAttr *Format,
3437 ArrayRef<const Expr *> Args,
3438 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003439 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003440 SourceLocation Loc, SourceRange Range,
3441 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003442 FormatStringInfo FSI;
3443 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003444 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003445 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003446 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003447 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003448}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003449
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003450bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003451 bool HasVAListArg, unsigned format_idx,
3452 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003453 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003454 SourceLocation Loc, SourceRange Range,
3455 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003456 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003457 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003458 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003459 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003460 }
Mike Stump11289f42009-09-09 15:08:12 +00003461
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003462 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003463
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003464 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003465 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003466 // Dynamically generated format strings are difficult to
3467 // automatically vet at compile time. Requiring that format strings
3468 // are string literals: (1) permits the checking of format strings by
3469 // the compiler and thereby (2) can practically remove the source of
3470 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003471
Mike Stump11289f42009-09-09 15:08:12 +00003472 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003473 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003474 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003475 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003476 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003477 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3478 format_idx, firstDataArg, Type, CallType,
3479 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003480 if (CT != SLCT_NotALiteral)
3481 // Literal format string found, check done!
3482 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003483
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003484 // Strftime is particular as it always uses a single 'time' argument,
3485 // so it is safe to pass a non-literal string.
3486 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003487 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003488
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003489 // Do not emit diag when the string param is a macro expansion and the
3490 // format is either NSString or CFString. This is a hack to prevent
3491 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3492 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003493 if (Type == FST_NSString &&
3494 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003495 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003496
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003497 // If there are no arguments specified, warn with -Wformat-security, otherwise
3498 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003499 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003500 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003501 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003502 << OrigFormatExpr->getSourceRange();
3503 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003504 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003505 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003506 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003507 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003508}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003509
Ted Kremenekab278de2010-01-28 23:39:18 +00003510namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003511class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3512protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003513 Sema &S;
3514 const StringLiteral *FExpr;
3515 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003516 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003517 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003518 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003519 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003520 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003521 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003522 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003523 bool usesPositionalArgs;
3524 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003525 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003526 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003527 llvm::SmallBitVector &CheckedVarArgs;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003528
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003529public:
Ted Kremenek02087932010-07-16 02:11:22 +00003530 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003531 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003532 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003533 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003534 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003535 Sema::VariadicCallType callType,
3536 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003537 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003538 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3539 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003540 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003541 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003542 inFunctionCall(inFunctionCall), CallType(callType),
3543 CheckedVarArgs(CheckedVarArgs) {
3544 CoveredArgs.resize(numDataArgs);
3545 CoveredArgs.reset();
3546 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003547
Ted Kremenek019d2242010-01-29 01:50:07 +00003548 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003549
Ted Kremenek02087932010-07-16 02:11:22 +00003550 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003551 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003552
Jordan Rose92303592012-09-08 04:00:03 +00003553 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003554 const analyze_format_string::FormatSpecifier &FS,
3555 const analyze_format_string::ConversionSpecifier &CS,
3556 const char *startSpecifier, unsigned specifierLen,
3557 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003558
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003559 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003560 const analyze_format_string::FormatSpecifier &FS,
3561 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003562
3563 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003564 const analyze_format_string::ConversionSpecifier &CS,
3565 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003566
Craig Toppere14c0f82014-03-12 04:55:44 +00003567 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003568
Craig Toppere14c0f82014-03-12 04:55:44 +00003569 void HandleInvalidPosition(const char *startSpecifier,
3570 unsigned specifierLen,
3571 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003572
Craig Toppere14c0f82014-03-12 04:55:44 +00003573 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003574
Craig Toppere14c0f82014-03-12 04:55:44 +00003575 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003576
Richard Trieu03cf7b72011-10-28 00:41:25 +00003577 template <typename Range>
3578 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3579 const Expr *ArgumentExpr,
3580 PartialDiagnostic PDiag,
3581 SourceLocation StringLoc,
3582 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003583 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003584
Ted Kremenek02087932010-07-16 02:11:22 +00003585protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003586 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3587 const char *startSpec,
3588 unsigned specifierLen,
3589 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003590
3591 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3592 const char *startSpec,
3593 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003594
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003595 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003596 CharSourceRange getSpecifierRange(const char *startSpecifier,
3597 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003598 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003599
Ted Kremenek5739de72010-01-29 01:06:55 +00003600 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003601
3602 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3603 const analyze_format_string::ConversionSpecifier &CS,
3604 const char *startSpecifier, unsigned specifierLen,
3605 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003606
3607 template <typename Range>
3608 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3609 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003610 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003611};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003612} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003613
Ted Kremenek02087932010-07-16 02:11:22 +00003614SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003615 return OrigFormatExpr->getSourceRange();
3616}
3617
Ted Kremenek02087932010-07-16 02:11:22 +00003618CharSourceRange CheckFormatHandler::
3619getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003620 SourceLocation Start = getLocationOfByte(startSpecifier);
3621 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3622
3623 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003624 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003625
3626 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003627}
3628
Ted Kremenek02087932010-07-16 02:11:22 +00003629SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003630 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003631}
3632
Ted Kremenek02087932010-07-16 02:11:22 +00003633void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3634 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003635 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3636 getLocationOfByte(startSpecifier),
3637 /*IsStringLocation*/true,
3638 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003639}
3640
Jordan Rose92303592012-09-08 04:00:03 +00003641void CheckFormatHandler::HandleInvalidLengthModifier(
3642 const analyze_format_string::FormatSpecifier &FS,
3643 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003644 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003645 using namespace analyze_format_string;
3646
3647 const LengthModifier &LM = FS.getLengthModifier();
3648 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3649
3650 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003651 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003652 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003653 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003654 getLocationOfByte(LM.getStart()),
3655 /*IsStringLocation*/true,
3656 getSpecifierRange(startSpecifier, specifierLen));
3657
3658 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3659 << FixedLM->toString()
3660 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3661
3662 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003663 FixItHint Hint;
3664 if (DiagID == diag::warn_format_nonsensical_length)
3665 Hint = FixItHint::CreateRemoval(LMRange);
3666
3667 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003668 getLocationOfByte(LM.getStart()),
3669 /*IsStringLocation*/true,
3670 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003671 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003672 }
3673}
3674
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003675void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003676 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003677 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003678 using namespace analyze_format_string;
3679
3680 const LengthModifier &LM = FS.getLengthModifier();
3681 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3682
3683 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003684 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003685 if (FixedLM) {
3686 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3687 << LM.toString() << 0,
3688 getLocationOfByte(LM.getStart()),
3689 /*IsStringLocation*/true,
3690 getSpecifierRange(startSpecifier, specifierLen));
3691
3692 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3693 << FixedLM->toString()
3694 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3695
3696 } else {
3697 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3698 << LM.toString() << 0,
3699 getLocationOfByte(LM.getStart()),
3700 /*IsStringLocation*/true,
3701 getSpecifierRange(startSpecifier, specifierLen));
3702 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003703}
3704
3705void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3706 const analyze_format_string::ConversionSpecifier &CS,
3707 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003708 using namespace analyze_format_string;
3709
3710 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003711 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003712 if (FixedCS) {
3713 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3714 << CS.toString() << /*conversion specifier*/1,
3715 getLocationOfByte(CS.getStart()),
3716 /*IsStringLocation*/true,
3717 getSpecifierRange(startSpecifier, specifierLen));
3718
3719 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3720 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3721 << FixedCS->toString()
3722 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3723 } else {
3724 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3725 << CS.toString() << /*conversion specifier*/1,
3726 getLocationOfByte(CS.getStart()),
3727 /*IsStringLocation*/true,
3728 getSpecifierRange(startSpecifier, specifierLen));
3729 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003730}
3731
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003732void CheckFormatHandler::HandlePosition(const char *startPos,
3733 unsigned posLen) {
3734 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3735 getLocationOfByte(startPos),
3736 /*IsStringLocation*/true,
3737 getSpecifierRange(startPos, posLen));
3738}
3739
Ted Kremenekd1668192010-02-27 01:41:03 +00003740void
Ted Kremenek02087932010-07-16 02:11:22 +00003741CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3742 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003743 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3744 << (unsigned) p,
3745 getLocationOfByte(startPos), /*IsStringLocation*/true,
3746 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003747}
3748
Ted Kremenek02087932010-07-16 02:11:22 +00003749void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003750 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003751 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3752 getLocationOfByte(startPos),
3753 /*IsStringLocation*/true,
3754 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003755}
3756
Ted Kremenek02087932010-07-16 02:11:22 +00003757void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003758 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003759 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003760 EmitFormatDiagnostic(
3761 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3762 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3763 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003764 }
Ted Kremenek02087932010-07-16 02:11:22 +00003765}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003766
Jordan Rose58bbe422012-07-19 18:10:08 +00003767// Note that this may return NULL if there was an error parsing or building
3768// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003769const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003770 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003771}
3772
3773void CheckFormatHandler::DoneProcessing() {
3774 // Does the number of data arguments exceed the number of
3775 // format conversions in the format string?
3776 if (!HasVAListArg) {
3777 // Find any arguments that weren't covered.
3778 CoveredArgs.flip();
3779 signed notCoveredArg = CoveredArgs.find_first();
3780 if (notCoveredArg >= 0) {
3781 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003782 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3783 SourceLocation Loc = E->getLocStart();
3784 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3785 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3786 Loc, /*IsStringLocation*/false,
3787 getFormatStringRange());
3788 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003789 }
Ted Kremenek02087932010-07-16 02:11:22 +00003790 }
3791 }
3792}
3793
Ted Kremenekce815422010-07-19 21:25:57 +00003794bool
3795CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3796 SourceLocation Loc,
3797 const char *startSpec,
3798 unsigned specifierLen,
3799 const char *csStart,
3800 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003801 bool keepGoing = true;
3802 if (argIndex < NumDataArgs) {
3803 // Consider the argument coverered, even though the specifier doesn't
3804 // make sense.
3805 CoveredArgs.set(argIndex);
3806 }
3807 else {
3808 // If argIndex exceeds the number of data arguments we
3809 // don't issue a warning because that is just a cascade of warnings (and
3810 // they may have intended '%%' anyway). We don't want to continue processing
3811 // the format string after this point, however, as we will like just get
3812 // gibberish when trying to match arguments.
3813 keepGoing = false;
3814 }
3815
Richard Trieu03cf7b72011-10-28 00:41:25 +00003816 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3817 << StringRef(csStart, csLen),
3818 Loc, /*IsStringLocation*/true,
3819 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003820
3821 return keepGoing;
3822}
3823
Richard Trieu03cf7b72011-10-28 00:41:25 +00003824void
3825CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3826 const char *startSpec,
3827 unsigned specifierLen) {
3828 EmitFormatDiagnostic(
3829 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3830 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3831}
3832
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003833bool
3834CheckFormatHandler::CheckNumArgs(
3835 const analyze_format_string::FormatSpecifier &FS,
3836 const analyze_format_string::ConversionSpecifier &CS,
3837 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3838
3839 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003840 PartialDiagnostic PDiag = FS.usesPositionalArg()
3841 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3842 << (argIndex+1) << NumDataArgs)
3843 : S.PDiag(diag::warn_printf_insufficient_data_args);
3844 EmitFormatDiagnostic(
3845 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3846 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003847 return false;
3848 }
3849 return true;
3850}
3851
Richard Trieu03cf7b72011-10-28 00:41:25 +00003852template<typename Range>
3853void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3854 SourceLocation Loc,
3855 bool IsStringLocation,
3856 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003857 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003858 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003859 Loc, IsStringLocation, StringRange, FixIt);
3860}
3861
3862/// \brief If the format string is not within the funcion call, emit a note
3863/// so that the function call and string are in diagnostic messages.
3864///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003865/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003866/// call and only one diagnostic message will be produced. Otherwise, an
3867/// extra note will be emitted pointing to location of the format string.
3868///
3869/// \param ArgumentExpr the expression that is passed as the format string
3870/// argument in the function call. Used for getting locations when two
3871/// diagnostics are emitted.
3872///
3873/// \param PDiag the callee should already have provided any strings for the
3874/// diagnostic message. This function only adds locations and fixits
3875/// to diagnostics.
3876///
3877/// \param Loc primary location for diagnostic. If two diagnostics are
3878/// required, one will be at Loc and a new SourceLocation will be created for
3879/// the other one.
3880///
3881/// \param IsStringLocation if true, Loc points to the format string should be
3882/// used for the note. Otherwise, Loc points to the argument list and will
3883/// be used with PDiag.
3884///
3885/// \param StringRange some or all of the string to highlight. This is
3886/// templated so it can accept either a CharSourceRange or a SourceRange.
3887///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003888/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003889template<typename Range>
3890void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3891 const Expr *ArgumentExpr,
3892 PartialDiagnostic PDiag,
3893 SourceLocation Loc,
3894 bool IsStringLocation,
3895 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003896 ArrayRef<FixItHint> FixIt) {
3897 if (InFunctionCall) {
3898 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3899 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003900 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003901 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003902 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3903 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003904
3905 const Sema::SemaDiagnosticBuilder &Note =
3906 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3907 diag::note_format_string_defined);
3908
3909 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003910 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003911 }
3912}
3913
Ted Kremenek02087932010-07-16 02:11:22 +00003914//===--- CHECK: Printf format string checking ------------------------------===//
3915
3916namespace {
3917class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003918 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003919
Ted Kremenek02087932010-07-16 02:11:22 +00003920public:
3921 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3922 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003923 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003924 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003925 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003926 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003927 Sema::VariadicCallType CallType,
3928 llvm::SmallBitVector &CheckedVarArgs)
3929 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3930 numDataArgs, beg, hasVAListArg, Args,
3931 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3932 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003933 {}
3934
Ted Kremenek02087932010-07-16 02:11:22 +00003935 bool HandleInvalidPrintfConversionSpecifier(
3936 const analyze_printf::PrintfSpecifier &FS,
3937 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003938 unsigned specifierLen) override;
3939
Ted Kremenek02087932010-07-16 02:11:22 +00003940 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3941 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003942 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003943 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3944 const char *StartSpecifier,
3945 unsigned SpecifierLen,
3946 const Expr *E);
3947
Ted Kremenek02087932010-07-16 02:11:22 +00003948 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3949 const char *startSpecifier, unsigned specifierLen);
3950 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3951 const analyze_printf::OptionalAmount &Amt,
3952 unsigned type,
3953 const char *startSpecifier, unsigned specifierLen);
3954 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3955 const analyze_printf::OptionalFlag &flag,
3956 const char *startSpecifier, unsigned specifierLen);
3957 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3958 const analyze_printf::OptionalFlag &ignoredFlag,
3959 const analyze_printf::OptionalFlag &flag,
3960 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003961 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003962 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003963
3964 void HandleEmptyObjCModifierFlag(const char *startFlag,
3965 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003966
Ted Kremenek2b417712015-07-02 05:39:16 +00003967 void HandleInvalidObjCModifierFlag(const char *startFlag,
3968 unsigned flagLen) override;
3969
3970 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3971 const char *flagsEnd,
3972 const char *conversionPosition)
3973 override;
3974};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003975} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00003976
3977bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3978 const analyze_printf::PrintfSpecifier &FS,
3979 const char *startSpecifier,
3980 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003981 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003982 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003983
Ted Kremenekce815422010-07-19 21:25:57 +00003984 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3985 getLocationOfByte(CS.getStart()),
3986 startSpecifier, specifierLen,
3987 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003988}
3989
Ted Kremenek02087932010-07-16 02:11:22 +00003990bool CheckPrintfHandler::HandleAmount(
3991 const analyze_format_string::OptionalAmount &Amt,
3992 unsigned k, const char *startSpecifier,
3993 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003994 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003995 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003996 unsigned argIndex = Amt.getArgIndex();
3997 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003998 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3999 << k,
4000 getLocationOfByte(Amt.getStart()),
4001 /*IsStringLocation*/true,
4002 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004003 // Don't do any more checking. We will just emit
4004 // spurious errors.
4005 return false;
4006 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004007
Ted Kremenek5739de72010-01-29 01:06:55 +00004008 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004009 // Although not in conformance with C99, we also allow the argument to be
4010 // an 'unsigned int' as that is a reasonably safe case. GCC also
4011 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004012 CoveredArgs.set(argIndex);
4013 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004014 if (!Arg)
4015 return false;
4016
Ted Kremenek5739de72010-01-29 01:06:55 +00004017 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004018
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004019 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4020 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004021
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004022 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004023 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004024 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004025 << T << Arg->getSourceRange(),
4026 getLocationOfByte(Amt.getStart()),
4027 /*IsStringLocation*/true,
4028 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004029 // Don't do any more checking. We will just emit
4030 // spurious errors.
4031 return false;
4032 }
4033 }
4034 }
4035 return true;
4036}
Ted Kremenek5739de72010-01-29 01:06:55 +00004037
Tom Careb49ec692010-06-17 19:00:27 +00004038void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004039 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004040 const analyze_printf::OptionalAmount &Amt,
4041 unsigned type,
4042 const char *startSpecifier,
4043 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004044 const analyze_printf::PrintfConversionSpecifier &CS =
4045 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004046
Richard Trieu03cf7b72011-10-28 00:41:25 +00004047 FixItHint fixit =
4048 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4049 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4050 Amt.getConstantLength()))
4051 : FixItHint();
4052
4053 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4054 << type << CS.toString(),
4055 getLocationOfByte(Amt.getStart()),
4056 /*IsStringLocation*/true,
4057 getSpecifierRange(startSpecifier, specifierLen),
4058 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004059}
4060
Ted Kremenek02087932010-07-16 02:11:22 +00004061void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004062 const analyze_printf::OptionalFlag &flag,
4063 const char *startSpecifier,
4064 unsigned specifierLen) {
4065 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004066 const analyze_printf::PrintfConversionSpecifier &CS =
4067 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004068 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4069 << flag.toString() << CS.toString(),
4070 getLocationOfByte(flag.getPosition()),
4071 /*IsStringLocation*/true,
4072 getSpecifierRange(startSpecifier, specifierLen),
4073 FixItHint::CreateRemoval(
4074 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004075}
4076
4077void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004078 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004079 const analyze_printf::OptionalFlag &ignoredFlag,
4080 const analyze_printf::OptionalFlag &flag,
4081 const char *startSpecifier,
4082 unsigned specifierLen) {
4083 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004084 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4085 << ignoredFlag.toString() << flag.toString(),
4086 getLocationOfByte(ignoredFlag.getPosition()),
4087 /*IsStringLocation*/true,
4088 getSpecifierRange(startSpecifier, specifierLen),
4089 FixItHint::CreateRemoval(
4090 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004091}
4092
Ted Kremenek2b417712015-07-02 05:39:16 +00004093// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4094// bool IsStringLocation, Range StringRange,
4095// ArrayRef<FixItHint> Fixit = None);
4096
4097void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4098 unsigned flagLen) {
4099 // Warn about an empty flag.
4100 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4101 getLocationOfByte(startFlag),
4102 /*IsStringLocation*/true,
4103 getSpecifierRange(startFlag, flagLen));
4104}
4105
4106void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4107 unsigned flagLen) {
4108 // Warn about an invalid flag.
4109 auto Range = getSpecifierRange(startFlag, flagLen);
4110 StringRef flag(startFlag, flagLen);
4111 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4112 getLocationOfByte(startFlag),
4113 /*IsStringLocation*/true,
4114 Range, FixItHint::CreateRemoval(Range));
4115}
4116
4117void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4118 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4119 // Warn about using '[...]' without a '@' conversion.
4120 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4121 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4122 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4123 getLocationOfByte(conversionPosition),
4124 /*IsStringLocation*/true,
4125 Range, FixItHint::CreateRemoval(Range));
4126}
4127
Richard Smith55ce3522012-06-25 20:30:08 +00004128// Determines if the specified is a C++ class or struct containing
4129// a member with the specified name and kind (e.g. a CXXMethodDecl named
4130// "c_str()").
4131template<typename MemberKind>
4132static llvm::SmallPtrSet<MemberKind*, 1>
4133CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4134 const RecordType *RT = Ty->getAs<RecordType>();
4135 llvm::SmallPtrSet<MemberKind*, 1> Results;
4136
4137 if (!RT)
4138 return Results;
4139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004140 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004141 return Results;
4142
Alp Tokerb6cc5922014-05-03 03:45:55 +00004143 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004144 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004145 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004146
4147 // We just need to include all members of the right kind turned up by the
4148 // filter, at this point.
4149 if (S.LookupQualifiedName(R, RT->getDecl()))
4150 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4151 NamedDecl *decl = (*I)->getUnderlyingDecl();
4152 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4153 Results.insert(FK);
4154 }
4155 return Results;
4156}
4157
Richard Smith2868a732014-02-28 01:36:39 +00004158/// Check if we could call '.c_str()' on an object.
4159///
4160/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4161/// allow the call, or if it would be ambiguous).
4162bool Sema::hasCStrMethod(const Expr *E) {
4163 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4164 MethodSet Results =
4165 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4166 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4167 MI != ME; ++MI)
4168 if ((*MI)->getMinRequiredArguments() == 0)
4169 return true;
4170 return false;
4171}
4172
Richard Smith55ce3522012-06-25 20:30:08 +00004173// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004174// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004175// Returns true when a c_str() conversion method is found.
4176bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004177 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004178 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4179
4180 MethodSet Results =
4181 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4182
4183 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4184 MI != ME; ++MI) {
4185 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004186 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004187 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004188 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004189 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004190 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4191 << "c_str()"
4192 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4193 return true;
4194 }
4195 }
4196
4197 return false;
4198}
4199
Ted Kremenekab278de2010-01-28 23:39:18 +00004200bool
Ted Kremenek02087932010-07-16 02:11:22 +00004201CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004202 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004203 const char *startSpecifier,
4204 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004205 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004206 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004207 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004208
Ted Kremenek6cd69422010-07-19 22:01:06 +00004209 if (FS.consumesDataArgument()) {
4210 if (atFirstArg) {
4211 atFirstArg = false;
4212 usesPositionalArgs = FS.usesPositionalArg();
4213 }
4214 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004215 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4216 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004217 return false;
4218 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004219 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004220
Ted Kremenekd1668192010-02-27 01:41:03 +00004221 // First check if the field width, precision, and conversion specifier
4222 // have matching data arguments.
4223 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4224 startSpecifier, specifierLen)) {
4225 return false;
4226 }
4227
4228 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4229 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004230 return false;
4231 }
4232
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004233 if (!CS.consumesDataArgument()) {
4234 // FIXME: Technically specifying a precision or field width here
4235 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004236 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004237 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004238
Ted Kremenek4a49d982010-02-26 19:18:41 +00004239 // Consume the argument.
4240 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004241 if (argIndex < NumDataArgs) {
4242 // The check to see if the argIndex is valid will come later.
4243 // We set the bit here because we may exit early from this
4244 // function if we encounter some other error.
4245 CoveredArgs.set(argIndex);
4246 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004247
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004248 // FreeBSD kernel extensions.
4249 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4250 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4251 // We need at least two arguments.
4252 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4253 return false;
4254
4255 // Claim the second argument.
4256 CoveredArgs.set(argIndex + 1);
4257
4258 // Type check the first argument (int for %b, pointer for %D)
4259 const Expr *Ex = getDataArg(argIndex);
4260 const analyze_printf::ArgType &AT =
4261 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4262 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4263 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4264 EmitFormatDiagnostic(
4265 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4266 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4267 << false << Ex->getSourceRange(),
4268 Ex->getLocStart(), /*IsStringLocation*/false,
4269 getSpecifierRange(startSpecifier, specifierLen));
4270
4271 // Type check the second argument (char * for both %b and %D)
4272 Ex = getDataArg(argIndex + 1);
4273 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4274 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4275 EmitFormatDiagnostic(
4276 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4277 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4278 << false << Ex->getSourceRange(),
4279 Ex->getLocStart(), /*IsStringLocation*/false,
4280 getSpecifierRange(startSpecifier, specifierLen));
4281
4282 return true;
4283 }
4284
Ted Kremenek4a49d982010-02-26 19:18:41 +00004285 // Check for using an Objective-C specific conversion specifier
4286 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004287 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004288 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4289 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004290 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004291
Tom Careb49ec692010-06-17 19:00:27 +00004292 // Check for invalid use of field width
4293 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004294 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004295 startSpecifier, specifierLen);
4296 }
4297
4298 // Check for invalid use of precision
4299 if (!FS.hasValidPrecision()) {
4300 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4301 startSpecifier, specifierLen);
4302 }
4303
4304 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004305 if (!FS.hasValidThousandsGroupingPrefix())
4306 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004307 if (!FS.hasValidLeadingZeros())
4308 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4309 if (!FS.hasValidPlusPrefix())
4310 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004311 if (!FS.hasValidSpacePrefix())
4312 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004313 if (!FS.hasValidAlternativeForm())
4314 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4315 if (!FS.hasValidLeftJustified())
4316 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4317
4318 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004319 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4320 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4321 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004322 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4323 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4324 startSpecifier, specifierLen);
4325
4326 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004327 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004328 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4329 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004330 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004331 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004332 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004333 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4334 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004335
Jordan Rose92303592012-09-08 04:00:03 +00004336 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4337 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4338
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004339 // The remaining checks depend on the data arguments.
4340 if (HasVAListArg)
4341 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004342
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004343 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004344 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004345
Jordan Rose58bbe422012-07-19 18:10:08 +00004346 const Expr *Arg = getDataArg(argIndex);
4347 if (!Arg)
4348 return true;
4349
4350 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004351}
4352
Jordan Roseaee34382012-09-05 22:56:26 +00004353static bool requiresParensToAddCast(const Expr *E) {
4354 // FIXME: We should have a general way to reason about operator
4355 // precedence and whether parens are actually needed here.
4356 // Take care of a few common cases where they aren't.
4357 const Expr *Inside = E->IgnoreImpCasts();
4358 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4359 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4360
4361 switch (Inside->getStmtClass()) {
4362 case Stmt::ArraySubscriptExprClass:
4363 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004364 case Stmt::CharacterLiteralClass:
4365 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004366 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004367 case Stmt::FloatingLiteralClass:
4368 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004369 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004370 case Stmt::ObjCArrayLiteralClass:
4371 case Stmt::ObjCBoolLiteralExprClass:
4372 case Stmt::ObjCBoxedExprClass:
4373 case Stmt::ObjCDictionaryLiteralClass:
4374 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004375 case Stmt::ObjCIvarRefExprClass:
4376 case Stmt::ObjCMessageExprClass:
4377 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004378 case Stmt::ObjCStringLiteralClass:
4379 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004380 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004381 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004382 case Stmt::UnaryOperatorClass:
4383 return false;
4384 default:
4385 return true;
4386 }
4387}
4388
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004389static std::pair<QualType, StringRef>
4390shouldNotPrintDirectly(const ASTContext &Context,
4391 QualType IntendedTy,
4392 const Expr *E) {
4393 // Use a 'while' to peel off layers of typedefs.
4394 QualType TyTy = IntendedTy;
4395 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4396 StringRef Name = UserTy->getDecl()->getName();
4397 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4398 .Case("NSInteger", Context.LongTy)
4399 .Case("NSUInteger", Context.UnsignedLongTy)
4400 .Case("SInt32", Context.IntTy)
4401 .Case("UInt32", Context.UnsignedIntTy)
4402 .Default(QualType());
4403
4404 if (!CastTy.isNull())
4405 return std::make_pair(CastTy, Name);
4406
4407 TyTy = UserTy->desugar();
4408 }
4409
4410 // Strip parens if necessary.
4411 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4412 return shouldNotPrintDirectly(Context,
4413 PE->getSubExpr()->getType(),
4414 PE->getSubExpr());
4415
4416 // If this is a conditional expression, then its result type is constructed
4417 // via usual arithmetic conversions and thus there might be no necessary
4418 // typedef sugar there. Recurse to operands to check for NSInteger &
4419 // Co. usage condition.
4420 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4421 QualType TrueTy, FalseTy;
4422 StringRef TrueName, FalseName;
4423
4424 std::tie(TrueTy, TrueName) =
4425 shouldNotPrintDirectly(Context,
4426 CO->getTrueExpr()->getType(),
4427 CO->getTrueExpr());
4428 std::tie(FalseTy, FalseName) =
4429 shouldNotPrintDirectly(Context,
4430 CO->getFalseExpr()->getType(),
4431 CO->getFalseExpr());
4432
4433 if (TrueTy == FalseTy)
4434 return std::make_pair(TrueTy, TrueName);
4435 else if (TrueTy.isNull())
4436 return std::make_pair(FalseTy, FalseName);
4437 else if (FalseTy.isNull())
4438 return std::make_pair(TrueTy, TrueName);
4439 }
4440
4441 return std::make_pair(QualType(), StringRef());
4442}
4443
Richard Smith55ce3522012-06-25 20:30:08 +00004444bool
4445CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4446 const char *StartSpecifier,
4447 unsigned SpecifierLen,
4448 const Expr *E) {
4449 using namespace analyze_format_string;
4450 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004451 // Now type check the data expression that matches the
4452 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004453 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4454 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004455 if (!AT.isValid())
4456 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004457
Jordan Rose598ec092012-12-05 18:44:40 +00004458 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004459 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4460 ExprTy = TET->getUnderlyingExpr()->getType();
4461 }
4462
Seth Cantrellb4802962015-03-04 03:12:10 +00004463 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4464
4465 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004466 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004467 }
Jordan Rose98709982012-06-04 22:48:57 +00004468
Jordan Rose22b74712012-09-05 22:56:19 +00004469 // Look through argument promotions for our error message's reported type.
4470 // This includes the integral and floating promotions, but excludes array
4471 // and function pointer decay; seeing that an argument intended to be a
4472 // string has type 'char [6]' is probably more confusing than 'char *'.
4473 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4474 if (ICE->getCastKind() == CK_IntegralCast ||
4475 ICE->getCastKind() == CK_FloatingCast) {
4476 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004477 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004478
4479 // Check if we didn't match because of an implicit cast from a 'char'
4480 // or 'short' to an 'int'. This is done because printf is a varargs
4481 // function.
4482 if (ICE->getType() == S.Context.IntTy ||
4483 ICE->getType() == S.Context.UnsignedIntTy) {
4484 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004485 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004486 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004487 }
Jordan Rose98709982012-06-04 22:48:57 +00004488 }
Jordan Rose598ec092012-12-05 18:44:40 +00004489 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4490 // Special case for 'a', which has type 'int' in C.
4491 // Note, however, that we do /not/ want to treat multibyte constants like
4492 // 'MooV' as characters! This form is deprecated but still exists.
4493 if (ExprTy == S.Context.IntTy)
4494 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4495 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004496 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004497
Jordan Rosebc53ed12014-05-31 04:12:14 +00004498 // Look through enums to their underlying type.
4499 bool IsEnum = false;
4500 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4501 ExprTy = EnumTy->getDecl()->getIntegerType();
4502 IsEnum = true;
4503 }
4504
Jordan Rose0e5badd2012-12-05 18:44:49 +00004505 // %C in an Objective-C context prints a unichar, not a wchar_t.
4506 // If the argument is an integer of some kind, believe the %C and suggest
4507 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004508 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004509 if (ObjCContext &&
4510 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4511 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4512 !ExprTy->isCharType()) {
4513 // 'unichar' is defined as a typedef of unsigned short, but we should
4514 // prefer using the typedef if it is visible.
4515 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004516
4517 // While we are here, check if the value is an IntegerLiteral that happens
4518 // to be within the valid range.
4519 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4520 const llvm::APInt &V = IL->getValue();
4521 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4522 return true;
4523 }
4524
Jordan Rose0e5badd2012-12-05 18:44:49 +00004525 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4526 Sema::LookupOrdinaryName);
4527 if (S.LookupName(Result, S.getCurScope())) {
4528 NamedDecl *ND = Result.getFoundDecl();
4529 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4530 if (TD->getUnderlyingType() == IntendedTy)
4531 IntendedTy = S.Context.getTypedefType(TD);
4532 }
4533 }
4534 }
4535
4536 // Special-case some of Darwin's platform-independence types by suggesting
4537 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004538 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004539 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004540 QualType CastTy;
4541 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4542 if (!CastTy.isNull()) {
4543 IntendedTy = CastTy;
4544 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004545 }
4546 }
4547
Jordan Rose22b74712012-09-05 22:56:19 +00004548 // We may be able to offer a FixItHint if it is a supported type.
4549 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004550 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004551 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004552
Jordan Rose22b74712012-09-05 22:56:19 +00004553 if (success) {
4554 // Get the fix string from the fixed format specifier
4555 SmallString<16> buf;
4556 llvm::raw_svector_ostream os(buf);
4557 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004558
Jordan Roseaee34382012-09-05 22:56:26 +00004559 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4560
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004561 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004562 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4563 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4564 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4565 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004566 // In this case, the specifier is wrong and should be changed to match
4567 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004568 EmitFormatDiagnostic(S.PDiag(diag)
4569 << AT.getRepresentativeTypeName(S.Context)
4570 << IntendedTy << IsEnum << E->getSourceRange(),
4571 E->getLocStart(),
4572 /*IsStringLocation*/ false, SpecRange,
4573 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004574 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004575 // The canonical type for formatting this value is different from the
4576 // actual type of the expression. (This occurs, for example, with Darwin's
4577 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4578 // should be printed as 'long' for 64-bit compatibility.)
4579 // Rather than emitting a normal format/argument mismatch, we want to
4580 // add a cast to the recommended type (and correct the format string
4581 // if necessary).
4582 SmallString<16> CastBuf;
4583 llvm::raw_svector_ostream CastFix(CastBuf);
4584 CastFix << "(";
4585 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4586 CastFix << ")";
4587
4588 SmallVector<FixItHint,4> Hints;
4589 if (!AT.matchesType(S.Context, IntendedTy))
4590 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4591
4592 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4593 // If there's already a cast present, just replace it.
4594 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4595 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4596
4597 } else if (!requiresParensToAddCast(E)) {
4598 // If the expression has high enough precedence,
4599 // just write the C-style cast.
4600 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4601 CastFix.str()));
4602 } else {
4603 // Otherwise, add parens around the expression as well as the cast.
4604 CastFix << "(";
4605 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4606 CastFix.str()));
4607
Alp Tokerb6cc5922014-05-03 03:45:55 +00004608 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004609 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4610 }
4611
Jordan Rose0e5badd2012-12-05 18:44:49 +00004612 if (ShouldNotPrintDirectly) {
4613 // The expression has a type that should not be printed directly.
4614 // We extract the name from the typedef because we don't want to show
4615 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004616 StringRef Name;
4617 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4618 Name = TypedefTy->getDecl()->getName();
4619 else
4620 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004621 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004622 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004623 << E->getSourceRange(),
4624 E->getLocStart(), /*IsStringLocation=*/false,
4625 SpecRange, Hints);
4626 } else {
4627 // In this case, the expression could be printed using a different
4628 // specifier, but we've decided that the specifier is probably correct
4629 // and we should cast instead. Just use the normal warning message.
4630 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004631 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4632 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004633 << E->getSourceRange(),
4634 E->getLocStart(), /*IsStringLocation*/false,
4635 SpecRange, Hints);
4636 }
Jordan Roseaee34382012-09-05 22:56:26 +00004637 }
Jordan Rose22b74712012-09-05 22:56:19 +00004638 } else {
4639 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4640 SpecifierLen);
4641 // Since the warning for passing non-POD types to variadic functions
4642 // was deferred until now, we emit a warning for non-POD
4643 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004644 switch (S.isValidVarArgType(ExprTy)) {
4645 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004646 case Sema::VAK_ValidInCXX11: {
4647 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4648 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4649 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4650 }
Richard Smithd7293d72013-08-05 18:49:43 +00004651
Seth Cantrellb4802962015-03-04 03:12:10 +00004652 EmitFormatDiagnostic(
4653 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4654 << IsEnum << CSR << E->getSourceRange(),
4655 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4656 break;
4657 }
Richard Smithd7293d72013-08-05 18:49:43 +00004658 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004659 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004660 EmitFormatDiagnostic(
4661 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004662 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004663 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004664 << CallType
4665 << AT.getRepresentativeTypeName(S.Context)
4666 << CSR
4667 << E->getSourceRange(),
4668 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004669 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004670 break;
4671
4672 case Sema::VAK_Invalid:
4673 if (ExprTy->isObjCObjectType())
4674 EmitFormatDiagnostic(
4675 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4676 << S.getLangOpts().CPlusPlus11
4677 << ExprTy
4678 << CallType
4679 << AT.getRepresentativeTypeName(S.Context)
4680 << CSR
4681 << E->getSourceRange(),
4682 E->getLocStart(), /*IsStringLocation*/false, CSR);
4683 else
4684 // FIXME: If this is an initializer list, suggest removing the braces
4685 // or inserting a cast to the target type.
4686 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4687 << isa<InitListExpr>(E) << ExprTy << CallType
4688 << AT.getRepresentativeTypeName(S.Context)
4689 << E->getSourceRange();
4690 break;
4691 }
4692
4693 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4694 "format string specifier index out of range");
4695 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004696 }
4697
Ted Kremenekab278de2010-01-28 23:39:18 +00004698 return true;
4699}
4700
Ted Kremenek02087932010-07-16 02:11:22 +00004701//===--- CHECK: Scanf format string checking ------------------------------===//
4702
4703namespace {
4704class CheckScanfHandler : public CheckFormatHandler {
4705public:
4706 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4707 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004708 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004709 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004710 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004711 Sema::VariadicCallType CallType,
4712 llvm::SmallBitVector &CheckedVarArgs)
4713 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4714 numDataArgs, beg, hasVAListArg,
4715 Args, formatIdx, inFunctionCall, CallType,
4716 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004717 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004718
4719 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4720 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004721 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004722
4723 bool HandleInvalidScanfConversionSpecifier(
4724 const analyze_scanf::ScanfSpecifier &FS,
4725 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004726 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004727
Craig Toppere14c0f82014-03-12 04:55:44 +00004728 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004729};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004730} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004731
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004732void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4733 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004734 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4735 getLocationOfByte(end), /*IsStringLocation*/true,
4736 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004737}
4738
Ted Kremenekce815422010-07-19 21:25:57 +00004739bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4740 const analyze_scanf::ScanfSpecifier &FS,
4741 const char *startSpecifier,
4742 unsigned specifierLen) {
4743
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004744 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004745 FS.getConversionSpecifier();
4746
4747 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4748 getLocationOfByte(CS.getStart()),
4749 startSpecifier, specifierLen,
4750 CS.getStart(), CS.getLength());
4751}
4752
Ted Kremenek02087932010-07-16 02:11:22 +00004753bool CheckScanfHandler::HandleScanfSpecifier(
4754 const analyze_scanf::ScanfSpecifier &FS,
4755 const char *startSpecifier,
4756 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004757 using namespace analyze_scanf;
4758 using namespace analyze_format_string;
4759
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004760 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004761
Ted Kremenek6cd69422010-07-19 22:01:06 +00004762 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4763 // be used to decide if we are using positional arguments consistently.
4764 if (FS.consumesDataArgument()) {
4765 if (atFirstArg) {
4766 atFirstArg = false;
4767 usesPositionalArgs = FS.usesPositionalArg();
4768 }
4769 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004770 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4771 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004772 return false;
4773 }
Ted Kremenek02087932010-07-16 02:11:22 +00004774 }
4775
4776 // Check if the field with is non-zero.
4777 const OptionalAmount &Amt = FS.getFieldWidth();
4778 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4779 if (Amt.getConstantAmount() == 0) {
4780 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4781 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004782 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4783 getLocationOfByte(Amt.getStart()),
4784 /*IsStringLocation*/true, R,
4785 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004786 }
4787 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004788
Ted Kremenek02087932010-07-16 02:11:22 +00004789 if (!FS.consumesDataArgument()) {
4790 // FIXME: Technically specifying a precision or field width here
4791 // makes no sense. Worth issuing a warning at some point.
4792 return true;
4793 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004794
Ted Kremenek02087932010-07-16 02:11:22 +00004795 // Consume the argument.
4796 unsigned argIndex = FS.getArgIndex();
4797 if (argIndex < NumDataArgs) {
4798 // The check to see if the argIndex is valid will come later.
4799 // We set the bit here because we may exit early from this
4800 // function if we encounter some other error.
4801 CoveredArgs.set(argIndex);
4802 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004803
Ted Kremenek4407ea42010-07-20 20:04:47 +00004804 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004805 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004806 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4807 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004808 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004809 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004810 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004811 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4812 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004813
Jordan Rose92303592012-09-08 04:00:03 +00004814 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4815 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4816
Ted Kremenek02087932010-07-16 02:11:22 +00004817 // The remaining checks depend on the data arguments.
4818 if (HasVAListArg)
4819 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004820
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004821 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004822 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004823
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004824 // Check that the argument type matches the format specifier.
4825 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004826 if (!Ex)
4827 return true;
4828
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004829 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004830
4831 if (!AT.isValid()) {
4832 return true;
4833 }
4834
Seth Cantrellb4802962015-03-04 03:12:10 +00004835 analyze_format_string::ArgType::MatchKind match =
4836 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004837 if (match == analyze_format_string::ArgType::Match) {
4838 return true;
4839 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004840
Seth Cantrell79340072015-03-04 05:58:08 +00004841 ScanfSpecifier fixedFS = FS;
4842 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4843 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004844
Seth Cantrell79340072015-03-04 05:58:08 +00004845 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4846 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4847 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4848 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004849
Seth Cantrell79340072015-03-04 05:58:08 +00004850 if (success) {
4851 // Get the fix string from the fixed format specifier.
4852 SmallString<128> buf;
4853 llvm::raw_svector_ostream os(buf);
4854 fixedFS.toString(os);
4855
4856 EmitFormatDiagnostic(
4857 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4858 << Ex->getType() << false << Ex->getSourceRange(),
4859 Ex->getLocStart(),
4860 /*IsStringLocation*/ false,
4861 getSpecifierRange(startSpecifier, specifierLen),
4862 FixItHint::CreateReplacement(
4863 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4864 } else {
4865 EmitFormatDiagnostic(S.PDiag(diag)
4866 << AT.getRepresentativeTypeName(S.Context)
4867 << Ex->getType() << false << Ex->getSourceRange(),
4868 Ex->getLocStart(),
4869 /*IsStringLocation*/ false,
4870 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004871 }
4872
Ted Kremenek02087932010-07-16 02:11:22 +00004873 return true;
4874}
4875
4876void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004877 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004878 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004879 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004880 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004881 bool inFunctionCall, VariadicCallType CallType,
4882 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenekab278de2010-01-28 23:39:18 +00004883 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004884 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004885 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004886 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004887 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4888 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004889 return;
4890 }
Ted Kremenek02087932010-07-16 02:11:22 +00004891
Ted Kremenekab278de2010-01-28 23:39:18 +00004892 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004893 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004894 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004895 // Account for cases where the string literal is truncated in a declaration.
4896 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4897 assert(T && "String literal not of constant array type!");
4898 size_t TypeSize = T->getSize().getZExtValue();
4899 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004900 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004901
4902 // Emit a warning if the string literal is truncated and does not contain an
4903 // embedded null character.
4904 if (TypeSize <= StrRef.size() &&
4905 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4906 CheckFormatHandler::EmitFormatDiagnostic(
4907 *this, inFunctionCall, Args[format_idx],
4908 PDiag(diag::warn_printf_format_string_not_null_terminated),
4909 FExpr->getLocStart(),
4910 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4911 return;
4912 }
4913
Ted Kremenekab278de2010-01-28 23:39:18 +00004914 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004915 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004916 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004917 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004918 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4919 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004920 return;
4921 }
Ted Kremenek02087932010-07-16 02:11:22 +00004922
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004923 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004924 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004925 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004926 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004927 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004928 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004929
Hans Wennborg23926bd2011-12-15 10:25:47 +00004930 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004931 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004932 Context.getTargetInfo(),
4933 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004934 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004935 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004936 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004937 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004938 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004939
Hans Wennborg23926bd2011-12-15 10:25:47 +00004940 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004941 getLangOpts(),
4942 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004943 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004944 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004945}
4946
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004947bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4948 // Str - The format string. NOTE: this is NOT null-terminated!
4949 StringRef StrRef = FExpr->getString();
4950 const char *Str = StrRef.data();
4951 // Account for cases where the string literal is truncated in a declaration.
4952 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4953 assert(T && "String literal not of constant array type!");
4954 size_t TypeSize = T->getSize().getZExtValue();
4955 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4956 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4957 getLangOpts(),
4958 Context.getTargetInfo());
4959}
4960
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004961//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4962
4963// Returns the related absolute value function that is larger, of 0 if one
4964// does not exist.
4965static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4966 switch (AbsFunction) {
4967 default:
4968 return 0;
4969
4970 case Builtin::BI__builtin_abs:
4971 return Builtin::BI__builtin_labs;
4972 case Builtin::BI__builtin_labs:
4973 return Builtin::BI__builtin_llabs;
4974 case Builtin::BI__builtin_llabs:
4975 return 0;
4976
4977 case Builtin::BI__builtin_fabsf:
4978 return Builtin::BI__builtin_fabs;
4979 case Builtin::BI__builtin_fabs:
4980 return Builtin::BI__builtin_fabsl;
4981 case Builtin::BI__builtin_fabsl:
4982 return 0;
4983
4984 case Builtin::BI__builtin_cabsf:
4985 return Builtin::BI__builtin_cabs;
4986 case Builtin::BI__builtin_cabs:
4987 return Builtin::BI__builtin_cabsl;
4988 case Builtin::BI__builtin_cabsl:
4989 return 0;
4990
4991 case Builtin::BIabs:
4992 return Builtin::BIlabs;
4993 case Builtin::BIlabs:
4994 return Builtin::BIllabs;
4995 case Builtin::BIllabs:
4996 return 0;
4997
4998 case Builtin::BIfabsf:
4999 return Builtin::BIfabs;
5000 case Builtin::BIfabs:
5001 return Builtin::BIfabsl;
5002 case Builtin::BIfabsl:
5003 return 0;
5004
5005 case Builtin::BIcabsf:
5006 return Builtin::BIcabs;
5007 case Builtin::BIcabs:
5008 return Builtin::BIcabsl;
5009 case Builtin::BIcabsl:
5010 return 0;
5011 }
5012}
5013
5014// Returns the argument type of the absolute value function.
5015static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5016 unsigned AbsType) {
5017 if (AbsType == 0)
5018 return QualType();
5019
5020 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5021 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5022 if (Error != ASTContext::GE_None)
5023 return QualType();
5024
5025 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5026 if (!FT)
5027 return QualType();
5028
5029 if (FT->getNumParams() != 1)
5030 return QualType();
5031
5032 return FT->getParamType(0);
5033}
5034
5035// Returns the best absolute value function, or zero, based on type and
5036// current absolute value function.
5037static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5038 unsigned AbsFunctionKind) {
5039 unsigned BestKind = 0;
5040 uint64_t ArgSize = Context.getTypeSize(ArgType);
5041 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5042 Kind = getLargerAbsoluteValueFunction(Kind)) {
5043 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5044 if (Context.getTypeSize(ParamType) >= ArgSize) {
5045 if (BestKind == 0)
5046 BestKind = Kind;
5047 else if (Context.hasSameType(ParamType, ArgType)) {
5048 BestKind = Kind;
5049 break;
5050 }
5051 }
5052 }
5053 return BestKind;
5054}
5055
5056enum AbsoluteValueKind {
5057 AVK_Integer,
5058 AVK_Floating,
5059 AVK_Complex
5060};
5061
5062static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5063 if (T->isIntegralOrEnumerationType())
5064 return AVK_Integer;
5065 if (T->isRealFloatingType())
5066 return AVK_Floating;
5067 if (T->isAnyComplexType())
5068 return AVK_Complex;
5069
5070 llvm_unreachable("Type not integer, floating, or complex");
5071}
5072
5073// Changes the absolute value function to a different type. Preserves whether
5074// the function is a builtin.
5075static unsigned changeAbsFunction(unsigned AbsKind,
5076 AbsoluteValueKind ValueKind) {
5077 switch (ValueKind) {
5078 case AVK_Integer:
5079 switch (AbsKind) {
5080 default:
5081 return 0;
5082 case Builtin::BI__builtin_fabsf:
5083 case Builtin::BI__builtin_fabs:
5084 case Builtin::BI__builtin_fabsl:
5085 case Builtin::BI__builtin_cabsf:
5086 case Builtin::BI__builtin_cabs:
5087 case Builtin::BI__builtin_cabsl:
5088 return Builtin::BI__builtin_abs;
5089 case Builtin::BIfabsf:
5090 case Builtin::BIfabs:
5091 case Builtin::BIfabsl:
5092 case Builtin::BIcabsf:
5093 case Builtin::BIcabs:
5094 case Builtin::BIcabsl:
5095 return Builtin::BIabs;
5096 }
5097 case AVK_Floating:
5098 switch (AbsKind) {
5099 default:
5100 return 0;
5101 case Builtin::BI__builtin_abs:
5102 case Builtin::BI__builtin_labs:
5103 case Builtin::BI__builtin_llabs:
5104 case Builtin::BI__builtin_cabsf:
5105 case Builtin::BI__builtin_cabs:
5106 case Builtin::BI__builtin_cabsl:
5107 return Builtin::BI__builtin_fabsf;
5108 case Builtin::BIabs:
5109 case Builtin::BIlabs:
5110 case Builtin::BIllabs:
5111 case Builtin::BIcabsf:
5112 case Builtin::BIcabs:
5113 case Builtin::BIcabsl:
5114 return Builtin::BIfabsf;
5115 }
5116 case AVK_Complex:
5117 switch (AbsKind) {
5118 default:
5119 return 0;
5120 case Builtin::BI__builtin_abs:
5121 case Builtin::BI__builtin_labs:
5122 case Builtin::BI__builtin_llabs:
5123 case Builtin::BI__builtin_fabsf:
5124 case Builtin::BI__builtin_fabs:
5125 case Builtin::BI__builtin_fabsl:
5126 return Builtin::BI__builtin_cabsf;
5127 case Builtin::BIabs:
5128 case Builtin::BIlabs:
5129 case Builtin::BIllabs:
5130 case Builtin::BIfabsf:
5131 case Builtin::BIfabs:
5132 case Builtin::BIfabsl:
5133 return Builtin::BIcabsf;
5134 }
5135 }
5136 llvm_unreachable("Unable to convert function");
5137}
5138
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005139static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005140 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5141 if (!FnInfo)
5142 return 0;
5143
5144 switch (FDecl->getBuiltinID()) {
5145 default:
5146 return 0;
5147 case Builtin::BI__builtin_abs:
5148 case Builtin::BI__builtin_fabs:
5149 case Builtin::BI__builtin_fabsf:
5150 case Builtin::BI__builtin_fabsl:
5151 case Builtin::BI__builtin_labs:
5152 case Builtin::BI__builtin_llabs:
5153 case Builtin::BI__builtin_cabs:
5154 case Builtin::BI__builtin_cabsf:
5155 case Builtin::BI__builtin_cabsl:
5156 case Builtin::BIabs:
5157 case Builtin::BIlabs:
5158 case Builtin::BIllabs:
5159 case Builtin::BIfabs:
5160 case Builtin::BIfabsf:
5161 case Builtin::BIfabsl:
5162 case Builtin::BIcabs:
5163 case Builtin::BIcabsf:
5164 case Builtin::BIcabsl:
5165 return FDecl->getBuiltinID();
5166 }
5167 llvm_unreachable("Unknown Builtin type");
5168}
5169
5170// If the replacement is valid, emit a note with replacement function.
5171// Additionally, suggest including the proper header if not already included.
5172static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005173 unsigned AbsKind, QualType ArgType) {
5174 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005175 const char *HeaderName = nullptr;
5176 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005177 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5178 FunctionName = "std::abs";
5179 if (ArgType->isIntegralOrEnumerationType()) {
5180 HeaderName = "cstdlib";
5181 } else if (ArgType->isRealFloatingType()) {
5182 HeaderName = "cmath";
5183 } else {
5184 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005185 }
Richard Trieubeffb832014-04-15 23:47:53 +00005186
5187 // Lookup all std::abs
5188 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005189 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005190 R.suppressDiagnostics();
5191 S.LookupQualifiedName(R, Std);
5192
5193 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005194 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005195 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5196 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5197 } else {
5198 FDecl = dyn_cast<FunctionDecl>(I);
5199 }
5200 if (!FDecl)
5201 continue;
5202
5203 // Found std::abs(), check that they are the right ones.
5204 if (FDecl->getNumParams() != 1)
5205 continue;
5206
5207 // Check that the parameter type can handle the argument.
5208 QualType ParamType = FDecl->getParamDecl(0)->getType();
5209 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5210 S.Context.getTypeSize(ArgType) <=
5211 S.Context.getTypeSize(ParamType)) {
5212 // Found a function, don't need the header hint.
5213 EmitHeaderHint = false;
5214 break;
5215 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005216 }
Richard Trieubeffb832014-04-15 23:47:53 +00005217 }
5218 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005219 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005220 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5221
5222 if (HeaderName) {
5223 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5224 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5225 R.suppressDiagnostics();
5226 S.LookupName(R, S.getCurScope());
5227
5228 if (R.isSingleResult()) {
5229 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5230 if (FD && FD->getBuiltinID() == AbsKind) {
5231 EmitHeaderHint = false;
5232 } else {
5233 return;
5234 }
5235 } else if (!R.empty()) {
5236 return;
5237 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005238 }
5239 }
5240
5241 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005242 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005243
Richard Trieubeffb832014-04-15 23:47:53 +00005244 if (!HeaderName)
5245 return;
5246
5247 if (!EmitHeaderHint)
5248 return;
5249
Alp Toker5d96e0a2014-07-11 20:53:51 +00005250 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5251 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005252}
5253
5254static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5255 if (!FDecl)
5256 return false;
5257
5258 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5259 return false;
5260
5261 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5262
5263 while (ND && ND->isInlineNamespace()) {
5264 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005265 }
Richard Trieubeffb832014-04-15 23:47:53 +00005266
5267 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5268 return false;
5269
5270 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5271 return false;
5272
5273 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005274}
5275
5276// Warn when using the wrong abs() function.
5277void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5278 const FunctionDecl *FDecl,
5279 IdentifierInfo *FnInfo) {
5280 if (Call->getNumArgs() != 1)
5281 return;
5282
5283 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005284 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5285 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005286 return;
5287
5288 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5289 QualType ParamType = Call->getArg(0)->getType();
5290
Alp Toker5d96e0a2014-07-11 20:53:51 +00005291 // Unsigned types cannot be negative. Suggest removing the absolute value
5292 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005293 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005294 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005295 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005296 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5297 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005298 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005299 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5300 return;
5301 }
5302
David Majnemer7f77eb92015-11-15 03:04:34 +00005303 // Taking the absolute value of a pointer is very suspicious, they probably
5304 // wanted to index into an array, dereference a pointer, call a function, etc.
5305 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5306 unsigned DiagType = 0;
5307 if (ArgType->isFunctionType())
5308 DiagType = 1;
5309 else if (ArgType->isArrayType())
5310 DiagType = 2;
5311
5312 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5313 return;
5314 }
5315
Richard Trieubeffb832014-04-15 23:47:53 +00005316 // std::abs has overloads which prevent most of the absolute value problems
5317 // from occurring.
5318 if (IsStdAbs)
5319 return;
5320
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005321 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5322 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5323
5324 // The argument and parameter are the same kind. Check if they are the right
5325 // size.
5326 if (ArgValueKind == ParamValueKind) {
5327 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5328 return;
5329
5330 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5331 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5332 << FDecl << ArgType << ParamType;
5333
5334 if (NewAbsKind == 0)
5335 return;
5336
5337 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005338 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005339 return;
5340 }
5341
5342 // ArgValueKind != ParamValueKind
5343 // The wrong type of absolute value function was used. Attempt to find the
5344 // proper one.
5345 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5346 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5347 if (NewAbsKind == 0)
5348 return;
5349
5350 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5351 << FDecl << ParamValueKind << ArgValueKind;
5352
5353 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005354 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005355}
5356
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005357//===--- CHECK: Standard memory functions ---------------------------------===//
5358
Nico Weber0e6daef2013-12-26 23:38:39 +00005359/// \brief Takes the expression passed to the size_t parameter of functions
5360/// such as memcmp, strncat, etc and warns if it's a comparison.
5361///
5362/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5363static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5364 IdentifierInfo *FnName,
5365 SourceLocation FnLoc,
5366 SourceLocation RParenLoc) {
5367 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5368 if (!Size)
5369 return false;
5370
5371 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5372 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5373 return false;
5374
Nico Weber0e6daef2013-12-26 23:38:39 +00005375 SourceRange SizeRange = Size->getSourceRange();
5376 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5377 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005378 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005379 << FnName << FixItHint::CreateInsertion(
5380 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005381 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005382 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005383 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005384 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5385 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005386
5387 return true;
5388}
5389
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005390/// \brief Determine whether the given type is or contains a dynamic class type
5391/// (e.g., whether it has a vtable).
5392static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5393 bool &IsContained) {
5394 // Look through array types while ignoring qualifiers.
5395 const Type *Ty = T->getBaseElementTypeUnsafe();
5396 IsContained = false;
5397
5398 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5399 RD = RD ? RD->getDefinition() : nullptr;
5400 if (!RD)
5401 return nullptr;
5402
5403 if (RD->isDynamicClass())
5404 return RD;
5405
5406 // Check all the fields. If any bases were dynamic, the class is dynamic.
5407 // It's impossible for a class to transitively contain itself by value, so
5408 // infinite recursion is impossible.
5409 for (auto *FD : RD->fields()) {
5410 bool SubContained;
5411 if (const CXXRecordDecl *ContainedRD =
5412 getContainedDynamicClass(FD->getType(), SubContained)) {
5413 IsContained = true;
5414 return ContainedRD;
5415 }
5416 }
5417
5418 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005419}
5420
Chandler Carruth889ed862011-06-21 23:04:20 +00005421/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005422/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005423static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005424 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005425 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5426 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5427 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005428
Craig Topperc3ec1492014-05-26 06:22:03 +00005429 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005430}
5431
Chandler Carruth889ed862011-06-21 23:04:20 +00005432/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005433static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005434 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5435 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5436 if (SizeOf->getKind() == clang::UETT_SizeOf)
5437 return SizeOf->getTypeOfArgument();
5438
5439 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005440}
5441
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005442/// \brief Check for dangerous or invalid arguments to memset().
5443///
Chandler Carruthac687262011-06-03 06:23:57 +00005444/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005445/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5446/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005447///
5448/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005449void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005450 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005451 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005452 assert(BId != 0);
5453
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005454 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005455 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005456 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005457 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005458 return;
5459
Anna Zaks22122702012-01-17 00:37:07 +00005460 unsigned LastArg = (BId == Builtin::BImemset ||
5461 BId == Builtin::BIstrndup ? 1 : 2);
5462 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005463 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005464
Nico Weber0e6daef2013-12-26 23:38:39 +00005465 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5466 Call->getLocStart(), Call->getRParenLoc()))
5467 return;
5468
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005469 // We have special checking when the length is a sizeof expression.
5470 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5471 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5472 llvm::FoldingSetNodeID SizeOfArgID;
5473
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005474 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5475 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005476 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005477
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005478 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005479 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005480 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005481 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005482
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005483 // Never warn about void type pointers. This can be used to suppress
5484 // false positives.
5485 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005486 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005487
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005488 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5489 // actually comparing the expressions for equality. Because computing the
5490 // expression IDs can be expensive, we only do this if the diagnostic is
5491 // enabled.
5492 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005493 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5494 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005495 // We only compute IDs for expressions if the warning is enabled, and
5496 // cache the sizeof arg's ID.
5497 if (SizeOfArgID == llvm::FoldingSetNodeID())
5498 SizeOfArg->Profile(SizeOfArgID, Context, true);
5499 llvm::FoldingSetNodeID DestID;
5500 Dest->Profile(DestID, Context, true);
5501 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005502 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5503 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005504 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005505 StringRef ReadableName = FnName->getName();
5506
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005507 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005508 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005509 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005510 if (!PointeeTy->isIncompleteType() &&
5511 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005512 ActionIdx = 2; // If the pointee's size is sizeof(char),
5513 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005514
5515 // If the function is defined as a builtin macro, do not show macro
5516 // expansion.
5517 SourceLocation SL = SizeOfArg->getExprLoc();
5518 SourceRange DSR = Dest->getSourceRange();
5519 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005520 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005521
5522 if (SM.isMacroArgExpansion(SL)) {
5523 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5524 SL = SM.getSpellingLoc(SL);
5525 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5526 SM.getSpellingLoc(DSR.getEnd()));
5527 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5528 SM.getSpellingLoc(SSR.getEnd()));
5529 }
5530
Anna Zaksd08d9152012-05-30 23:14:52 +00005531 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005532 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005533 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005534 << PointeeTy
5535 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005536 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005537 << SSR);
5538 DiagRuntimeBehavior(SL, SizeOfArg,
5539 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5540 << ActionIdx
5541 << SSR);
5542
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005543 break;
5544 }
5545 }
5546
5547 // Also check for cases where the sizeof argument is the exact same
5548 // type as the memory argument, and where it points to a user-defined
5549 // record type.
5550 if (SizeOfArgTy != QualType()) {
5551 if (PointeeTy->isRecordType() &&
5552 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5553 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5554 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5555 << FnName << SizeOfArgTy << ArgIdx
5556 << PointeeTy << Dest->getSourceRange()
5557 << LenExpr->getSourceRange());
5558 break;
5559 }
Nico Weberc5e73862011-06-14 16:14:58 +00005560 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005561 } else if (DestTy->isArrayType()) {
5562 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005563 }
Nico Weberc5e73862011-06-14 16:14:58 +00005564
Nico Weberc44b35e2015-03-21 17:37:46 +00005565 if (PointeeTy == QualType())
5566 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005567
Nico Weberc44b35e2015-03-21 17:37:46 +00005568 // Always complain about dynamic classes.
5569 bool IsContained;
5570 if (const CXXRecordDecl *ContainedRD =
5571 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005572
Nico Weberc44b35e2015-03-21 17:37:46 +00005573 unsigned OperationType = 0;
5574 // "overwritten" if we're warning about the destination for any call
5575 // but memcmp; otherwise a verb appropriate to the call.
5576 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5577 if (BId == Builtin::BImemcpy)
5578 OperationType = 1;
5579 else if(BId == Builtin::BImemmove)
5580 OperationType = 2;
5581 else if (BId == Builtin::BImemcmp)
5582 OperationType = 3;
5583 }
5584
John McCall31168b02011-06-15 23:02:42 +00005585 DiagRuntimeBehavior(
5586 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005587 PDiag(diag::warn_dyn_class_memaccess)
5588 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5589 << FnName << IsContained << ContainedRD << OperationType
5590 << Call->getCallee()->getSourceRange());
5591 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5592 BId != Builtin::BImemset)
5593 DiagRuntimeBehavior(
5594 Dest->getExprLoc(), Dest,
5595 PDiag(diag::warn_arc_object_memaccess)
5596 << ArgIdx << FnName << PointeeTy
5597 << Call->getCallee()->getSourceRange());
5598 else
5599 continue;
5600
5601 DiagRuntimeBehavior(
5602 Dest->getExprLoc(), Dest,
5603 PDiag(diag::note_bad_memaccess_silence)
5604 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5605 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005606 }
5607}
5608
Ted Kremenek6865f772011-08-18 20:55:45 +00005609// A little helper routine: ignore addition and subtraction of integer literals.
5610// This intentionally does not ignore all integer constant expressions because
5611// we don't want to remove sizeof().
5612static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5613 Ex = Ex->IgnoreParenCasts();
5614
5615 for (;;) {
5616 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5617 if (!BO || !BO->isAdditiveOp())
5618 break;
5619
5620 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5621 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5622
5623 if (isa<IntegerLiteral>(RHS))
5624 Ex = LHS;
5625 else if (isa<IntegerLiteral>(LHS))
5626 Ex = RHS;
5627 else
5628 break;
5629 }
5630
5631 return Ex;
5632}
5633
Anna Zaks13b08572012-08-08 21:42:23 +00005634static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5635 ASTContext &Context) {
5636 // Only handle constant-sized or VLAs, but not flexible members.
5637 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5638 // Only issue the FIXIT for arrays of size > 1.
5639 if (CAT->getSize().getSExtValue() <= 1)
5640 return false;
5641 } else if (!Ty->isVariableArrayType()) {
5642 return false;
5643 }
5644 return true;
5645}
5646
Ted Kremenek6865f772011-08-18 20:55:45 +00005647// Warn if the user has made the 'size' argument to strlcpy or strlcat
5648// be the size of the source, instead of the destination.
5649void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5650 IdentifierInfo *FnName) {
5651
5652 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005653 unsigned NumArgs = Call->getNumArgs();
5654 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005655 return;
5656
5657 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5658 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005659 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005660
5661 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5662 Call->getLocStart(), Call->getRParenLoc()))
5663 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005664
5665 // Look for 'strlcpy(dst, x, sizeof(x))'
5666 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5667 CompareWithSrc = Ex;
5668 else {
5669 // Look for 'strlcpy(dst, x, strlen(x))'
5670 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005671 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5672 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005673 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5674 }
5675 }
5676
5677 if (!CompareWithSrc)
5678 return;
5679
5680 // Determine if the argument to sizeof/strlen is equal to the source
5681 // argument. In principle there's all kinds of things you could do
5682 // here, for instance creating an == expression and evaluating it with
5683 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5684 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5685 if (!SrcArgDRE)
5686 return;
5687
5688 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5689 if (!CompareWithSrcDRE ||
5690 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5691 return;
5692
5693 const Expr *OriginalSizeArg = Call->getArg(2);
5694 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5695 << OriginalSizeArg->getSourceRange() << FnName;
5696
5697 // Output a FIXIT hint if the destination is an array (rather than a
5698 // pointer to an array). This could be enhanced to handle some
5699 // pointers if we know the actual size, like if DstArg is 'array+2'
5700 // we could say 'sizeof(array)-2'.
5701 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005702 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005703 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005704
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005705 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005706 llvm::raw_svector_ostream OS(sizeString);
5707 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005708 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005709 OS << ")";
5710
5711 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5712 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5713 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005714}
5715
Anna Zaks314cd092012-02-01 19:08:57 +00005716/// Check if two expressions refer to the same declaration.
5717static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5718 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5719 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5720 return D1->getDecl() == D2->getDecl();
5721 return false;
5722}
5723
5724static const Expr *getStrlenExprArg(const Expr *E) {
5725 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5726 const FunctionDecl *FD = CE->getDirectCallee();
5727 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005728 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005729 return CE->getArg(0)->IgnoreParenCasts();
5730 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005731 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005732}
5733
5734// Warn on anti-patterns as the 'size' argument to strncat.
5735// The correct size argument should look like following:
5736// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5737void Sema::CheckStrncatArguments(const CallExpr *CE,
5738 IdentifierInfo *FnName) {
5739 // Don't crash if the user has the wrong number of arguments.
5740 if (CE->getNumArgs() < 3)
5741 return;
5742 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5743 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5744 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5745
Nico Weber0e6daef2013-12-26 23:38:39 +00005746 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5747 CE->getRParenLoc()))
5748 return;
5749
Anna Zaks314cd092012-02-01 19:08:57 +00005750 // Identify common expressions, which are wrongly used as the size argument
5751 // to strncat and may lead to buffer overflows.
5752 unsigned PatternType = 0;
5753 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5754 // - sizeof(dst)
5755 if (referToTheSameDecl(SizeOfArg, DstArg))
5756 PatternType = 1;
5757 // - sizeof(src)
5758 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5759 PatternType = 2;
5760 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5761 if (BE->getOpcode() == BO_Sub) {
5762 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5763 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5764 // - sizeof(dst) - strlen(dst)
5765 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5766 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5767 PatternType = 1;
5768 // - sizeof(src) - (anything)
5769 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5770 PatternType = 2;
5771 }
5772 }
5773
5774 if (PatternType == 0)
5775 return;
5776
Anna Zaks5069aa32012-02-03 01:27:37 +00005777 // Generate the diagnostic.
5778 SourceLocation SL = LenArg->getLocStart();
5779 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005780 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005781
5782 // If the function is defined as a builtin macro, do not show macro expansion.
5783 if (SM.isMacroArgExpansion(SL)) {
5784 SL = SM.getSpellingLoc(SL);
5785 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5786 SM.getSpellingLoc(SR.getEnd()));
5787 }
5788
Anna Zaks13b08572012-08-08 21:42:23 +00005789 // Check if the destination is an array (rather than a pointer to an array).
5790 QualType DstTy = DstArg->getType();
5791 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5792 Context);
5793 if (!isKnownSizeArray) {
5794 if (PatternType == 1)
5795 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5796 else
5797 Diag(SL, diag::warn_strncat_src_size) << SR;
5798 return;
5799 }
5800
Anna Zaks314cd092012-02-01 19:08:57 +00005801 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005802 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005803 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005804 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005805
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005806 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005807 llvm::raw_svector_ostream OS(sizeString);
5808 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005809 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005810 OS << ") - ";
5811 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005812 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005813 OS << ") - 1";
5814
Anna Zaks5069aa32012-02-03 01:27:37 +00005815 Diag(SL, diag::note_strncat_wrong_size)
5816 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005817}
5818
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005819//===--- CHECK: Return Address of Stack Variable --------------------------===//
5820
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005821static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5822 Decl *ParentDecl);
5823static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5824 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005825
5826/// CheckReturnStackAddr - Check if a return statement returns the address
5827/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005828static void
5829CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5830 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005831
Craig Topperc3ec1492014-05-26 06:22:03 +00005832 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005833 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005834
5835 // Perform checking for returned stack addresses, local blocks,
5836 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005837 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005838 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005839 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005840 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005841 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005842 }
5843
Craig Topperc3ec1492014-05-26 06:22:03 +00005844 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005845 return; // Nothing suspicious was found.
5846
5847 SourceLocation diagLoc;
5848 SourceRange diagRange;
5849 if (refVars.empty()) {
5850 diagLoc = stackE->getLocStart();
5851 diagRange = stackE->getSourceRange();
5852 } else {
5853 // We followed through a reference variable. 'stackE' contains the
5854 // problematic expression but we will warn at the return statement pointing
5855 // at the reference variable. We will later display the "trail" of
5856 // reference variables using notes.
5857 diagLoc = refVars[0]->getLocStart();
5858 diagRange = refVars[0]->getSourceRange();
5859 }
5860
5861 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Craig Topperda7b27f2015-11-17 05:40:09 +00005862 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005863 << DR->getDecl()->getDeclName() << diagRange;
5864 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005865 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005866 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005867 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005868 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005869 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5870 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005871 }
5872
5873 // Display the "trail" of reference variables that we followed until we
5874 // found the problematic expression using notes.
5875 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5876 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5877 // If this var binds to another reference var, show the range of the next
5878 // var, otherwise the var binds to the problematic expression, in which case
5879 // show the range of the expression.
5880 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5881 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005882 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5883 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005884 }
5885}
5886
5887/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5888/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005889/// to a location on the stack, a local block, an address of a label, or a
5890/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005891/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005892/// encounter a subexpression that (1) clearly does not lead to one of the
5893/// above problematic expressions (2) is something we cannot determine leads to
5894/// a problematic expression based on such local checking.
5895///
5896/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5897/// the expression that they point to. Such variables are added to the
5898/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005899///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005900/// EvalAddr processes expressions that are pointers that are used as
5901/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005902/// At the base case of the recursion is a check for the above problematic
5903/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005904///
5905/// This implementation handles:
5906///
5907/// * pointer-to-pointer casts
5908/// * implicit conversions from array references to pointers
5909/// * taking the address of fields
5910/// * arbitrary interplay between "&" and "*" operators
5911/// * pointer arithmetic from an address of a stack variable
5912/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005913static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5914 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005915 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005916 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005917
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005918 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005919 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005920 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005921 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005922 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005923
Peter Collingbourne91147592011-04-15 00:35:48 +00005924 E = E->IgnoreParens();
5925
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005926 // Our "symbolic interpreter" is just a dispatch off the currently
5927 // viewed AST node. We then recursively traverse the AST by calling
5928 // EvalAddr and EvalVal appropriately.
5929 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005930 case Stmt::DeclRefExprClass: {
5931 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5932
Richard Smith40f08eb2014-01-30 22:05:38 +00005933 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005934 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005935 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005936
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005937 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5938 // If this is a reference variable, follow through to the expression that
5939 // it points to.
5940 if (V->hasLocalStorage() &&
5941 V->getType()->isReferenceType() && V->hasInit()) {
5942 // Add the reference variable to the "trail".
5943 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005944 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005945 }
5946
Craig Topperc3ec1492014-05-26 06:22:03 +00005947 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005948 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005949
Chris Lattner934edb22007-12-28 05:31:15 +00005950 case Stmt::UnaryOperatorClass: {
5951 // The only unary operator that make sense to handle here
5952 // is AddrOf. All others don't make sense as pointers.
5953 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005954
John McCalle3027922010-08-25 11:45:40 +00005955 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005956 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005957 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005958 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005959 }
Mike Stump11289f42009-09-09 15:08:12 +00005960
Chris Lattner934edb22007-12-28 05:31:15 +00005961 case Stmt::BinaryOperatorClass: {
5962 // Handle pointer arithmetic. All other binary operators are not valid
5963 // in this context.
5964 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005965 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005966
John McCalle3027922010-08-25 11:45:40 +00005967 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005968 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005969
Chris Lattner934edb22007-12-28 05:31:15 +00005970 Expr *Base = B->getLHS();
5971
5972 // Determine which argument is the real pointer base. It could be
5973 // the RHS argument instead of the LHS.
5974 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005975
Chris Lattner934edb22007-12-28 05:31:15 +00005976 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005977 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005978 }
Steve Naroff2752a172008-09-10 19:17:48 +00005979
Chris Lattner934edb22007-12-28 05:31:15 +00005980 // For conditional operators we need to see if either the LHS or RHS are
5981 // valid DeclRefExpr*s. If one of them is valid, we return it.
5982 case Stmt::ConditionalOperatorClass: {
5983 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005984
Chris Lattner934edb22007-12-28 05:31:15 +00005985 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005986 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5987 if (Expr *LHSExpr = C->getLHS()) {
5988 // In C++, we can have a throw-expression, which has 'void' type.
5989 if (!LHSExpr->getType()->isVoidType())
5990 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005991 return LHS;
5992 }
Chris Lattner934edb22007-12-28 05:31:15 +00005993
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005994 // In C++, we can have a throw-expression, which has 'void' type.
5995 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005996 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005997
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005998 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005999 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006000
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006001 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006002 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006003 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006004 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006005
6006 case Stmt::AddrLabelExprClass:
6007 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006008
John McCall28fc7092011-11-10 05:35:25 +00006009 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006010 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6011 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006012
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006013 // For casts, we need to handle conversions from arrays to
6014 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006015 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006016 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006017 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006018 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006019 case Stmt::CXXStaticCastExprClass:
6020 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006021 case Stmt::CXXConstCastExprClass:
6022 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00006023 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
6024 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006025 case CK_LValueToRValue:
6026 case CK_NoOp:
6027 case CK_BaseToDerived:
6028 case CK_DerivedToBase:
6029 case CK_UncheckedDerivedToBase:
6030 case CK_Dynamic:
6031 case CK_CPointerToObjCPointerCast:
6032 case CK_BlockPointerToObjCPointerCast:
6033 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006034 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006035
6036 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006037 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006038
Richard Trieudadefde2014-07-02 04:39:38 +00006039 case CK_BitCast:
6040 if (SubExpr->getType()->isAnyPointerType() ||
6041 SubExpr->getType()->isBlockPointerType() ||
6042 SubExpr->getType()->isObjCQualifiedIdType())
6043 return EvalAddr(SubExpr, refVars, ParentDecl);
6044 else
6045 return nullptr;
6046
Eli Friedman8195ad72012-02-23 23:04:32 +00006047 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006048 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006049 }
Chris Lattner934edb22007-12-28 05:31:15 +00006050 }
Mike Stump11289f42009-09-09 15:08:12 +00006051
Douglas Gregorfe314812011-06-21 17:03:29 +00006052 case Stmt::MaterializeTemporaryExprClass:
6053 if (Expr *Result = EvalAddr(
6054 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006055 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006056 return Result;
6057
6058 return E;
6059
Chris Lattner934edb22007-12-28 05:31:15 +00006060 // Everything else: we simply don't reason about them.
6061 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006062 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006063 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006064}
Mike Stump11289f42009-09-09 15:08:12 +00006065
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006066/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6067/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006068static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
6069 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00006070do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00006071 // We should only be called for evaluating non-pointer expressions, or
6072 // expressions with a pointer type that are not used as references but instead
6073 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006074
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006075 // Our "symbolic interpreter" is just a dispatch off the currently
6076 // viewed AST node. We then recursively traverse the AST by calling
6077 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006078
6079 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006080 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00006081 case Stmt::ImplicitCastExprClass: {
6082 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00006083 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00006084 E = IE->getSubExpr();
6085 continue;
6086 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006087 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00006088 }
6089
John McCall28fc7092011-11-10 05:35:25 +00006090 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006091 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006092
Douglas Gregor4bd90e52009-10-23 18:54:35 +00006093 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006094 // When we hit a DeclRefExpr we are looking at code that refers to a
6095 // variable's name. If it's not a reference variable we check if it has
6096 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006097 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006098
Richard Smith40f08eb2014-01-30 22:05:38 +00006099 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00006100 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00006101 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00006102
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006103 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6104 // Check if it refers to itself, e.g. "int& i = i;".
6105 if (V == ParentDecl)
6106 return DR;
6107
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006108 if (V->hasLocalStorage()) {
6109 if (!V->getType()->isReferenceType())
6110 return DR;
6111
6112 // Reference variable, follow through to the expression that
6113 // it points to.
6114 if (V->hasInit()) {
6115 // Add the reference variable to the "trail".
6116 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006117 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006118 }
6119 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006120 }
Mike Stump11289f42009-09-09 15:08:12 +00006121
Craig Topperc3ec1492014-05-26 06:22:03 +00006122 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006123 }
Mike Stump11289f42009-09-09 15:08:12 +00006124
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006125 case Stmt::UnaryOperatorClass: {
6126 // The only unary operator that make sense to handle here
6127 // is Deref. All others don't resolve to a "name." This includes
6128 // handling all sorts of rvalues passed to a unary operator.
6129 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006130
John McCalle3027922010-08-25 11:45:40 +00006131 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006132 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006133
Craig Topperc3ec1492014-05-26 06:22:03 +00006134 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006135 }
Mike Stump11289f42009-09-09 15:08:12 +00006136
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006137 case Stmt::ArraySubscriptExprClass: {
6138 // Array subscripts are potential references to data on the stack. We
6139 // retrieve the DeclRefExpr* for the array variable if it indeed
6140 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006141 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006142 }
Mike Stump11289f42009-09-09 15:08:12 +00006143
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006144 case Stmt::OMPArraySectionExprClass: {
6145 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6146 ParentDecl);
6147 }
6148
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006149 case Stmt::ConditionalOperatorClass: {
6150 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006151 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006152 ConditionalOperator *C = cast<ConditionalOperator>(E);
6153
Anders Carlsson801c5c72007-11-30 19:04:31 +00006154 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006155 if (Expr *LHSExpr = C->getLHS()) {
6156 // In C++, we can have a throw-expression, which has 'void' type.
6157 if (!LHSExpr->getType()->isVoidType())
6158 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6159 return LHS;
6160 }
6161
6162 // In C++, we can have a throw-expression, which has 'void' type.
6163 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006164 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00006165
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006166 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006167 }
Mike Stump11289f42009-09-09 15:08:12 +00006168
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006169 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00006170 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006171 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006172
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006173 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006174 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00006175 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006176
6177 // Check whether the member type is itself a reference, in which case
6178 // we're not going to refer to the member, but to what the member refers to.
6179 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006180 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006181
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006182 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006183 }
Mike Stump11289f42009-09-09 15:08:12 +00006184
Douglas Gregorfe314812011-06-21 17:03:29 +00006185 case Stmt::MaterializeTemporaryExprClass:
6186 if (Expr *Result = EvalVal(
6187 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006188 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006189 return Result;
6190
6191 return E;
6192
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006193 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006194 // Check that we don't return or take the address of a reference to a
6195 // temporary. This is only useful in C++.
6196 if (!E->isTypeDependent() && E->isRValue())
6197 return E;
6198
6199 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00006200 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006201 }
Ted Kremenekb7861562010-08-04 20:01:07 +00006202} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006203}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006204
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006205void
6206Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6207 SourceLocation ReturnLoc,
6208 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006209 const AttrVec *Attrs,
6210 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006211 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6212
6213 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006214 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6215 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006216 CheckNonNullExpr(*this, RetValExp))
6217 Diag(ReturnLoc, diag::warn_null_ret)
6218 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006219
6220 // C++11 [basic.stc.dynamic.allocation]p4:
6221 // If an allocation function declared with a non-throwing
6222 // exception-specification fails to allocate storage, it shall return
6223 // a null pointer. Any other allocation function that fails to allocate
6224 // storage shall indicate failure only by throwing an exception [...]
6225 if (FD) {
6226 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6227 if (Op == OO_New || Op == OO_Array_New) {
6228 const FunctionProtoType *Proto
6229 = FD->getType()->castAs<FunctionProtoType>();
6230 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6231 CheckNonNullExpr(*this, RetValExp))
6232 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6233 << FD << getLangOpts().CPlusPlus11;
6234 }
6235 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006236}
6237
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006238//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6239
6240/// Check for comparisons of floating point operands using != and ==.
6241/// Issue a warning if these are no self-comparisons, as they are not likely
6242/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006243void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006244 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6245 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006246
6247 // Special case: check for x == x (which is OK).
6248 // Do not emit warnings for such cases.
6249 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6250 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6251 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006252 return;
Mike Stump11289f42009-09-09 15:08:12 +00006253
Ted Kremenekeda40e22007-11-29 00:59:04 +00006254 // Special case: check for comparisons against literals that can be exactly
6255 // represented by APFloat. In such cases, do not emit a warning. This
6256 // is a heuristic: often comparison against such literals are used to
6257 // detect if a value in a variable has not changed. This clearly can
6258 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006259 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6260 if (FLL->isExact())
6261 return;
6262 } else
6263 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6264 if (FLR->isExact())
6265 return;
Mike Stump11289f42009-09-09 15:08:12 +00006266
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006267 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006268 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006269 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006270 return;
Mike Stump11289f42009-09-09 15:08:12 +00006271
David Blaikie1f4ff152012-07-16 20:47:22 +00006272 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006273 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006274 return;
Mike Stump11289f42009-09-09 15:08:12 +00006275
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006276 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006277 Diag(Loc, diag::warn_floatingpoint_eq)
6278 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006279}
John McCallca01b222010-01-04 23:21:16 +00006280
John McCall70aa5392010-01-06 05:24:50 +00006281//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6282//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006283
John McCall70aa5392010-01-06 05:24:50 +00006284namespace {
John McCallca01b222010-01-04 23:21:16 +00006285
John McCall70aa5392010-01-06 05:24:50 +00006286/// Structure recording the 'active' range of an integer-valued
6287/// expression.
6288struct IntRange {
6289 /// The number of bits active in the int.
6290 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006291
John McCall70aa5392010-01-06 05:24:50 +00006292 /// True if the int is known not to have negative values.
6293 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006294
John McCall70aa5392010-01-06 05:24:50 +00006295 IntRange(unsigned Width, bool NonNegative)
6296 : Width(Width), NonNegative(NonNegative)
6297 {}
John McCallca01b222010-01-04 23:21:16 +00006298
John McCall817d4af2010-11-10 23:38:19 +00006299 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006300 static IntRange forBoolType() {
6301 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006302 }
6303
John McCall817d4af2010-11-10 23:38:19 +00006304 /// Returns the range of an opaque value of the given integral type.
6305 static IntRange forValueOfType(ASTContext &C, QualType T) {
6306 return forValueOfCanonicalType(C,
6307 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006308 }
6309
John McCall817d4af2010-11-10 23:38:19 +00006310 /// Returns the range of an opaque value of a canonical integral type.
6311 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006312 assert(T->isCanonicalUnqualified());
6313
6314 if (const VectorType *VT = dyn_cast<VectorType>(T))
6315 T = VT->getElementType().getTypePtr();
6316 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6317 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006318 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6319 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006320
David Majnemer6a426652013-06-07 22:07:20 +00006321 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006322 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006323 EnumDecl *Enum = ET->getDecl();
6324 if (!Enum->isCompleteDefinition())
6325 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006326
David Majnemer6a426652013-06-07 22:07:20 +00006327 unsigned NumPositive = Enum->getNumPositiveBits();
6328 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006329
David Majnemer6a426652013-06-07 22:07:20 +00006330 if (NumNegative == 0)
6331 return IntRange(NumPositive, true/*NonNegative*/);
6332 else
6333 return IntRange(std::max(NumPositive + 1, NumNegative),
6334 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006335 }
John McCall70aa5392010-01-06 05:24:50 +00006336
6337 const BuiltinType *BT = cast<BuiltinType>(T);
6338 assert(BT->isInteger());
6339
6340 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6341 }
6342
John McCall817d4af2010-11-10 23:38:19 +00006343 /// Returns the "target" range of a canonical integral type, i.e.
6344 /// the range of values expressible in the type.
6345 ///
6346 /// This matches forValueOfCanonicalType except that enums have the
6347 /// full range of their type, not the range of their enumerators.
6348 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6349 assert(T->isCanonicalUnqualified());
6350
6351 if (const VectorType *VT = dyn_cast<VectorType>(T))
6352 T = VT->getElementType().getTypePtr();
6353 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6354 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006355 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6356 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006357 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006358 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006359
6360 const BuiltinType *BT = cast<BuiltinType>(T);
6361 assert(BT->isInteger());
6362
6363 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6364 }
6365
6366 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006367 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006368 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006369 L.NonNegative && R.NonNegative);
6370 }
6371
John McCall817d4af2010-11-10 23:38:19 +00006372 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006373 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006374 return IntRange(std::min(L.Width, R.Width),
6375 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006376 }
6377};
6378
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006379IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006380 if (value.isSigned() && value.isNegative())
6381 return IntRange(value.getMinSignedBits(), false);
6382
6383 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006384 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006385
6386 // isNonNegative() just checks the sign bit without considering
6387 // signedness.
6388 return IntRange(value.getActiveBits(), true);
6389}
6390
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006391IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6392 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006393 if (result.isInt())
6394 return GetValueRange(C, result.getInt(), MaxWidth);
6395
6396 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006397 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6398 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6399 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6400 R = IntRange::join(R, El);
6401 }
John McCall70aa5392010-01-06 05:24:50 +00006402 return R;
6403 }
6404
6405 if (result.isComplexInt()) {
6406 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6407 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6408 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006409 }
6410
6411 // This can happen with lossless casts to intptr_t of "based" lvalues.
6412 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006413 // FIXME: The only reason we need to pass the type in here is to get
6414 // the sign right on this one case. It would be nice if APValue
6415 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006416 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006417 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006418}
John McCall70aa5392010-01-06 05:24:50 +00006419
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006420QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006421 QualType Ty = E->getType();
6422 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6423 Ty = AtomicRHS->getValueType();
6424 return Ty;
6425}
6426
John McCall70aa5392010-01-06 05:24:50 +00006427/// Pseudo-evaluate the given integer expression, estimating the
6428/// range of values it might take.
6429///
6430/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006431IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006432 E = E->IgnoreParens();
6433
6434 // Try a full evaluation first.
6435 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006436 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006437 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006438
6439 // I think we only want to look through implicit casts here; if the
6440 // user has an explicit widening cast, we should treat the value as
6441 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006442 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006443 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006444 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6445
Eli Friedmane6d33952013-07-08 20:20:06 +00006446 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006447
George Burgess IVdf1ed002016-01-13 01:52:39 +00006448 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6449 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006450
John McCall70aa5392010-01-06 05:24:50 +00006451 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006452 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006453 return OutputTypeRange;
6454
6455 IntRange SubRange
6456 = GetExprRange(C, CE->getSubExpr(),
6457 std::min(MaxWidth, OutputTypeRange.Width));
6458
6459 // Bail out if the subexpr's range is as wide as the cast type.
6460 if (SubRange.Width >= OutputTypeRange.Width)
6461 return OutputTypeRange;
6462
6463 // Otherwise, we take the smaller width, and we're non-negative if
6464 // either the output type or the subexpr is.
6465 return IntRange(SubRange.Width,
6466 SubRange.NonNegative || OutputTypeRange.NonNegative);
6467 }
6468
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006469 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006470 // If we can fold the condition, just take that operand.
6471 bool CondResult;
6472 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6473 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6474 : CO->getFalseExpr(),
6475 MaxWidth);
6476
6477 // Otherwise, conservatively merge.
6478 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6479 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6480 return IntRange::join(L, R);
6481 }
6482
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006483 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006484 switch (BO->getOpcode()) {
6485
6486 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006487 case BO_LAnd:
6488 case BO_LOr:
6489 case BO_LT:
6490 case BO_GT:
6491 case BO_LE:
6492 case BO_GE:
6493 case BO_EQ:
6494 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006495 return IntRange::forBoolType();
6496
John McCallc3688382011-07-13 06:35:24 +00006497 // The type of the assignments is the type of the LHS, so the RHS
6498 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006499 case BO_MulAssign:
6500 case BO_DivAssign:
6501 case BO_RemAssign:
6502 case BO_AddAssign:
6503 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006504 case BO_XorAssign:
6505 case BO_OrAssign:
6506 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006507 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006508
John McCallc3688382011-07-13 06:35:24 +00006509 // Simple assignments just pass through the RHS, which will have
6510 // been coerced to the LHS type.
6511 case BO_Assign:
6512 // TODO: bitfields?
6513 return GetExprRange(C, BO->getRHS(), MaxWidth);
6514
John McCall70aa5392010-01-06 05:24:50 +00006515 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006516 case BO_PtrMemD:
6517 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006518 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006519
John McCall2ce81ad2010-01-06 22:07:33 +00006520 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006521 case BO_And:
6522 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006523 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6524 GetExprRange(C, BO->getRHS(), MaxWidth));
6525
John McCall70aa5392010-01-06 05:24:50 +00006526 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006527 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006528 // ...except that we want to treat '1 << (blah)' as logically
6529 // positive. It's an important idiom.
6530 if (IntegerLiteral *I
6531 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6532 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006533 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006534 return IntRange(R.Width, /*NonNegative*/ true);
6535 }
6536 }
6537 // fallthrough
6538
John McCalle3027922010-08-25 11:45:40 +00006539 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006540 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006541
John McCall2ce81ad2010-01-06 22:07:33 +00006542 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006543 case BO_Shr:
6544 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006545 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6546
6547 // If the shift amount is a positive constant, drop the width by
6548 // that much.
6549 llvm::APSInt shift;
6550 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6551 shift.isNonNegative()) {
6552 unsigned zext = shift.getZExtValue();
6553 if (zext >= L.Width)
6554 L.Width = (L.NonNegative ? 0 : 1);
6555 else
6556 L.Width -= zext;
6557 }
6558
6559 return L;
6560 }
6561
6562 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006563 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006564 return GetExprRange(C, BO->getRHS(), MaxWidth);
6565
John McCall2ce81ad2010-01-06 22:07:33 +00006566 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006567 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006568 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006569 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006570 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006571
John McCall51431812011-07-14 22:39:48 +00006572 // The width of a division result is mostly determined by the size
6573 // of the LHS.
6574 case BO_Div: {
6575 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006576 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006577 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6578
6579 // If the divisor is constant, use that.
6580 llvm::APSInt divisor;
6581 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6582 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6583 if (log2 >= L.Width)
6584 L.Width = (L.NonNegative ? 0 : 1);
6585 else
6586 L.Width = std::min(L.Width - log2, MaxWidth);
6587 return L;
6588 }
6589
6590 // Otherwise, just use the LHS's width.
6591 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6592 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6593 }
6594
6595 // The result of a remainder can't be larger than the result of
6596 // either side.
6597 case BO_Rem: {
6598 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006599 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006600 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6601 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6602
6603 IntRange meet = IntRange::meet(L, R);
6604 meet.Width = std::min(meet.Width, MaxWidth);
6605 return meet;
6606 }
6607
6608 // The default behavior is okay for these.
6609 case BO_Mul:
6610 case BO_Add:
6611 case BO_Xor:
6612 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006613 break;
6614 }
6615
John McCall51431812011-07-14 22:39:48 +00006616 // The default case is to treat the operation as if it were closed
6617 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006618 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6619 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6620 return IntRange::join(L, R);
6621 }
6622
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006623 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006624 switch (UO->getOpcode()) {
6625 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006626 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006627 return IntRange::forBoolType();
6628
6629 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006630 case UO_Deref:
6631 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006632 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006633
6634 default:
6635 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6636 }
6637 }
6638
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006639 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006640 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6641
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006642 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006643 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006644 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006645
Eli Friedmane6d33952013-07-08 20:20:06 +00006646 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006647}
John McCall263a48b2010-01-04 23:31:57 +00006648
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006649IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006650 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006651}
6652
John McCall263a48b2010-01-04 23:31:57 +00006653/// Checks whether the given value, which currently has the given
6654/// source semantics, has the same value when coerced through the
6655/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006656bool IsSameFloatAfterCast(const llvm::APFloat &value,
6657 const llvm::fltSemantics &Src,
6658 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006659 llvm::APFloat truncated = value;
6660
6661 bool ignored;
6662 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6663 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6664
6665 return truncated.bitwiseIsEqual(value);
6666}
6667
6668/// Checks whether the given value, which currently has the given
6669/// source semantics, has the same value when coerced through the
6670/// target semantics.
6671///
6672/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006673bool IsSameFloatAfterCast(const APValue &value,
6674 const llvm::fltSemantics &Src,
6675 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006676 if (value.isFloat())
6677 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6678
6679 if (value.isVector()) {
6680 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6681 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6682 return false;
6683 return true;
6684 }
6685
6686 assert(value.isComplexFloat());
6687 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6688 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6689}
6690
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006691void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006692
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006693bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006694 // Suppress cases where we are comparing against an enum constant.
6695 if (const DeclRefExpr *DR =
6696 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6697 if (isa<EnumConstantDecl>(DR->getDecl()))
6698 return false;
6699
6700 // Suppress cases where the '0' value is expanded from a macro.
6701 if (E->getLocStart().isMacroID())
6702 return false;
6703
John McCallcc7e5bf2010-05-06 08:58:33 +00006704 llvm::APSInt Value;
6705 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6706}
6707
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006708bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006709 // Strip off implicit integral promotions.
6710 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006711 if (ICE->getCastKind() != CK_IntegralCast &&
6712 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006713 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006714 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006715 }
6716
6717 return E->getType()->isEnumeralType();
6718}
6719
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006720void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006721 // Disable warning in template instantiations.
6722 if (!S.ActiveTemplateInstantiations.empty())
6723 return;
6724
John McCalle3027922010-08-25 11:45:40 +00006725 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006726 if (E->isValueDependent())
6727 return;
6728
John McCalle3027922010-08-25 11:45:40 +00006729 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006730 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006731 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006732 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006733 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006734 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006735 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006736 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006737 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006738 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006739 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006740 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006741 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006742 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006743 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006744 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6745 }
6746}
6747
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006748void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6749 Expr *Constant, Expr *Other,
6750 llvm::APSInt Value,
6751 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006752 // Disable warning in template instantiations.
6753 if (!S.ActiveTemplateInstantiations.empty())
6754 return;
6755
Richard Trieu0f097742014-04-04 04:13:47 +00006756 // TODO: Investigate using GetExprRange() to get tighter bounds
6757 // on the bit ranges.
6758 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006759 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006760 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006761 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6762 unsigned OtherWidth = OtherRange.Width;
6763
6764 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6765
Richard Trieu560910c2012-11-14 22:50:24 +00006766 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006767 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006768 return;
6769
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006770 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006771 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006772
Richard Trieu0f097742014-04-04 04:13:47 +00006773 // Used for diagnostic printout.
6774 enum {
6775 LiteralConstant = 0,
6776 CXXBoolLiteralTrue,
6777 CXXBoolLiteralFalse
6778 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006779
Richard Trieu0f097742014-04-04 04:13:47 +00006780 if (!OtherIsBooleanType) {
6781 QualType ConstantT = Constant->getType();
6782 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006783
Richard Trieu0f097742014-04-04 04:13:47 +00006784 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6785 return;
6786 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6787 "comparison with non-integer type");
6788
6789 bool ConstantSigned = ConstantT->isSignedIntegerType();
6790 bool CommonSigned = CommonT->isSignedIntegerType();
6791
6792 bool EqualityOnly = false;
6793
6794 if (CommonSigned) {
6795 // The common type is signed, therefore no signed to unsigned conversion.
6796 if (!OtherRange.NonNegative) {
6797 // Check that the constant is representable in type OtherT.
6798 if (ConstantSigned) {
6799 if (OtherWidth >= Value.getMinSignedBits())
6800 return;
6801 } else { // !ConstantSigned
6802 if (OtherWidth >= Value.getActiveBits() + 1)
6803 return;
6804 }
6805 } else { // !OtherSigned
6806 // Check that the constant is representable in type OtherT.
6807 // Negative values are out of range.
6808 if (ConstantSigned) {
6809 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6810 return;
6811 } else { // !ConstantSigned
6812 if (OtherWidth >= Value.getActiveBits())
6813 return;
6814 }
Richard Trieu560910c2012-11-14 22:50:24 +00006815 }
Richard Trieu0f097742014-04-04 04:13:47 +00006816 } else { // !CommonSigned
6817 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006818 if (OtherWidth >= Value.getActiveBits())
6819 return;
Craig Toppercf360162014-06-18 05:13:11 +00006820 } else { // OtherSigned
6821 assert(!ConstantSigned &&
6822 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006823 // Check to see if the constant is representable in OtherT.
6824 if (OtherWidth > Value.getActiveBits())
6825 return;
6826 // Check to see if the constant is equivalent to a negative value
6827 // cast to CommonT.
6828 if (S.Context.getIntWidth(ConstantT) ==
6829 S.Context.getIntWidth(CommonT) &&
6830 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6831 return;
6832 // The constant value rests between values that OtherT can represent
6833 // after conversion. Relational comparison still works, but equality
6834 // comparisons will be tautological.
6835 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006836 }
6837 }
Richard Trieu0f097742014-04-04 04:13:47 +00006838
6839 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6840
6841 if (op == BO_EQ || op == BO_NE) {
6842 IsTrue = op == BO_NE;
6843 } else if (EqualityOnly) {
6844 return;
6845 } else if (RhsConstant) {
6846 if (op == BO_GT || op == BO_GE)
6847 IsTrue = !PositiveConstant;
6848 else // op == BO_LT || op == BO_LE
6849 IsTrue = PositiveConstant;
6850 } else {
6851 if (op == BO_LT || op == BO_LE)
6852 IsTrue = !PositiveConstant;
6853 else // op == BO_GT || op == BO_GE
6854 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006855 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006856 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006857 // Other isKnownToHaveBooleanValue
6858 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6859 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6860 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6861
6862 static const struct LinkedConditions {
6863 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6864 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6865 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6866 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6867 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6868 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6869
6870 } TruthTable = {
6871 // Constant on LHS. | Constant on RHS. |
6872 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6873 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6874 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6875 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6876 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6877 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6878 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6879 };
6880
6881 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6882
6883 enum ConstantValue ConstVal = Zero;
6884 if (Value.isUnsigned() || Value.isNonNegative()) {
6885 if (Value == 0) {
6886 LiteralOrBoolConstant =
6887 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6888 ConstVal = Zero;
6889 } else if (Value == 1) {
6890 LiteralOrBoolConstant =
6891 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6892 ConstVal = One;
6893 } else {
6894 LiteralOrBoolConstant = LiteralConstant;
6895 ConstVal = GT_One;
6896 }
6897 } else {
6898 ConstVal = LT_Zero;
6899 }
6900
6901 CompareBoolWithConstantResult CmpRes;
6902
6903 switch (op) {
6904 case BO_LT:
6905 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6906 break;
6907 case BO_GT:
6908 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6909 break;
6910 case BO_LE:
6911 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6912 break;
6913 case BO_GE:
6914 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6915 break;
6916 case BO_EQ:
6917 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6918 break;
6919 case BO_NE:
6920 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6921 break;
6922 default:
6923 CmpRes = Unkwn;
6924 break;
6925 }
6926
6927 if (CmpRes == AFals) {
6928 IsTrue = false;
6929 } else if (CmpRes == ATrue) {
6930 IsTrue = true;
6931 } else {
6932 return;
6933 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006934 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006935
6936 // If this is a comparison to an enum constant, include that
6937 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006938 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006939 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6940 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6941
6942 SmallString<64> PrettySourceValue;
6943 llvm::raw_svector_ostream OS(PrettySourceValue);
6944 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006945 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006946 else
6947 OS << Value;
6948
Richard Trieu0f097742014-04-04 04:13:47 +00006949 S.DiagRuntimeBehavior(
6950 E->getOperatorLoc(), E,
6951 S.PDiag(diag::warn_out_of_range_compare)
6952 << OS.str() << LiteralOrBoolConstant
6953 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6954 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006955}
6956
John McCallcc7e5bf2010-05-06 08:58:33 +00006957/// Analyze the operands of the given comparison. Implements the
6958/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006959void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006960 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6961 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006962}
John McCall263a48b2010-01-04 23:31:57 +00006963
John McCallca01b222010-01-04 23:21:16 +00006964/// \brief Implements -Wsign-compare.
6965///
Richard Trieu82402a02011-09-15 21:56:47 +00006966/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006967void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006968 // The type the comparison is being performed in.
6969 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006970
6971 // Only analyze comparison operators where both sides have been converted to
6972 // the same type.
6973 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6974 return AnalyzeImpConvsInComparison(S, E);
6975
6976 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006977 if (E->isValueDependent())
6978 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006979
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006980 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6981 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006982
6983 bool IsComparisonConstant = false;
6984
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006985 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006986 // of 'true' or 'false'.
6987 if (T->isIntegralType(S.Context)) {
6988 llvm::APSInt RHSValue;
6989 bool IsRHSIntegralLiteral =
6990 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6991 llvm::APSInt LHSValue;
6992 bool IsLHSIntegralLiteral =
6993 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6994 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6995 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6996 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6997 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6998 else
6999 IsComparisonConstant =
7000 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007001 } else if (!T->hasUnsignedIntegerRepresentation())
7002 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007003
John McCallcc7e5bf2010-05-06 08:58:33 +00007004 // We don't do anything special if this isn't an unsigned integral
7005 // comparison: we're only interested in integral comparisons, and
7006 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007007 //
7008 // We also don't care about value-dependent expressions or expressions
7009 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007010 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007011 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007012
John McCallcc7e5bf2010-05-06 08:58:33 +00007013 // Check to see if one of the (unmodified) operands is of different
7014 // signedness.
7015 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007016 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7017 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007018 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007019 signedOperand = LHS;
7020 unsignedOperand = RHS;
7021 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7022 signedOperand = RHS;
7023 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007024 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007025 CheckTrivialUnsignedComparison(S, E);
7026 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007027 }
7028
John McCallcc7e5bf2010-05-06 08:58:33 +00007029 // Otherwise, calculate the effective range of the signed operand.
7030 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007031
John McCallcc7e5bf2010-05-06 08:58:33 +00007032 // Go ahead and analyze implicit conversions in the operands. Note
7033 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007034 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7035 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007036
John McCallcc7e5bf2010-05-06 08:58:33 +00007037 // If the signed range is non-negative, -Wsign-compare won't fire,
7038 // but we should still check for comparisons which are always true
7039 // or false.
7040 if (signedRange.NonNegative)
7041 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007042
7043 // For (in)equality comparisons, if the unsigned operand is a
7044 // constant which cannot collide with a overflowed signed operand,
7045 // then reinterpreting the signed operand as unsigned will not
7046 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007047 if (E->isEqualityOp()) {
7048 unsigned comparisonWidth = S.Context.getIntWidth(T);
7049 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007050
John McCallcc7e5bf2010-05-06 08:58:33 +00007051 // We should never be unable to prove that the unsigned operand is
7052 // non-negative.
7053 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7054
7055 if (unsignedRange.Width < comparisonWidth)
7056 return;
7057 }
7058
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007059 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7060 S.PDiag(diag::warn_mixed_sign_comparison)
7061 << LHS->getType() << RHS->getType()
7062 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007063}
7064
John McCall1f425642010-11-11 03:21:53 +00007065/// Analyzes an attempt to assign the given value to a bitfield.
7066///
7067/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007068bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7069 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007070 assert(Bitfield->isBitField());
7071 if (Bitfield->isInvalidDecl())
7072 return false;
7073
John McCalldeebbcf2010-11-11 05:33:51 +00007074 // White-list bool bitfields.
7075 if (Bitfield->getType()->isBooleanType())
7076 return false;
7077
Douglas Gregor789adec2011-02-04 13:09:01 +00007078 // Ignore value- or type-dependent expressions.
7079 if (Bitfield->getBitWidth()->isValueDependent() ||
7080 Bitfield->getBitWidth()->isTypeDependent() ||
7081 Init->isValueDependent() ||
7082 Init->isTypeDependent())
7083 return false;
7084
John McCall1f425642010-11-11 03:21:53 +00007085 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7086
Richard Smith5fab0c92011-12-28 19:48:30 +00007087 llvm::APSInt Value;
7088 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007089 return false;
7090
John McCall1f425642010-11-11 03:21:53 +00007091 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007092 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007093
7094 if (OriginalWidth <= FieldWidth)
7095 return false;
7096
Eli Friedmanc267a322012-01-26 23:11:39 +00007097 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007098 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007099 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007100
Eli Friedmanc267a322012-01-26 23:11:39 +00007101 // Check whether the stored value is equal to the original value.
7102 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007103 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007104 return false;
7105
Eli Friedmanc267a322012-01-26 23:11:39 +00007106 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007107 // therefore don't strictly fit into a signed bitfield of width 1.
7108 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007109 return false;
7110
John McCall1f425642010-11-11 03:21:53 +00007111 std::string PrettyValue = Value.toString(10);
7112 std::string PrettyTrunc = TruncatedValue.toString(10);
7113
7114 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7115 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7116 << Init->getSourceRange();
7117
7118 return true;
7119}
7120
John McCalld2a53122010-11-09 23:24:47 +00007121/// Analyze the given simple or compound assignment for warning-worthy
7122/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007123void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007124 // Just recurse on the LHS.
7125 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7126
7127 // We want to recurse on the RHS as normal unless we're assigning to
7128 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007129 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007130 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007131 E->getOperatorLoc())) {
7132 // Recurse, ignoring any implicit conversions on the RHS.
7133 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7134 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007135 }
7136 }
7137
7138 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7139}
7140
John McCall263a48b2010-01-04 23:31:57 +00007141/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007142void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7143 SourceLocation CContext, unsigned diag,
7144 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007145 if (pruneControlFlow) {
7146 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7147 S.PDiag(diag)
7148 << SourceType << T << E->getSourceRange()
7149 << SourceRange(CContext));
7150 return;
7151 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007152 S.Diag(E->getExprLoc(), diag)
7153 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7154}
7155
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007156/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007157void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7158 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007159 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007160}
7161
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007162/// Diagnose an implicit cast from a literal expression. Does not warn when the
7163/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007164void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7165 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007166 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007167 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007168 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007169 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7170 T->hasUnsignedIntegerRepresentation());
7171 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007172 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007173 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007174 return;
7175
Eli Friedman07185912013-08-29 23:44:43 +00007176 // FIXME: Force the precision of the source value down so we don't print
7177 // digits which are usually useless (we don't really care here if we
7178 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7179 // would automatically print the shortest representation, but it's a bit
7180 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007181 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007182 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7183 precision = (precision * 59 + 195) / 196;
7184 Value.toString(PrettySourceValue, precision);
7185
David Blaikie9b88cc02012-05-15 17:18:27 +00007186 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007187 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007188 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007189 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007190 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007191
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007192 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007193 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7194 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007195}
7196
John McCall18a2c2c2010-11-09 22:22:12 +00007197std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7198 if (!Range.Width) return "0";
7199
7200 llvm::APSInt ValueInRange = Value;
7201 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007202 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007203 return ValueInRange.toString(10);
7204}
7205
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007206bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007207 if (!isa<ImplicitCastExpr>(Ex))
7208 return false;
7209
7210 Expr *InnerE = Ex->IgnoreParenImpCasts();
7211 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7212 const Type *Source =
7213 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7214 if (Target->isDependentType())
7215 return false;
7216
7217 const BuiltinType *FloatCandidateBT =
7218 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7219 const Type *BoolCandidateType = ToBool ? Target : Source;
7220
7221 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7222 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7223}
7224
7225void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7226 SourceLocation CC) {
7227 unsigned NumArgs = TheCall->getNumArgs();
7228 for (unsigned i = 0; i < NumArgs; ++i) {
7229 Expr *CurrA = TheCall->getArg(i);
7230 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7231 continue;
7232
7233 bool IsSwapped = ((i > 0) &&
7234 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7235 IsSwapped |= ((i < (NumArgs - 1)) &&
7236 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7237 if (IsSwapped) {
7238 // Warn on this floating-point to bool conversion.
7239 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7240 CurrA->getType(), CC,
7241 diag::warn_impcast_floating_point_to_bool);
7242 }
7243 }
7244}
7245
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007246void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007247 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7248 E->getExprLoc()))
7249 return;
7250
Richard Trieu09d6b802016-01-08 23:35:06 +00007251 // Don't warn on functions which have return type nullptr_t.
7252 if (isa<CallExpr>(E))
7253 return;
7254
Richard Trieu5b993502014-10-15 03:42:06 +00007255 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7256 const Expr::NullPointerConstantKind NullKind =
7257 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7258 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7259 return;
7260
7261 // Return if target type is a safe conversion.
7262 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7263 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7264 return;
7265
7266 SourceLocation Loc = E->getSourceRange().getBegin();
7267
7268 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7269 if (NullKind == Expr::NPCK_GNUNull) {
Richard Trieufc014f22016-01-09 01:10:17 +00007270 if (Loc.isMacroID()) {
Richard Trieu3a5c9582016-01-26 02:51:55 +00007271 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7272 Loc, S.SourceMgr, S.getLangOpts());
Richard Trieufc014f22016-01-09 01:10:17 +00007273 if (MacroName == "NULL")
7274 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7275 }
Richard Trieu5b993502014-10-15 03:42:06 +00007276 }
7277
7278 // Only warn if the null and context location are in the same macro expansion.
7279 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7280 return;
7281
7282 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7283 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7284 << FixItHint::CreateReplacement(Loc,
7285 S.getFixItZeroLiteralForType(T, Loc));
7286}
7287
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007288void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7289 ObjCArrayLiteral *ArrayLiteral);
7290void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7291 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007292
7293/// Check a single element within a collection literal against the
7294/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007295void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7296 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007297 // Skip a bitcast to 'id' or qualified 'id'.
7298 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7299 if (ICE->getCastKind() == CK_BitCast &&
7300 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7301 Element = ICE->getSubExpr();
7302 }
7303
7304 QualType ElementType = Element->getType();
7305 ExprResult ElementResult(Element);
7306 if (ElementType->getAs<ObjCObjectPointerType>() &&
7307 S.CheckSingleAssignmentConstraints(TargetElementType,
7308 ElementResult,
7309 false, false)
7310 != Sema::Compatible) {
7311 S.Diag(Element->getLocStart(),
7312 diag::warn_objc_collection_literal_element)
7313 << ElementType << ElementKind << TargetElementType
7314 << Element->getSourceRange();
7315 }
7316
7317 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7318 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7319 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7320 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7321}
7322
7323/// Check an Objective-C array literal being converted to the given
7324/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007325void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7326 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007327 if (!S.NSArrayDecl)
7328 return;
7329
7330 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7331 if (!TargetObjCPtr)
7332 return;
7333
7334 if (TargetObjCPtr->isUnspecialized() ||
7335 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7336 != S.NSArrayDecl->getCanonicalDecl())
7337 return;
7338
7339 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7340 if (TypeArgs.size() != 1)
7341 return;
7342
7343 QualType TargetElementType = TypeArgs[0];
7344 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7345 checkObjCCollectionLiteralElement(S, TargetElementType,
7346 ArrayLiteral->getElement(I),
7347 0);
7348 }
7349}
7350
7351/// Check an Objective-C dictionary literal being converted to the given
7352/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007353void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7354 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007355 if (!S.NSDictionaryDecl)
7356 return;
7357
7358 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7359 if (!TargetObjCPtr)
7360 return;
7361
7362 if (TargetObjCPtr->isUnspecialized() ||
7363 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7364 != S.NSDictionaryDecl->getCanonicalDecl())
7365 return;
7366
7367 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7368 if (TypeArgs.size() != 2)
7369 return;
7370
7371 QualType TargetKeyType = TypeArgs[0];
7372 QualType TargetObjectType = TypeArgs[1];
7373 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7374 auto Element = DictionaryLiteral->getKeyValueElement(I);
7375 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7376 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7377 }
7378}
7379
Richard Trieufc404c72016-02-05 23:02:38 +00007380// Helper function to filter out cases for constant width constant conversion.
7381// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007382bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7383 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007384 // If initializing from a constant, and the constant starts with '0',
7385 // then it is a binary, octal, or hexadecimal. Allow these constants
7386 // to fill all the bits, even if there is a sign change.
7387 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7388 const char FirstLiteralCharacter =
7389 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7390 if (FirstLiteralCharacter == '0')
7391 return false;
7392 }
7393
7394 // If the CC location points to a '{', and the type is char, then assume
7395 // assume it is an array initialization.
7396 if (CC.isValid() && T->isCharType()) {
7397 const char FirstContextCharacter =
7398 S.getSourceManager().getCharacterData(CC)[0];
7399 if (FirstContextCharacter == '{')
7400 return false;
7401 }
7402
7403 return true;
7404}
7405
John McCallcc7e5bf2010-05-06 08:58:33 +00007406void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007407 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007408 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007409
John McCallcc7e5bf2010-05-06 08:58:33 +00007410 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7411 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7412 if (Source == Target) return;
7413 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007414
Chandler Carruthc22845a2011-07-26 05:40:03 +00007415 // If the conversion context location is invalid don't complain. We also
7416 // don't want to emit a warning if the issue occurs from the expansion of
7417 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7418 // delay this check as long as possible. Once we detect we are in that
7419 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007420 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007421 return;
7422
Richard Trieu021baa32011-09-23 20:10:00 +00007423 // Diagnose implicit casts to bool.
7424 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7425 if (isa<StringLiteral>(E))
7426 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007427 // and expressions, for instance, assert(0 && "error here"), are
7428 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007429 return DiagnoseImpCast(S, E, T, CC,
7430 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007431 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7432 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7433 // This covers the literal expressions that evaluate to Objective-C
7434 // objects.
7435 return DiagnoseImpCast(S, E, T, CC,
7436 diag::warn_impcast_objective_c_literal_to_bool);
7437 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007438 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7439 // Warn on pointer to bool conversion that is always true.
7440 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7441 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007442 }
Richard Trieu021baa32011-09-23 20:10:00 +00007443 }
John McCall263a48b2010-01-04 23:31:57 +00007444
Douglas Gregor5054cb02015-07-07 03:58:22 +00007445 // Check implicit casts from Objective-C collection literals to specialized
7446 // collection types, e.g., NSArray<NSString *> *.
7447 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7448 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7449 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7450 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7451
John McCall263a48b2010-01-04 23:31:57 +00007452 // Strip vector types.
7453 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007454 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007455 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007456 return;
John McCallacf0ee52010-10-08 02:01:28 +00007457 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007458 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007459
7460 // If the vector cast is cast between two vectors of the same size, it is
7461 // a bitcast, not a conversion.
7462 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7463 return;
John McCall263a48b2010-01-04 23:31:57 +00007464
7465 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7466 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7467 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007468 if (auto VecTy = dyn_cast<VectorType>(Target))
7469 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007470
7471 // Strip complex types.
7472 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007473 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007474 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007475 return;
7476
John McCallacf0ee52010-10-08 02:01:28 +00007477 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007478 }
John McCall263a48b2010-01-04 23:31:57 +00007479
7480 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7481 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7482 }
7483
7484 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7485 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7486
7487 // If the source is floating point...
7488 if (SourceBT && SourceBT->isFloatingPoint()) {
7489 // ...and the target is floating point...
7490 if (TargetBT && TargetBT->isFloatingPoint()) {
7491 // ...then warn if we're dropping FP rank.
7492
7493 // Builtin FP kinds are ordered by increasing FP rank.
7494 if (SourceBT->getKind() > TargetBT->getKind()) {
7495 // Don't warn about float constants that are precisely
7496 // representable in the target type.
7497 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007498 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007499 // Value might be a float, a float vector, or a float complex.
7500 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007501 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7502 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007503 return;
7504 }
7505
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007506 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007507 return;
7508
John McCallacf0ee52010-10-08 02:01:28 +00007509 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007510 }
7511 // ... or possibly if we're increasing rank, too
7512 else if (TargetBT->getKind() > SourceBT->getKind()) {
7513 if (S.SourceMgr.isInSystemMacro(CC))
7514 return;
7515
7516 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007517 }
7518 return;
7519 }
7520
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007521 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007522 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007523 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007524 return;
7525
Chandler Carruth22c7a792011-02-17 11:05:49 +00007526 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007527 // We also want to warn on, e.g., "int i = -1.234"
7528 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7529 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7530 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7531
Chandler Carruth016ef402011-04-10 08:36:24 +00007532 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7533 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007534 } else {
7535 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7536 }
7537 }
John McCall263a48b2010-01-04 23:31:57 +00007538
Richard Smith54894fd2015-12-30 01:06:52 +00007539 // Detect the case where a call result is converted from floating-point to
7540 // to bool, and the final argument to the call is converted from bool, to
7541 // discover this typo:
7542 //
7543 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7544 //
7545 // FIXME: This is an incredibly special case; is there some more general
7546 // way to detect this class of misplaced-parentheses bug?
7547 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007548 // Check last argument of function call to see if it is an
7549 // implicit cast from a type matching the type the result
7550 // is being cast to.
7551 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007552 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007553 Expr *LastA = CEx->getArg(NumArgs - 1);
7554 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007555 if (isa<ImplicitCastExpr>(LastA) &&
7556 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007557 // Warn on this floating-point to bool conversion
7558 DiagnoseImpCast(S, E, T, CC,
7559 diag::warn_impcast_floating_point_to_bool);
7560 }
7561 }
7562 }
John McCall263a48b2010-01-04 23:31:57 +00007563 return;
7564 }
7565
Richard Trieu5b993502014-10-15 03:42:06 +00007566 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007567
David Blaikie9366d2b2012-06-19 21:19:06 +00007568 if (!Source->isIntegerType() || !Target->isIntegerType())
7569 return;
7570
David Blaikie7555b6a2012-05-15 16:56:36 +00007571 // TODO: remove this early return once the false positives for constant->bool
7572 // in templates, macros, etc, are reduced or removed.
7573 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7574 return;
7575
John McCallcc7e5bf2010-05-06 08:58:33 +00007576 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007577 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007578
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007579 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007580 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007581 // TODO: this should happen for bitfield stores, too.
7582 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007583 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007584 if (S.SourceMgr.isInSystemMacro(CC))
7585 return;
7586
John McCall18a2c2c2010-11-09 22:22:12 +00007587 std::string PrettySourceValue = Value.toString(10);
7588 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007589
Ted Kremenek33ba9952011-10-22 02:37:33 +00007590 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7591 S.PDiag(diag::warn_impcast_integer_precision_constant)
7592 << PrettySourceValue << PrettyTargetValue
7593 << E->getType() << T << E->getSourceRange()
7594 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007595 return;
7596 }
7597
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007598 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7599 if (S.SourceMgr.isInSystemMacro(CC))
7600 return;
7601
David Blaikie9455da02012-04-12 22:40:54 +00007602 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007603 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7604 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007605 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007606 }
7607
Richard Trieudcb55572016-01-29 23:51:16 +00007608 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7609 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7610 // Warn when doing a signed to signed conversion, warn if the positive
7611 // source value is exactly the width of the target type, which will
7612 // cause a negative value to be stored.
7613
7614 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007615 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7616 !S.SourceMgr.isInSystemMacro(CC)) {
7617 if (isSameWidthConstantConversion(S, E, T, CC)) {
7618 std::string PrettySourceValue = Value.toString(10);
7619 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007620
Richard Trieufc404c72016-02-05 23:02:38 +00007621 S.DiagRuntimeBehavior(
7622 E->getExprLoc(), E,
7623 S.PDiag(diag::warn_impcast_integer_precision_constant)
7624 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7625 << E->getSourceRange() << clang::SourceRange(CC));
7626 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007627 }
7628 }
Richard Trieufc404c72016-02-05 23:02:38 +00007629
Richard Trieudcb55572016-01-29 23:51:16 +00007630 // Fall through for non-constants to give a sign conversion warning.
7631 }
7632
John McCallcc7e5bf2010-05-06 08:58:33 +00007633 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7634 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7635 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007636 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007637 return;
7638
John McCallcc7e5bf2010-05-06 08:58:33 +00007639 unsigned DiagID = diag::warn_impcast_integer_sign;
7640
7641 // Traditionally, gcc has warned about this under -Wsign-compare.
7642 // We also want to warn about it in -Wconversion.
7643 // So if -Wconversion is off, use a completely identical diagnostic
7644 // in the sign-compare group.
7645 // The conditional-checking code will
7646 if (ICContext) {
7647 DiagID = diag::warn_impcast_integer_sign_conditional;
7648 *ICContext = true;
7649 }
7650
John McCallacf0ee52010-10-08 02:01:28 +00007651 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007652 }
7653
Douglas Gregora78f1932011-02-22 02:45:07 +00007654 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007655 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7656 // type, to give us better diagnostics.
7657 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007658 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007659 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7660 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7661 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7662 SourceType = S.Context.getTypeDeclType(Enum);
7663 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7664 }
7665 }
7666
Douglas Gregora78f1932011-02-22 02:45:07 +00007667 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7668 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007669 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7670 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007671 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007672 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007673 return;
7674
Douglas Gregor364f7db2011-03-12 00:14:31 +00007675 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007676 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007677 }
John McCall263a48b2010-01-04 23:31:57 +00007678}
7679
David Blaikie18e9ac72012-05-15 21:57:38 +00007680void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7681 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007682
7683void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007684 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007685 E = E->IgnoreParenImpCasts();
7686
7687 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007688 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007689
John McCallacf0ee52010-10-08 02:01:28 +00007690 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007691 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007692 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007693}
7694
David Blaikie18e9ac72012-05-15 21:57:38 +00007695void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7696 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007697 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007698
7699 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007700 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7701 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007702
7703 // If -Wconversion would have warned about either of the candidates
7704 // for a signedness conversion to the context type...
7705 if (!Suspicious) return;
7706
7707 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007708 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007709 return;
7710
John McCallcc7e5bf2010-05-06 08:58:33 +00007711 // ...then check whether it would have warned about either of the
7712 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007713 if (E->getType() == T) return;
7714
7715 Suspicious = false;
7716 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7717 E->getType(), CC, &Suspicious);
7718 if (!Suspicious)
7719 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007720 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007721}
7722
Richard Trieu65724892014-11-15 06:37:39 +00007723/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7724/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007725void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007726 if (S.getLangOpts().Bool)
7727 return;
7728 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7729}
7730
John McCallcc7e5bf2010-05-06 08:58:33 +00007731/// AnalyzeImplicitConversions - Find and report any interesting
7732/// implicit conversions in the given expression. There are a couple
7733/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007734void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007735 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007736 Expr *E = OrigE->IgnoreParenImpCasts();
7737
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007738 if (E->isTypeDependent() || E->isValueDependent())
7739 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007740
John McCallcc7e5bf2010-05-06 08:58:33 +00007741 // For conditional operators, we analyze the arguments as if they
7742 // were being fed directly into the output.
7743 if (isa<ConditionalOperator>(E)) {
7744 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007745 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007746 return;
7747 }
7748
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007749 // Check implicit argument conversions for function calls.
7750 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7751 CheckImplicitArgumentConversions(S, Call, CC);
7752
John McCallcc7e5bf2010-05-06 08:58:33 +00007753 // Go ahead and check any implicit conversions we might have skipped.
7754 // The non-canonical typecheck is just an optimization;
7755 // CheckImplicitConversion will filter out dead implicit conversions.
7756 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007757 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007758
7759 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007760
7761 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7762 // The bound subexpressions in a PseudoObjectExpr are not reachable
7763 // as transitive children.
7764 // FIXME: Use a more uniform representation for this.
7765 for (auto *SE : POE->semantics())
7766 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7767 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007768 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007769
John McCallcc7e5bf2010-05-06 08:58:33 +00007770 // Skip past explicit casts.
7771 if (isa<ExplicitCastExpr>(E)) {
7772 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007773 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007774 }
7775
John McCalld2a53122010-11-09 23:24:47 +00007776 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7777 // Do a somewhat different check with comparison operators.
7778 if (BO->isComparisonOp())
7779 return AnalyzeComparison(S, BO);
7780
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007781 // And with simple assignments.
7782 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007783 return AnalyzeAssignment(S, BO);
7784 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007785
7786 // These break the otherwise-useful invariant below. Fortunately,
7787 // we don't really need to recurse into them, because any internal
7788 // expressions should have been analyzed already when they were
7789 // built into statements.
7790 if (isa<StmtExpr>(E)) return;
7791
7792 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007793 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007794
7795 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007796 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007797 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007798 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007799 for (Stmt *SubStmt : E->children()) {
7800 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007801 if (!ChildExpr)
7802 continue;
7803
Richard Trieu955231d2014-01-25 01:10:35 +00007804 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007805 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007806 // Ignore checking string literals that are in logical and operators.
7807 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007808 continue;
7809 AnalyzeImplicitConversions(S, ChildExpr, CC);
7810 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007811
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007812 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007813 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7814 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007815 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007816
7817 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7818 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007819 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007820 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007821
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007822 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7823 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007824 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007825}
7826
7827} // end anonymous namespace
7828
Richard Trieuc1888e02014-06-28 23:25:37 +00007829// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7830// Returns true when emitting a warning about taking the address of a reference.
7831static bool CheckForReference(Sema &SemaRef, const Expr *E,
7832 PartialDiagnostic PD) {
7833 E = E->IgnoreParenImpCasts();
7834
7835 const FunctionDecl *FD = nullptr;
7836
7837 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7838 if (!DRE->getDecl()->getType()->isReferenceType())
7839 return false;
7840 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7841 if (!M->getMemberDecl()->getType()->isReferenceType())
7842 return false;
7843 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007844 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007845 return false;
7846 FD = Call->getDirectCallee();
7847 } else {
7848 return false;
7849 }
7850
7851 SemaRef.Diag(E->getExprLoc(), PD);
7852
7853 // If possible, point to location of function.
7854 if (FD) {
7855 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7856 }
7857
7858 return true;
7859}
7860
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007861// Returns true if the SourceLocation is expanded from any macro body.
7862// Returns false if the SourceLocation is invalid, is from not in a macro
7863// expansion, or is from expanded from a top-level macro argument.
7864static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7865 if (Loc.isInvalid())
7866 return false;
7867
7868 while (Loc.isMacroID()) {
7869 if (SM.isMacroBodyExpansion(Loc))
7870 return true;
7871 Loc = SM.getImmediateMacroCallerLoc(Loc);
7872 }
7873
7874 return false;
7875}
7876
Richard Trieu3bb8b562014-02-26 02:36:06 +00007877/// \brief Diagnose pointers that are always non-null.
7878/// \param E the expression containing the pointer
7879/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7880/// compared to a null pointer
7881/// \param IsEqual True when the comparison is equal to a null pointer
7882/// \param Range Extra SourceRange to highlight in the diagnostic
7883void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7884 Expr::NullPointerConstantKind NullKind,
7885 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007886 if (!E)
7887 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007888
7889 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007890 if (E->getExprLoc().isMacroID()) {
7891 const SourceManager &SM = getSourceManager();
7892 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7893 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007894 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007895 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007896 E = E->IgnoreImpCasts();
7897
7898 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7899
Richard Trieuf7432752014-06-06 21:39:26 +00007900 if (isa<CXXThisExpr>(E)) {
7901 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7902 : diag::warn_this_bool_conversion;
7903 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7904 return;
7905 }
7906
Richard Trieu3bb8b562014-02-26 02:36:06 +00007907 bool IsAddressOf = false;
7908
7909 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7910 if (UO->getOpcode() != UO_AddrOf)
7911 return;
7912 IsAddressOf = true;
7913 E = UO->getSubExpr();
7914 }
7915
Richard Trieuc1888e02014-06-28 23:25:37 +00007916 if (IsAddressOf) {
7917 unsigned DiagID = IsCompare
7918 ? diag::warn_address_of_reference_null_compare
7919 : diag::warn_address_of_reference_bool_conversion;
7920 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7921 << IsEqual;
7922 if (CheckForReference(*this, E, PD)) {
7923 return;
7924 }
7925 }
7926
George Burgess IV850269a2015-12-08 22:02:00 +00007927 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7928 std::string Str;
7929 llvm::raw_string_ostream S(Str);
7930 E->printPretty(S, nullptr, getPrintingPolicy());
7931 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7932 : diag::warn_cast_nonnull_to_bool;
7933 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7934 << E->getSourceRange() << Range << IsEqual;
7935 };
7936
7937 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
7938 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
7939 if (auto *Callee = Call->getDirectCallee()) {
7940 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7941 ComplainAboutNonnullParamOrCall(false);
7942 return;
7943 }
7944 }
7945 }
7946
Richard Trieu3bb8b562014-02-26 02:36:06 +00007947 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007948 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007949 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7950 D = R->getDecl();
7951 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7952 D = M->getMemberDecl();
7953 }
7954
7955 // Weak Decls can be null.
7956 if (!D || D->isWeak())
7957 return;
George Burgess IV850269a2015-12-08 22:02:00 +00007958
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007959 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00007960 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
7961 if (getCurFunction() &&
7962 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
7963 if (PV->hasAttr<NonNullAttr>()) {
7964 ComplainAboutNonnullParamOrCall(true);
7965 return;
7966 }
7967
7968 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7969 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
7970 assert(ParamIter != FD->param_end());
7971 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
7972
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007973 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7974 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00007975 ComplainAboutNonnullParamOrCall(true);
7976 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007977 }
George Burgess IV850269a2015-12-08 22:02:00 +00007978
7979 for (unsigned ArgNo : NonNull->args()) {
7980 if (ArgNo == ParamNo) {
7981 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007982 return;
7983 }
George Burgess IV850269a2015-12-08 22:02:00 +00007984 }
7985 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007986 }
7987 }
George Burgess IV850269a2015-12-08 22:02:00 +00007988 }
7989
Richard Trieu3bb8b562014-02-26 02:36:06 +00007990 QualType T = D->getType();
7991 const bool IsArray = T->isArrayType();
7992 const bool IsFunction = T->isFunctionType();
7993
Richard Trieuc1888e02014-06-28 23:25:37 +00007994 // Address of function is used to silence the function warning.
7995 if (IsAddressOf && IsFunction) {
7996 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007997 }
7998
7999 // Found nothing.
8000 if (!IsAddressOf && !IsFunction && !IsArray)
8001 return;
8002
8003 // Pretty print the expression for the diagnostic.
8004 std::string Str;
8005 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008006 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008007
8008 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8009 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008010 enum {
8011 AddressOf,
8012 FunctionPointer,
8013 ArrayPointer
8014 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008015 if (IsAddressOf)
8016 DiagType = AddressOf;
8017 else if (IsFunction)
8018 DiagType = FunctionPointer;
8019 else if (IsArray)
8020 DiagType = ArrayPointer;
8021 else
8022 llvm_unreachable("Could not determine diagnostic.");
8023 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8024 << Range << IsEqual;
8025
8026 if (!IsFunction)
8027 return;
8028
8029 // Suggest '&' to silence the function warning.
8030 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8031 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8032
8033 // Check to see if '()' fixit should be emitted.
8034 QualType ReturnType;
8035 UnresolvedSet<4> NonTemplateOverloads;
8036 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8037 if (ReturnType.isNull())
8038 return;
8039
8040 if (IsCompare) {
8041 // There are two cases here. If there is null constant, the only suggest
8042 // for a pointer return type. If the null is 0, then suggest if the return
8043 // type is a pointer or an integer type.
8044 if (!ReturnType->isPointerType()) {
8045 if (NullKind == Expr::NPCK_ZeroExpression ||
8046 NullKind == Expr::NPCK_ZeroLiteral) {
8047 if (!ReturnType->isIntegerType())
8048 return;
8049 } else {
8050 return;
8051 }
8052 }
8053 } else { // !IsCompare
8054 // For function to bool, only suggest if the function pointer has bool
8055 // return type.
8056 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8057 return;
8058 }
8059 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008060 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008061}
8062
John McCallcc7e5bf2010-05-06 08:58:33 +00008063/// Diagnoses "dangerous" implicit conversions within the given
8064/// expression (which is a full expression). Implements -Wconversion
8065/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008066///
8067/// \param CC the "context" location of the implicit conversion, i.e.
8068/// the most location of the syntactic entity requiring the implicit
8069/// conversion
8070void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008071 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008072 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008073 return;
8074
8075 // Don't diagnose for value- or type-dependent expressions.
8076 if (E->isTypeDependent() || E->isValueDependent())
8077 return;
8078
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008079 // Check for array bounds violations in cases where the check isn't triggered
8080 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8081 // ArraySubscriptExpr is on the RHS of a variable initialization.
8082 CheckArrayAccess(E);
8083
John McCallacf0ee52010-10-08 02:01:28 +00008084 // This is not the right CC for (e.g.) a variable initialization.
8085 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008086}
8087
Richard Trieu65724892014-11-15 06:37:39 +00008088/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8089/// Input argument E is a logical expression.
8090void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8091 ::CheckBoolLikeConversion(*this, E, CC);
8092}
8093
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008094/// Diagnose when expression is an integer constant expression and its evaluation
8095/// results in integer overflow
8096void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008097 // Use a work list to deal with nested struct initializers.
8098 SmallVector<Expr *, 2> Exprs(1, E);
8099
8100 do {
8101 Expr *E = Exprs.pop_back_val();
8102
8103 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8104 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8105 continue;
8106 }
8107
8108 if (auto InitList = dyn_cast<InitListExpr>(E))
8109 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8110 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008111}
8112
Richard Smithc406cb72013-01-17 01:17:56 +00008113namespace {
8114/// \brief Visitor for expressions which looks for unsequenced operations on the
8115/// same object.
8116class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008117 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8118
Richard Smithc406cb72013-01-17 01:17:56 +00008119 /// \brief A tree of sequenced regions within an expression. Two regions are
8120 /// unsequenced if one is an ancestor or a descendent of the other. When we
8121 /// finish processing an expression with sequencing, such as a comma
8122 /// expression, we fold its tree nodes into its parent, since they are
8123 /// unsequenced with respect to nodes we will visit later.
8124 class SequenceTree {
8125 struct Value {
8126 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8127 unsigned Parent : 31;
8128 bool Merged : 1;
8129 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008130 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008131
8132 public:
8133 /// \brief A region within an expression which may be sequenced with respect
8134 /// to some other region.
8135 class Seq {
8136 explicit Seq(unsigned N) : Index(N) {}
8137 unsigned Index;
8138 friend class SequenceTree;
8139 public:
8140 Seq() : Index(0) {}
8141 };
8142
8143 SequenceTree() { Values.push_back(Value(0)); }
8144 Seq root() const { return Seq(0); }
8145
8146 /// \brief Create a new sequence of operations, which is an unsequenced
8147 /// subset of \p Parent. This sequence of operations is sequenced with
8148 /// respect to other children of \p Parent.
8149 Seq allocate(Seq Parent) {
8150 Values.push_back(Value(Parent.Index));
8151 return Seq(Values.size() - 1);
8152 }
8153
8154 /// \brief Merge a sequence of operations into its parent.
8155 void merge(Seq S) {
8156 Values[S.Index].Merged = true;
8157 }
8158
8159 /// \brief Determine whether two operations are unsequenced. This operation
8160 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8161 /// should have been merged into its parent as appropriate.
8162 bool isUnsequenced(Seq Cur, Seq Old) {
8163 unsigned C = representative(Cur.Index);
8164 unsigned Target = representative(Old.Index);
8165 while (C >= Target) {
8166 if (C == Target)
8167 return true;
8168 C = Values[C].Parent;
8169 }
8170 return false;
8171 }
8172
8173 private:
8174 /// \brief Pick a representative for a sequence.
8175 unsigned representative(unsigned K) {
8176 if (Values[K].Merged)
8177 // Perform path compression as we go.
8178 return Values[K].Parent = representative(Values[K].Parent);
8179 return K;
8180 }
8181 };
8182
8183 /// An object for which we can track unsequenced uses.
8184 typedef NamedDecl *Object;
8185
8186 /// Different flavors of object usage which we track. We only track the
8187 /// least-sequenced usage of each kind.
8188 enum UsageKind {
8189 /// A read of an object. Multiple unsequenced reads are OK.
8190 UK_Use,
8191 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008192 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008193 UK_ModAsValue,
8194 /// A modification of an object which is not sequenced before the value
8195 /// computation of the expression, such as n++.
8196 UK_ModAsSideEffect,
8197
8198 UK_Count = UK_ModAsSideEffect + 1
8199 };
8200
8201 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008202 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008203 Expr *Use;
8204 SequenceTree::Seq Seq;
8205 };
8206
8207 struct UsageInfo {
8208 UsageInfo() : Diagnosed(false) {}
8209 Usage Uses[UK_Count];
8210 /// Have we issued a diagnostic for this variable already?
8211 bool Diagnosed;
8212 };
8213 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8214
8215 Sema &SemaRef;
8216 /// Sequenced regions within the expression.
8217 SequenceTree Tree;
8218 /// Declaration modifications and references which we have seen.
8219 UsageInfoMap UsageMap;
8220 /// The region we are currently within.
8221 SequenceTree::Seq Region;
8222 /// Filled in with declarations which were modified as a side-effect
8223 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008224 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008225 /// Expressions to check later. We defer checking these to reduce
8226 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008227 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008228
8229 /// RAII object wrapping the visitation of a sequenced subexpression of an
8230 /// expression. At the end of this process, the side-effects of the evaluation
8231 /// become sequenced with respect to the value computation of the result, so
8232 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8233 /// UK_ModAsValue.
8234 struct SequencedSubexpression {
8235 SequencedSubexpression(SequenceChecker &Self)
8236 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8237 Self.ModAsSideEffect = &ModAsSideEffect;
8238 }
8239 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008240 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8241 MI != ME; ++MI) {
8242 UsageInfo &U = Self.UsageMap[MI->first];
8243 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8244 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8245 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008246 }
8247 Self.ModAsSideEffect = OldModAsSideEffect;
8248 }
8249
8250 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008251 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8252 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008253 };
8254
Richard Smith40238f02013-06-20 22:21:56 +00008255 /// RAII object wrapping the visitation of a subexpression which we might
8256 /// choose to evaluate as a constant. If any subexpression is evaluated and
8257 /// found to be non-constant, this allows us to suppress the evaluation of
8258 /// the outer expression.
8259 class EvaluationTracker {
8260 public:
8261 EvaluationTracker(SequenceChecker &Self)
8262 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8263 Self.EvalTracker = this;
8264 }
8265 ~EvaluationTracker() {
8266 Self.EvalTracker = Prev;
8267 if (Prev)
8268 Prev->EvalOK &= EvalOK;
8269 }
8270
8271 bool evaluate(const Expr *E, bool &Result) {
8272 if (!EvalOK || E->isValueDependent())
8273 return false;
8274 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8275 return EvalOK;
8276 }
8277
8278 private:
8279 SequenceChecker &Self;
8280 EvaluationTracker *Prev;
8281 bool EvalOK;
8282 } *EvalTracker;
8283
Richard Smithc406cb72013-01-17 01:17:56 +00008284 /// \brief Find the object which is produced by the specified expression,
8285 /// if any.
8286 Object getObject(Expr *E, bool Mod) const {
8287 E = E->IgnoreParenCasts();
8288 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8289 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8290 return getObject(UO->getSubExpr(), Mod);
8291 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8292 if (BO->getOpcode() == BO_Comma)
8293 return getObject(BO->getRHS(), Mod);
8294 if (Mod && BO->isAssignmentOp())
8295 return getObject(BO->getLHS(), Mod);
8296 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8297 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8298 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8299 return ME->getMemberDecl();
8300 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8301 // FIXME: If this is a reference, map through to its value.
8302 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008303 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008304 }
8305
8306 /// \brief Note that an object was modified or used by an expression.
8307 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8308 Usage &U = UI.Uses[UK];
8309 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8310 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8311 ModAsSideEffect->push_back(std::make_pair(O, U));
8312 U.Use = Ref;
8313 U.Seq = Region;
8314 }
8315 }
8316 /// \brief Check whether a modification or use conflicts with a prior usage.
8317 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8318 bool IsModMod) {
8319 if (UI.Diagnosed)
8320 return;
8321
8322 const Usage &U = UI.Uses[OtherKind];
8323 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8324 return;
8325
8326 Expr *Mod = U.Use;
8327 Expr *ModOrUse = Ref;
8328 if (OtherKind == UK_Use)
8329 std::swap(Mod, ModOrUse);
8330
8331 SemaRef.Diag(Mod->getExprLoc(),
8332 IsModMod ? diag::warn_unsequenced_mod_mod
8333 : diag::warn_unsequenced_mod_use)
8334 << O << SourceRange(ModOrUse->getExprLoc());
8335 UI.Diagnosed = true;
8336 }
8337
8338 void notePreUse(Object O, Expr *Use) {
8339 UsageInfo &U = UsageMap[O];
8340 // Uses conflict with other modifications.
8341 checkUsage(O, U, Use, UK_ModAsValue, false);
8342 }
8343 void notePostUse(Object O, Expr *Use) {
8344 UsageInfo &U = UsageMap[O];
8345 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8346 addUsage(U, O, Use, UK_Use);
8347 }
8348
8349 void notePreMod(Object O, Expr *Mod) {
8350 UsageInfo &U = UsageMap[O];
8351 // Modifications conflict with other modifications and with uses.
8352 checkUsage(O, U, Mod, UK_ModAsValue, true);
8353 checkUsage(O, U, Mod, UK_Use, false);
8354 }
8355 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8356 UsageInfo &U = UsageMap[O];
8357 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8358 addUsage(U, O, Use, UK);
8359 }
8360
8361public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008362 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008363 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8364 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008365 Visit(E);
8366 }
8367
8368 void VisitStmt(Stmt *S) {
8369 // Skip all statements which aren't expressions for now.
8370 }
8371
8372 void VisitExpr(Expr *E) {
8373 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008374 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008375 }
8376
8377 void VisitCastExpr(CastExpr *E) {
8378 Object O = Object();
8379 if (E->getCastKind() == CK_LValueToRValue)
8380 O = getObject(E->getSubExpr(), false);
8381
8382 if (O)
8383 notePreUse(O, E);
8384 VisitExpr(E);
8385 if (O)
8386 notePostUse(O, E);
8387 }
8388
8389 void VisitBinComma(BinaryOperator *BO) {
8390 // C++11 [expr.comma]p1:
8391 // Every value computation and side effect associated with the left
8392 // expression is sequenced before every value computation and side
8393 // effect associated with the right expression.
8394 SequenceTree::Seq LHS = Tree.allocate(Region);
8395 SequenceTree::Seq RHS = Tree.allocate(Region);
8396 SequenceTree::Seq OldRegion = Region;
8397
8398 {
8399 SequencedSubexpression SeqLHS(*this);
8400 Region = LHS;
8401 Visit(BO->getLHS());
8402 }
8403
8404 Region = RHS;
8405 Visit(BO->getRHS());
8406
8407 Region = OldRegion;
8408
8409 // Forget that LHS and RHS are sequenced. They are both unsequenced
8410 // with respect to other stuff.
8411 Tree.merge(LHS);
8412 Tree.merge(RHS);
8413 }
8414
8415 void VisitBinAssign(BinaryOperator *BO) {
8416 // The modification is sequenced after the value computation of the LHS
8417 // and RHS, so check it before inspecting the operands and update the
8418 // map afterwards.
8419 Object O = getObject(BO->getLHS(), true);
8420 if (!O)
8421 return VisitExpr(BO);
8422
8423 notePreMod(O, BO);
8424
8425 // C++11 [expr.ass]p7:
8426 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8427 // only once.
8428 //
8429 // Therefore, for a compound assignment operator, O is considered used
8430 // everywhere except within the evaluation of E1 itself.
8431 if (isa<CompoundAssignOperator>(BO))
8432 notePreUse(O, BO);
8433
8434 Visit(BO->getLHS());
8435
8436 if (isa<CompoundAssignOperator>(BO))
8437 notePostUse(O, BO);
8438
8439 Visit(BO->getRHS());
8440
Richard Smith83e37bee2013-06-26 23:16:51 +00008441 // C++11 [expr.ass]p1:
8442 // the assignment is sequenced [...] before the value computation of the
8443 // assignment expression.
8444 // C11 6.5.16/3 has no such rule.
8445 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8446 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008447 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008448
Richard Smithc406cb72013-01-17 01:17:56 +00008449 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8450 VisitBinAssign(CAO);
8451 }
8452
8453 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8454 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8455 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8456 Object O = getObject(UO->getSubExpr(), true);
8457 if (!O)
8458 return VisitExpr(UO);
8459
8460 notePreMod(O, UO);
8461 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008462 // C++11 [expr.pre.incr]p1:
8463 // the expression ++x is equivalent to x+=1
8464 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8465 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008466 }
8467
8468 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8469 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8470 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8471 Object O = getObject(UO->getSubExpr(), true);
8472 if (!O)
8473 return VisitExpr(UO);
8474
8475 notePreMod(O, UO);
8476 Visit(UO->getSubExpr());
8477 notePostMod(O, UO, UK_ModAsSideEffect);
8478 }
8479
8480 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8481 void VisitBinLOr(BinaryOperator *BO) {
8482 // The side-effects of the LHS of an '&&' are sequenced before the
8483 // value computation of the RHS, and hence before the value computation
8484 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8485 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008486 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008487 {
8488 SequencedSubexpression Sequenced(*this);
8489 Visit(BO->getLHS());
8490 }
8491
8492 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008493 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008494 if (!Result)
8495 Visit(BO->getRHS());
8496 } else {
8497 // Check for unsequenced operations in the RHS, treating it as an
8498 // entirely separate evaluation.
8499 //
8500 // FIXME: If there are operations in the RHS which are unsequenced
8501 // with respect to operations outside the RHS, and those operations
8502 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008503 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008504 }
Richard Smithc406cb72013-01-17 01:17:56 +00008505 }
8506 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008507 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008508 {
8509 SequencedSubexpression Sequenced(*this);
8510 Visit(BO->getLHS());
8511 }
8512
8513 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008514 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008515 if (Result)
8516 Visit(BO->getRHS());
8517 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008518 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008519 }
Richard Smithc406cb72013-01-17 01:17:56 +00008520 }
8521
8522 // Only visit the condition, unless we can be sure which subexpression will
8523 // be chosen.
8524 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008525 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008526 {
8527 SequencedSubexpression Sequenced(*this);
8528 Visit(CO->getCond());
8529 }
Richard Smithc406cb72013-01-17 01:17:56 +00008530
8531 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008532 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008533 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008534 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008535 WorkList.push_back(CO->getTrueExpr());
8536 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008537 }
Richard Smithc406cb72013-01-17 01:17:56 +00008538 }
8539
Richard Smithe3dbfe02013-06-30 10:40:20 +00008540 void VisitCallExpr(CallExpr *CE) {
8541 // C++11 [intro.execution]p15:
8542 // When calling a function [...], every value computation and side effect
8543 // associated with any argument expression, or with the postfix expression
8544 // designating the called function, is sequenced before execution of every
8545 // expression or statement in the body of the function [and thus before
8546 // the value computation of its result].
8547 SequencedSubexpression Sequenced(*this);
8548 Base::VisitCallExpr(CE);
8549
8550 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8551 }
8552
Richard Smithc406cb72013-01-17 01:17:56 +00008553 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008554 // This is a call, so all subexpressions are sequenced before the result.
8555 SequencedSubexpression Sequenced(*this);
8556
Richard Smithc406cb72013-01-17 01:17:56 +00008557 if (!CCE->isListInitialization())
8558 return VisitExpr(CCE);
8559
8560 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008561 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008562 SequenceTree::Seq Parent = Region;
8563 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8564 E = CCE->arg_end();
8565 I != E; ++I) {
8566 Region = Tree.allocate(Parent);
8567 Elts.push_back(Region);
8568 Visit(*I);
8569 }
8570
8571 // Forget that the initializers are sequenced.
8572 Region = Parent;
8573 for (unsigned I = 0; I < Elts.size(); ++I)
8574 Tree.merge(Elts[I]);
8575 }
8576
8577 void VisitInitListExpr(InitListExpr *ILE) {
8578 if (!SemaRef.getLangOpts().CPlusPlus11)
8579 return VisitExpr(ILE);
8580
8581 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008582 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008583 SequenceTree::Seq Parent = Region;
8584 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8585 Expr *E = ILE->getInit(I);
8586 if (!E) continue;
8587 Region = Tree.allocate(Parent);
8588 Elts.push_back(Region);
8589 Visit(E);
8590 }
8591
8592 // Forget that the initializers are sequenced.
8593 Region = Parent;
8594 for (unsigned I = 0; I < Elts.size(); ++I)
8595 Tree.merge(Elts[I]);
8596 }
8597};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008598} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008599
8600void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008601 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008602 WorkList.push_back(E);
8603 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008604 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008605 SequenceChecker(*this, Item, WorkList);
8606 }
Richard Smithc406cb72013-01-17 01:17:56 +00008607}
8608
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008609void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8610 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008611 CheckImplicitConversions(E, CheckLoc);
8612 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008613 if (!IsConstexpr && !E->isValueDependent())
8614 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008615}
8616
John McCall1f425642010-11-11 03:21:53 +00008617void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8618 FieldDecl *BitField,
8619 Expr *Init) {
8620 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8621}
8622
David Majnemer61a5bbf2015-04-07 22:08:51 +00008623static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8624 SourceLocation Loc) {
8625 if (!PType->isVariablyModifiedType())
8626 return;
8627 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8628 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8629 return;
8630 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008631 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8632 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8633 return;
8634 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008635 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8636 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8637 return;
8638 }
8639
8640 const ArrayType *AT = S.Context.getAsArrayType(PType);
8641 if (!AT)
8642 return;
8643
8644 if (AT->getSizeModifier() != ArrayType::Star) {
8645 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8646 return;
8647 }
8648
8649 S.Diag(Loc, diag::err_array_star_in_function_definition);
8650}
8651
Mike Stump0c2ec772010-01-21 03:59:47 +00008652/// CheckParmsForFunctionDef - Check that the parameters of the given
8653/// function are appropriate for the definition of a function. This
8654/// takes care of any checks that cannot be performed on the
8655/// declaration itself, e.g., that the types of each of the function
8656/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008657bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8658 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008659 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008660 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008661 for (; P != PEnd; ++P) {
8662 ParmVarDecl *Param = *P;
8663
Mike Stump0c2ec772010-01-21 03:59:47 +00008664 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8665 // function declarator that is part of a function definition of
8666 // that function shall not have incomplete type.
8667 //
8668 // This is also C++ [dcl.fct]p6.
8669 if (!Param->isInvalidDecl() &&
8670 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008671 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008672 Param->setInvalidDecl();
8673 HasInvalidParm = true;
8674 }
8675
8676 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8677 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008678 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008679 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008680 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008681 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008682 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008683
8684 // C99 6.7.5.3p12:
8685 // If the function declarator is not part of a definition of that
8686 // function, parameters may have incomplete type and may use the [*]
8687 // notation in their sequences of declarator specifiers to specify
8688 // variable length array types.
8689 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008690 // FIXME: This diagnostic should point the '[*]' if source-location
8691 // information is added for it.
8692 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008693
8694 // MSVC destroys objects passed by value in the callee. Therefore a
8695 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008696 // object's destructor. However, we don't perform any direct access check
8697 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008698 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8699 .getCXXABI()
8700 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008701 if (!Param->isInvalidDecl()) {
8702 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8703 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8704 if (!ClassDecl->isInvalidDecl() &&
8705 !ClassDecl->hasIrrelevantDestructor() &&
8706 !ClassDecl->isDependentContext()) {
8707 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8708 MarkFunctionReferenced(Param->getLocation(), Destructor);
8709 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8710 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008711 }
8712 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008713 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008714
8715 // Parameters with the pass_object_size attribute only need to be marked
8716 // constant at function definitions. Because we lack information about
8717 // whether we're on a declaration or definition when we're instantiating the
8718 // attribute, we need to check for constness here.
8719 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8720 if (!Param->getType().isConstQualified())
8721 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8722 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008723 }
8724
8725 return HasInvalidParm;
8726}
John McCall2b5c1b22010-08-12 21:44:57 +00008727
8728/// CheckCastAlign - Implements -Wcast-align, which warns when a
8729/// pointer cast increases the alignment requirements.
8730void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8731 // This is actually a lot of work to potentially be doing on every
8732 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008733 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008734 return;
8735
8736 // Ignore dependent types.
8737 if (T->isDependentType() || Op->getType()->isDependentType())
8738 return;
8739
8740 // Require that the destination be a pointer type.
8741 const PointerType *DestPtr = T->getAs<PointerType>();
8742 if (!DestPtr) return;
8743
8744 // If the destination has alignment 1, we're done.
8745 QualType DestPointee = DestPtr->getPointeeType();
8746 if (DestPointee->isIncompleteType()) return;
8747 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8748 if (DestAlign.isOne()) return;
8749
8750 // Require that the source be a pointer type.
8751 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8752 if (!SrcPtr) return;
8753 QualType SrcPointee = SrcPtr->getPointeeType();
8754
8755 // Whitelist casts from cv void*. We already implicitly
8756 // whitelisted casts to cv void*, since they have alignment 1.
8757 // Also whitelist casts involving incomplete types, which implicitly
8758 // includes 'void'.
8759 if (SrcPointee->isIncompleteType()) return;
8760
8761 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8762 if (SrcAlign >= DestAlign) return;
8763
8764 Diag(TRange.getBegin(), diag::warn_cast_align)
8765 << Op->getType() << T
8766 << static_cast<unsigned>(SrcAlign.getQuantity())
8767 << static_cast<unsigned>(DestAlign.getQuantity())
8768 << TRange << Op->getSourceRange();
8769}
8770
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008771static const Type* getElementType(const Expr *BaseExpr) {
8772 const Type* EltType = BaseExpr->getType().getTypePtr();
8773 if (EltType->isAnyPointerType())
8774 return EltType->getPointeeType().getTypePtr();
8775 else if (EltType->isArrayType())
8776 return EltType->getBaseElementTypeUnsafe();
8777 return EltType;
8778}
8779
Chandler Carruth28389f02011-08-05 09:10:50 +00008780/// \brief Check whether this array fits the idiom of a size-one tail padded
8781/// array member of a struct.
8782///
8783/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8784/// commonly used to emulate flexible arrays in C89 code.
8785static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8786 const NamedDecl *ND) {
8787 if (Size != 1 || !ND) return false;
8788
8789 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8790 if (!FD) return false;
8791
8792 // Don't consider sizes resulting from macro expansions or template argument
8793 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008794
8795 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008796 while (TInfo) {
8797 TypeLoc TL = TInfo->getTypeLoc();
8798 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008799 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8800 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008801 TInfo = TDL->getTypeSourceInfo();
8802 continue;
8803 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008804 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8805 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008806 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8807 return false;
8808 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008809 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008810 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008811
8812 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008813 if (!RD) return false;
8814 if (RD->isUnion()) return false;
8815 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8816 if (!CRD->isStandardLayout()) return false;
8817 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008818
Benjamin Kramer8c543672011-08-06 03:04:42 +00008819 // See if this is the last field decl in the record.
8820 const Decl *D = FD;
8821 while ((D = D->getNextDeclInContext()))
8822 if (isa<FieldDecl>(D))
8823 return false;
8824 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008825}
8826
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008827void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008828 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008829 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008830 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008831 if (IndexExpr->isValueDependent())
8832 return;
8833
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008834 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008835 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008836 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008837 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008838 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008839 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008840
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008841 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008842 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008843 return;
Richard Smith13f67182011-12-16 19:31:14 +00008844 if (IndexNegated)
8845 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008846
Craig Topperc3ec1492014-05-26 06:22:03 +00008847 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008848 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8849 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008850 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008851 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008852
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008853 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008854 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008855 if (!size.isStrictlyPositive())
8856 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008857
8858 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008859 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008860 // Make sure we're comparing apples to apples when comparing index to size
8861 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8862 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008863 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008864 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008865 if (ptrarith_typesize != array_typesize) {
8866 // There's a cast to a different size type involved
8867 uint64_t ratio = array_typesize / ptrarith_typesize;
8868 // TODO: Be smarter about handling cases where array_typesize is not a
8869 // multiple of ptrarith_typesize
8870 if (ptrarith_typesize * ratio == array_typesize)
8871 size *= llvm::APInt(size.getBitWidth(), ratio);
8872 }
8873 }
8874
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008875 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008876 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008877 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008878 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008879
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008880 // For array subscripting the index must be less than size, but for pointer
8881 // arithmetic also allow the index (offset) to be equal to size since
8882 // computing the next address after the end of the array is legal and
8883 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008884 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008885 return;
8886
8887 // Also don't warn for arrays of size 1 which are members of some
8888 // structure. These are often used to approximate flexible arrays in C89
8889 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008890 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008891 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008892
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008893 // Suppress the warning if the subscript expression (as identified by the
8894 // ']' location) and the index expression are both from macro expansions
8895 // within a system header.
8896 if (ASE) {
8897 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8898 ASE->getRBracketLoc());
8899 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8900 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8901 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008902 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008903 return;
8904 }
8905 }
8906
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008907 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008908 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008909 DiagID = diag::warn_array_index_exceeds_bounds;
8910
8911 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8912 PDiag(DiagID) << index.toString(10, true)
8913 << size.toString(10, true)
8914 << (unsigned)size.getLimitedValue(~0U)
8915 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008916 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008917 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008918 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008919 DiagID = diag::warn_ptr_arith_precedes_bounds;
8920 if (index.isNegative()) index = -index;
8921 }
8922
8923 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8924 PDiag(DiagID) << index.toString(10, true)
8925 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008926 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008927
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008928 if (!ND) {
8929 // Try harder to find a NamedDecl to point at in the note.
8930 while (const ArraySubscriptExpr *ASE =
8931 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8932 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8934 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8935 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8936 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8937 }
8938
Chandler Carruth1af88f12011-02-17 21:10:52 +00008939 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008940 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8941 PDiag(diag::note_array_index_out_of_bounds)
8942 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008943}
8944
Ted Kremenekdf26df72011-03-01 18:41:00 +00008945void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008946 int AllowOnePastEnd = 0;
8947 while (expr) {
8948 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008949 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008950 case Stmt::ArraySubscriptExprClass: {
8951 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008952 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008953 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008954 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008955 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008956 case Stmt::OMPArraySectionExprClass: {
8957 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8958 if (ASE->getLowerBound())
8959 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8960 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8961 return;
8962 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008963 case Stmt::UnaryOperatorClass: {
8964 // Only unwrap the * and & unary operators
8965 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8966 expr = UO->getSubExpr();
8967 switch (UO->getOpcode()) {
8968 case UO_AddrOf:
8969 AllowOnePastEnd++;
8970 break;
8971 case UO_Deref:
8972 AllowOnePastEnd--;
8973 break;
8974 default:
8975 return;
8976 }
8977 break;
8978 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008979 case Stmt::ConditionalOperatorClass: {
8980 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8981 if (const Expr *lhs = cond->getLHS())
8982 CheckArrayAccess(lhs);
8983 if (const Expr *rhs = cond->getRHS())
8984 CheckArrayAccess(rhs);
8985 return;
8986 }
8987 default:
8988 return;
8989 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008990 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008991}
John McCall31168b02011-06-15 23:02:42 +00008992
8993//===--- CHECK: Objective-C retain cycles ----------------------------------//
8994
8995namespace {
8996 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008997 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008998 VarDecl *Variable;
8999 SourceRange Range;
9000 SourceLocation Loc;
9001 bool Indirect;
9002
9003 void setLocsFrom(Expr *e) {
9004 Loc = e->getExprLoc();
9005 Range = e->getSourceRange();
9006 }
9007 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009008} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009009
9010/// Consider whether capturing the given variable can possibly lead to
9011/// a retain cycle.
9012static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009013 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009014 // lifetime. In MRR, it's captured strongly if the variable is
9015 // __block and has an appropriate type.
9016 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9017 return false;
9018
9019 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009020 if (ref)
9021 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009022 return true;
9023}
9024
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009025static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009026 while (true) {
9027 e = e->IgnoreParens();
9028 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9029 switch (cast->getCastKind()) {
9030 case CK_BitCast:
9031 case CK_LValueBitCast:
9032 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009033 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009034 e = cast->getSubExpr();
9035 continue;
9036
John McCall31168b02011-06-15 23:02:42 +00009037 default:
9038 return false;
9039 }
9040 }
9041
9042 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9043 ObjCIvarDecl *ivar = ref->getDecl();
9044 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9045 return false;
9046
9047 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009048 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009049 return false;
9050
9051 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9052 owner.Indirect = true;
9053 return true;
9054 }
9055
9056 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9057 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9058 if (!var) return false;
9059 return considerVariable(var, ref, owner);
9060 }
9061
John McCall31168b02011-06-15 23:02:42 +00009062 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9063 if (member->isArrow()) return false;
9064
9065 // Don't count this as an indirect ownership.
9066 e = member->getBase();
9067 continue;
9068 }
9069
John McCallfe96e0b2011-11-06 09:01:30 +00009070 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9071 // Only pay attention to pseudo-objects on property references.
9072 ObjCPropertyRefExpr *pre
9073 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9074 ->IgnoreParens());
9075 if (!pre) return false;
9076 if (pre->isImplicitProperty()) return false;
9077 ObjCPropertyDecl *property = pre->getExplicitProperty();
9078 if (!property->isRetaining() &&
9079 !(property->getPropertyIvarDecl() &&
9080 property->getPropertyIvarDecl()->getType()
9081 .getObjCLifetime() == Qualifiers::OCL_Strong))
9082 return false;
9083
9084 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009085 if (pre->isSuperReceiver()) {
9086 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9087 if (!owner.Variable)
9088 return false;
9089 owner.Loc = pre->getLocation();
9090 owner.Range = pre->getSourceRange();
9091 return true;
9092 }
John McCallfe96e0b2011-11-06 09:01:30 +00009093 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9094 ->getSourceExpr());
9095 continue;
9096 }
9097
John McCall31168b02011-06-15 23:02:42 +00009098 // Array ivars?
9099
9100 return false;
9101 }
9102}
9103
9104namespace {
9105 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9106 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9107 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009108 Context(Context), Variable(variable), Capturer(nullptr),
9109 VarWillBeReased(false) {}
9110 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009111 VarDecl *Variable;
9112 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009113 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009114
9115 void VisitDeclRefExpr(DeclRefExpr *ref) {
9116 if (ref->getDecl() == Variable && !Capturer)
9117 Capturer = ref;
9118 }
9119
John McCall31168b02011-06-15 23:02:42 +00009120 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9121 if (Capturer) return;
9122 Visit(ref->getBase());
9123 if (Capturer && ref->isFreeIvar())
9124 Capturer = ref;
9125 }
9126
9127 void VisitBlockExpr(BlockExpr *block) {
9128 // Look inside nested blocks
9129 if (block->getBlockDecl()->capturesVariable(Variable))
9130 Visit(block->getBlockDecl()->getBody());
9131 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009132
9133 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9134 if (Capturer) return;
9135 if (OVE->getSourceExpr())
9136 Visit(OVE->getSourceExpr());
9137 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009138 void VisitBinaryOperator(BinaryOperator *BinOp) {
9139 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9140 return;
9141 Expr *LHS = BinOp->getLHS();
9142 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9143 if (DRE->getDecl() != Variable)
9144 return;
9145 if (Expr *RHS = BinOp->getRHS()) {
9146 RHS = RHS->IgnoreParenCasts();
9147 llvm::APSInt Value;
9148 VarWillBeReased =
9149 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9150 }
9151 }
9152 }
John McCall31168b02011-06-15 23:02:42 +00009153 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009154} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009155
9156/// Check whether the given argument is a block which captures a
9157/// variable.
9158static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9159 assert(owner.Variable && owner.Loc.isValid());
9160
9161 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009162
9163 // Look through [^{...} copy] and Block_copy(^{...}).
9164 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9165 Selector Cmd = ME->getSelector();
9166 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9167 e = ME->getInstanceReceiver();
9168 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009169 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009170 e = e->IgnoreParenCasts();
9171 }
9172 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9173 if (CE->getNumArgs() == 1) {
9174 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009175 if (Fn) {
9176 const IdentifierInfo *FnI = Fn->getIdentifier();
9177 if (FnI && FnI->isStr("_Block_copy")) {
9178 e = CE->getArg(0)->IgnoreParenCasts();
9179 }
9180 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009181 }
9182 }
9183
John McCall31168b02011-06-15 23:02:42 +00009184 BlockExpr *block = dyn_cast<BlockExpr>(e);
9185 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009186 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009187
9188 FindCaptureVisitor visitor(S.Context, owner.Variable);
9189 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009190 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009191}
9192
9193static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9194 RetainCycleOwner &owner) {
9195 assert(capturer);
9196 assert(owner.Variable && owner.Loc.isValid());
9197
9198 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9199 << owner.Variable << capturer->getSourceRange();
9200 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9201 << owner.Indirect << owner.Range;
9202}
9203
9204/// Check for a keyword selector that starts with the word 'add' or
9205/// 'set'.
9206static bool isSetterLikeSelector(Selector sel) {
9207 if (sel.isUnarySelector()) return false;
9208
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009209 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009210 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009211 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009212 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009213 else if (str.startswith("add")) {
9214 // Specially whitelist 'addOperationWithBlock:'.
9215 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9216 return false;
9217 str = str.substr(3);
9218 }
John McCall31168b02011-06-15 23:02:42 +00009219 else
9220 return false;
9221
9222 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009223 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009224}
9225
Benjamin Kramer3a743452015-03-09 15:03:32 +00009226static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9227 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009228 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9229 Message->getReceiverInterface(),
9230 NSAPI::ClassId_NSMutableArray);
9231 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009232 return None;
9233 }
9234
9235 Selector Sel = Message->getSelector();
9236
9237 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9238 S.NSAPIObj->getNSArrayMethodKind(Sel);
9239 if (!MKOpt) {
9240 return None;
9241 }
9242
9243 NSAPI::NSArrayMethodKind MK = *MKOpt;
9244
9245 switch (MK) {
9246 case NSAPI::NSMutableArr_addObject:
9247 case NSAPI::NSMutableArr_insertObjectAtIndex:
9248 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9249 return 0;
9250 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9251 return 1;
9252
9253 default:
9254 return None;
9255 }
9256
9257 return None;
9258}
9259
9260static
9261Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9262 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009263 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9264 Message->getReceiverInterface(),
9265 NSAPI::ClassId_NSMutableDictionary);
9266 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009267 return None;
9268 }
9269
9270 Selector Sel = Message->getSelector();
9271
9272 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9273 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9274 if (!MKOpt) {
9275 return None;
9276 }
9277
9278 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9279
9280 switch (MK) {
9281 case NSAPI::NSMutableDict_setObjectForKey:
9282 case NSAPI::NSMutableDict_setValueForKey:
9283 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9284 return 0;
9285
9286 default:
9287 return None;
9288 }
9289
9290 return None;
9291}
9292
9293static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009294 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9295 Message->getReceiverInterface(),
9296 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009297
Alex Denisov5dfac812015-08-06 04:51:14 +00009298 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9299 Message->getReceiverInterface(),
9300 NSAPI::ClassId_NSMutableOrderedSet);
9301 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009302 return None;
9303 }
9304
9305 Selector Sel = Message->getSelector();
9306
9307 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9308 if (!MKOpt) {
9309 return None;
9310 }
9311
9312 NSAPI::NSSetMethodKind MK = *MKOpt;
9313
9314 switch (MK) {
9315 case NSAPI::NSMutableSet_addObject:
9316 case NSAPI::NSOrderedSet_setObjectAtIndex:
9317 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9318 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9319 return 0;
9320 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9321 return 1;
9322 }
9323
9324 return None;
9325}
9326
9327void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9328 if (!Message->isInstanceMessage()) {
9329 return;
9330 }
9331
9332 Optional<int> ArgOpt;
9333
9334 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9335 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9336 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9337 return;
9338 }
9339
9340 int ArgIndex = *ArgOpt;
9341
Alex Denisove1d882c2015-03-04 17:55:52 +00009342 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9343 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9344 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9345 }
9346
Alex Denisov5dfac812015-08-06 04:51:14 +00009347 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009348 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009349 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009350 Diag(Message->getSourceRange().getBegin(),
9351 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009352 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009353 }
9354 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009355 } else {
9356 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9357
9358 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9359 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9360 }
9361
9362 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9363 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9364 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9365 ValueDecl *Decl = ReceiverRE->getDecl();
9366 Diag(Message->getSourceRange().getBegin(),
9367 diag::warn_objc_circular_container)
9368 << Decl->getName() << Decl->getName();
9369 if (!ArgRE->isObjCSelfExpr()) {
9370 Diag(Decl->getLocation(),
9371 diag::note_objc_circular_container_declared_here)
9372 << Decl->getName();
9373 }
9374 }
9375 }
9376 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9377 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9378 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9379 ObjCIvarDecl *Decl = IvarRE->getDecl();
9380 Diag(Message->getSourceRange().getBegin(),
9381 diag::warn_objc_circular_container)
9382 << Decl->getName() << Decl->getName();
9383 Diag(Decl->getLocation(),
9384 diag::note_objc_circular_container_declared_here)
9385 << Decl->getName();
9386 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009387 }
9388 }
9389 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009390}
9391
John McCall31168b02011-06-15 23:02:42 +00009392/// Check a message send to see if it's likely to cause a retain cycle.
9393void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9394 // Only check instance methods whose selector looks like a setter.
9395 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9396 return;
9397
9398 // Try to find a variable that the receiver is strongly owned by.
9399 RetainCycleOwner owner;
9400 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009401 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009402 return;
9403 } else {
9404 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9405 owner.Variable = getCurMethodDecl()->getSelfDecl();
9406 owner.Loc = msg->getSuperLoc();
9407 owner.Range = msg->getSuperLoc();
9408 }
9409
9410 // Check whether the receiver is captured by any of the arguments.
9411 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9412 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9413 return diagnoseRetainCycle(*this, capturer, owner);
9414}
9415
9416/// Check a property assign to see if it's likely to cause a retain cycle.
9417void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9418 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009419 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009420 return;
9421
9422 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9423 diagnoseRetainCycle(*this, capturer, owner);
9424}
9425
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009426void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9427 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009428 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009429 return;
9430
9431 // Because we don't have an expression for the variable, we have to set the
9432 // location explicitly here.
9433 Owner.Loc = Var->getLocation();
9434 Owner.Range = Var->getSourceRange();
9435
9436 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9437 diagnoseRetainCycle(*this, Capturer, Owner);
9438}
9439
Ted Kremenek9304da92012-12-21 08:04:28 +00009440static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9441 Expr *RHS, bool isProperty) {
9442 // Check if RHS is an Objective-C object literal, which also can get
9443 // immediately zapped in a weak reference. Note that we explicitly
9444 // allow ObjCStringLiterals, since those are designed to never really die.
9445 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009446
Ted Kremenek64873352012-12-21 22:46:35 +00009447 // This enum needs to match with the 'select' in
9448 // warn_objc_arc_literal_assign (off-by-1).
9449 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9450 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9451 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009452
9453 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009454 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009455 << (isProperty ? 0 : 1)
9456 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009457
9458 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009459}
9460
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009461static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9462 Qualifiers::ObjCLifetime LT,
9463 Expr *RHS, bool isProperty) {
9464 // Strip off any implicit cast added to get to the one ARC-specific.
9465 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9466 if (cast->getCastKind() == CK_ARCConsumeObject) {
9467 S.Diag(Loc, diag::warn_arc_retained_assign)
9468 << (LT == Qualifiers::OCL_ExplicitNone)
9469 << (isProperty ? 0 : 1)
9470 << RHS->getSourceRange();
9471 return true;
9472 }
9473 RHS = cast->getSubExpr();
9474 }
9475
9476 if (LT == Qualifiers::OCL_Weak &&
9477 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9478 return true;
9479
9480 return false;
9481}
9482
Ted Kremenekb36234d2012-12-21 08:04:20 +00009483bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9484 QualType LHS, Expr *RHS) {
9485 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9486
9487 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9488 return false;
9489
9490 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9491 return true;
9492
9493 return false;
9494}
9495
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009496void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9497 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009498 QualType LHSType;
9499 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009500 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009501 ObjCPropertyRefExpr *PRE
9502 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9503 if (PRE && !PRE->isImplicitProperty()) {
9504 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9505 if (PD)
9506 LHSType = PD->getType();
9507 }
9508
9509 if (LHSType.isNull())
9510 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009511
9512 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9513
9514 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009515 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009516 getCurFunction()->markSafeWeakUse(LHS);
9517 }
9518
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009519 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9520 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009521
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009522 // FIXME. Check for other life times.
9523 if (LT != Qualifiers::OCL_None)
9524 return;
9525
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009526 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009527 if (PRE->isImplicitProperty())
9528 return;
9529 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9530 if (!PD)
9531 return;
9532
Bill Wendling44426052012-12-20 19:22:21 +00009533 unsigned Attributes = PD->getPropertyAttributes();
9534 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009535 // when 'assign' attribute was not explicitly specified
9536 // by user, ignore it and rely on property type itself
9537 // for lifetime info.
9538 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9539 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9540 LHSType->isObjCRetainableType())
9541 return;
9542
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009543 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009544 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009545 Diag(Loc, diag::warn_arc_retained_property_assign)
9546 << RHS->getSourceRange();
9547 return;
9548 }
9549 RHS = cast->getSubExpr();
9550 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009551 }
Bill Wendling44426052012-12-20 19:22:21 +00009552 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009553 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9554 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009555 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009556 }
9557}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009558
9559//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9560
9561namespace {
9562bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9563 SourceLocation StmtLoc,
9564 const NullStmt *Body) {
9565 // Do not warn if the body is a macro that expands to nothing, e.g:
9566 //
9567 // #define CALL(x)
9568 // if (condition)
9569 // CALL(0);
9570 //
9571 if (Body->hasLeadingEmptyMacro())
9572 return false;
9573
9574 // Get line numbers of statement and body.
9575 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009576 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009577 &StmtLineInvalid);
9578 if (StmtLineInvalid)
9579 return false;
9580
9581 bool BodyLineInvalid;
9582 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9583 &BodyLineInvalid);
9584 if (BodyLineInvalid)
9585 return false;
9586
9587 // Warn if null statement and body are on the same line.
9588 if (StmtLine != BodyLine)
9589 return false;
9590
9591 return true;
9592}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009593} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009594
9595void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9596 const Stmt *Body,
9597 unsigned DiagID) {
9598 // Since this is a syntactic check, don't emit diagnostic for template
9599 // instantiations, this just adds noise.
9600 if (CurrentInstantiationScope)
9601 return;
9602
9603 // The body should be a null statement.
9604 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9605 if (!NBody)
9606 return;
9607
9608 // Do the usual checks.
9609 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9610 return;
9611
9612 Diag(NBody->getSemiLoc(), DiagID);
9613 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9614}
9615
9616void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9617 const Stmt *PossibleBody) {
9618 assert(!CurrentInstantiationScope); // Ensured by caller
9619
9620 SourceLocation StmtLoc;
9621 const Stmt *Body;
9622 unsigned DiagID;
9623 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9624 StmtLoc = FS->getRParenLoc();
9625 Body = FS->getBody();
9626 DiagID = diag::warn_empty_for_body;
9627 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9628 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9629 Body = WS->getBody();
9630 DiagID = diag::warn_empty_while_body;
9631 } else
9632 return; // Neither `for' nor `while'.
9633
9634 // The body should be a null statement.
9635 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9636 if (!NBody)
9637 return;
9638
9639 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009640 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009641 return;
9642
9643 // Do the usual checks.
9644 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9645 return;
9646
9647 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9648 // noise level low, emit diagnostics only if for/while is followed by a
9649 // CompoundStmt, e.g.:
9650 // for (int i = 0; i < n; i++);
9651 // {
9652 // a(i);
9653 // }
9654 // or if for/while is followed by a statement with more indentation
9655 // than for/while itself:
9656 // for (int i = 0; i < n; i++);
9657 // a(i);
9658 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9659 if (!ProbableTypo) {
9660 bool BodyColInvalid;
9661 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9662 PossibleBody->getLocStart(),
9663 &BodyColInvalid);
9664 if (BodyColInvalid)
9665 return;
9666
9667 bool StmtColInvalid;
9668 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9669 S->getLocStart(),
9670 &StmtColInvalid);
9671 if (StmtColInvalid)
9672 return;
9673
9674 if (BodyCol > StmtCol)
9675 ProbableTypo = true;
9676 }
9677
9678 if (ProbableTypo) {
9679 Diag(NBody->getSemiLoc(), DiagID);
9680 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9681 }
9682}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009683
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009684//===--- CHECK: Warn on self move with std::move. -------------------------===//
9685
9686/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9687void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9688 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009689 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9690 return;
9691
9692 if (!ActiveTemplateInstantiations.empty())
9693 return;
9694
9695 // Strip parens and casts away.
9696 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9697 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9698
9699 // Check for a call expression
9700 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9701 if (!CE || CE->getNumArgs() != 1)
9702 return;
9703
9704 // Check for a call to std::move
9705 const FunctionDecl *FD = CE->getDirectCallee();
9706 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9707 !FD->getIdentifier()->isStr("move"))
9708 return;
9709
9710 // Get argument from std::move
9711 RHSExpr = CE->getArg(0);
9712
9713 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9714 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9715
9716 // Two DeclRefExpr's, check that the decls are the same.
9717 if (LHSDeclRef && RHSDeclRef) {
9718 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9719 return;
9720 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9721 RHSDeclRef->getDecl()->getCanonicalDecl())
9722 return;
9723
9724 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9725 << LHSExpr->getSourceRange()
9726 << RHSExpr->getSourceRange();
9727 return;
9728 }
9729
9730 // Member variables require a different approach to check for self moves.
9731 // MemberExpr's are the same if every nested MemberExpr refers to the same
9732 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9733 // the base Expr's are CXXThisExpr's.
9734 const Expr *LHSBase = LHSExpr;
9735 const Expr *RHSBase = RHSExpr;
9736 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9737 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9738 if (!LHSME || !RHSME)
9739 return;
9740
9741 while (LHSME && RHSME) {
9742 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9743 RHSME->getMemberDecl()->getCanonicalDecl())
9744 return;
9745
9746 LHSBase = LHSME->getBase();
9747 RHSBase = RHSME->getBase();
9748 LHSME = dyn_cast<MemberExpr>(LHSBase);
9749 RHSME = dyn_cast<MemberExpr>(RHSBase);
9750 }
9751
9752 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9753 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9754 if (LHSDeclRef && RHSDeclRef) {
9755 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9756 return;
9757 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9758 RHSDeclRef->getDecl()->getCanonicalDecl())
9759 return;
9760
9761 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9762 << LHSExpr->getSourceRange()
9763 << RHSExpr->getSourceRange();
9764 return;
9765 }
9766
9767 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9768 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9769 << LHSExpr->getSourceRange()
9770 << RHSExpr->getSourceRange();
9771}
9772
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009773//===--- Layout compatibility ----------------------------------------------//
9774
9775namespace {
9776
9777bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9778
9779/// \brief Check if two enumeration types are layout-compatible.
9780bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9781 // C++11 [dcl.enum] p8:
9782 // Two enumeration types are layout-compatible if they have the same
9783 // underlying type.
9784 return ED1->isComplete() && ED2->isComplete() &&
9785 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9786}
9787
9788/// \brief Check if two fields are layout-compatible.
9789bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9790 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9791 return false;
9792
9793 if (Field1->isBitField() != Field2->isBitField())
9794 return false;
9795
9796 if (Field1->isBitField()) {
9797 // Make sure that the bit-fields are the same length.
9798 unsigned Bits1 = Field1->getBitWidthValue(C);
9799 unsigned Bits2 = Field2->getBitWidthValue(C);
9800
9801 if (Bits1 != Bits2)
9802 return false;
9803 }
9804
9805 return true;
9806}
9807
9808/// \brief Check if two standard-layout structs are layout-compatible.
9809/// (C++11 [class.mem] p17)
9810bool isLayoutCompatibleStruct(ASTContext &C,
9811 RecordDecl *RD1,
9812 RecordDecl *RD2) {
9813 // If both records are C++ classes, check that base classes match.
9814 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9815 // If one of records is a CXXRecordDecl we are in C++ mode,
9816 // thus the other one is a CXXRecordDecl, too.
9817 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9818 // Check number of base classes.
9819 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9820 return false;
9821
9822 // Check the base classes.
9823 for (CXXRecordDecl::base_class_const_iterator
9824 Base1 = D1CXX->bases_begin(),
9825 BaseEnd1 = D1CXX->bases_end(),
9826 Base2 = D2CXX->bases_begin();
9827 Base1 != BaseEnd1;
9828 ++Base1, ++Base2) {
9829 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9830 return false;
9831 }
9832 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9833 // If only RD2 is a C++ class, it should have zero base classes.
9834 if (D2CXX->getNumBases() > 0)
9835 return false;
9836 }
9837
9838 // Check the fields.
9839 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9840 Field2End = RD2->field_end(),
9841 Field1 = RD1->field_begin(),
9842 Field1End = RD1->field_end();
9843 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9844 if (!isLayoutCompatible(C, *Field1, *Field2))
9845 return false;
9846 }
9847 if (Field1 != Field1End || Field2 != Field2End)
9848 return false;
9849
9850 return true;
9851}
9852
9853/// \brief Check if two standard-layout unions are layout-compatible.
9854/// (C++11 [class.mem] p18)
9855bool isLayoutCompatibleUnion(ASTContext &C,
9856 RecordDecl *RD1,
9857 RecordDecl *RD2) {
9858 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009859 for (auto *Field2 : RD2->fields())
9860 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009861
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009862 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009863 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9864 I = UnmatchedFields.begin(),
9865 E = UnmatchedFields.end();
9866
9867 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009868 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009869 bool Result = UnmatchedFields.erase(*I);
9870 (void) Result;
9871 assert(Result);
9872 break;
9873 }
9874 }
9875 if (I == E)
9876 return false;
9877 }
9878
9879 return UnmatchedFields.empty();
9880}
9881
9882bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9883 if (RD1->isUnion() != RD2->isUnion())
9884 return false;
9885
9886 if (RD1->isUnion())
9887 return isLayoutCompatibleUnion(C, RD1, RD2);
9888 else
9889 return isLayoutCompatibleStruct(C, RD1, RD2);
9890}
9891
9892/// \brief Check if two types are layout-compatible in C++11 sense.
9893bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9894 if (T1.isNull() || T2.isNull())
9895 return false;
9896
9897 // C++11 [basic.types] p11:
9898 // If two types T1 and T2 are the same type, then T1 and T2 are
9899 // layout-compatible types.
9900 if (C.hasSameType(T1, T2))
9901 return true;
9902
9903 T1 = T1.getCanonicalType().getUnqualifiedType();
9904 T2 = T2.getCanonicalType().getUnqualifiedType();
9905
9906 const Type::TypeClass TC1 = T1->getTypeClass();
9907 const Type::TypeClass TC2 = T2->getTypeClass();
9908
9909 if (TC1 != TC2)
9910 return false;
9911
9912 if (TC1 == Type::Enum) {
9913 return isLayoutCompatible(C,
9914 cast<EnumType>(T1)->getDecl(),
9915 cast<EnumType>(T2)->getDecl());
9916 } else if (TC1 == Type::Record) {
9917 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9918 return false;
9919
9920 return isLayoutCompatible(C,
9921 cast<RecordType>(T1)->getDecl(),
9922 cast<RecordType>(T2)->getDecl());
9923 }
9924
9925 return false;
9926}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009927} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009928
9929//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9930
9931namespace {
9932/// \brief Given a type tag expression find the type tag itself.
9933///
9934/// \param TypeExpr Type tag expression, as it appears in user's code.
9935///
9936/// \param VD Declaration of an identifier that appears in a type tag.
9937///
9938/// \param MagicValue Type tag magic value.
9939bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9940 const ValueDecl **VD, uint64_t *MagicValue) {
9941 while(true) {
9942 if (!TypeExpr)
9943 return false;
9944
9945 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9946
9947 switch (TypeExpr->getStmtClass()) {
9948 case Stmt::UnaryOperatorClass: {
9949 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9950 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9951 TypeExpr = UO->getSubExpr();
9952 continue;
9953 }
9954 return false;
9955 }
9956
9957 case Stmt::DeclRefExprClass: {
9958 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9959 *VD = DRE->getDecl();
9960 return true;
9961 }
9962
9963 case Stmt::IntegerLiteralClass: {
9964 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9965 llvm::APInt MagicValueAPInt = IL->getValue();
9966 if (MagicValueAPInt.getActiveBits() <= 64) {
9967 *MagicValue = MagicValueAPInt.getZExtValue();
9968 return true;
9969 } else
9970 return false;
9971 }
9972
9973 case Stmt::BinaryConditionalOperatorClass:
9974 case Stmt::ConditionalOperatorClass: {
9975 const AbstractConditionalOperator *ACO =
9976 cast<AbstractConditionalOperator>(TypeExpr);
9977 bool Result;
9978 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9979 if (Result)
9980 TypeExpr = ACO->getTrueExpr();
9981 else
9982 TypeExpr = ACO->getFalseExpr();
9983 continue;
9984 }
9985 return false;
9986 }
9987
9988 case Stmt::BinaryOperatorClass: {
9989 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9990 if (BO->getOpcode() == BO_Comma) {
9991 TypeExpr = BO->getRHS();
9992 continue;
9993 }
9994 return false;
9995 }
9996
9997 default:
9998 return false;
9999 }
10000 }
10001}
10002
10003/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10004///
10005/// \param TypeExpr Expression that specifies a type tag.
10006///
10007/// \param MagicValues Registered magic values.
10008///
10009/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10010/// kind.
10011///
10012/// \param TypeInfo Information about the corresponding C type.
10013///
10014/// \returns true if the corresponding C type was found.
10015bool GetMatchingCType(
10016 const IdentifierInfo *ArgumentKind,
10017 const Expr *TypeExpr, const ASTContext &Ctx,
10018 const llvm::DenseMap<Sema::TypeTagMagicValue,
10019 Sema::TypeTagData> *MagicValues,
10020 bool &FoundWrongKind,
10021 Sema::TypeTagData &TypeInfo) {
10022 FoundWrongKind = false;
10023
10024 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010025 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010026
10027 uint64_t MagicValue;
10028
10029 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10030 return false;
10031
10032 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010033 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010034 if (I->getArgumentKind() != ArgumentKind) {
10035 FoundWrongKind = true;
10036 return false;
10037 }
10038 TypeInfo.Type = I->getMatchingCType();
10039 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10040 TypeInfo.MustBeNull = I->getMustBeNull();
10041 return true;
10042 }
10043 return false;
10044 }
10045
10046 if (!MagicValues)
10047 return false;
10048
10049 llvm::DenseMap<Sema::TypeTagMagicValue,
10050 Sema::TypeTagData>::const_iterator I =
10051 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10052 if (I == MagicValues->end())
10053 return false;
10054
10055 TypeInfo = I->second;
10056 return true;
10057}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010058} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010059
10060void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10061 uint64_t MagicValue, QualType Type,
10062 bool LayoutCompatible,
10063 bool MustBeNull) {
10064 if (!TypeTagForDatatypeMagicValues)
10065 TypeTagForDatatypeMagicValues.reset(
10066 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10067
10068 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10069 (*TypeTagForDatatypeMagicValues)[Magic] =
10070 TypeTagData(Type, LayoutCompatible, MustBeNull);
10071}
10072
10073namespace {
10074bool IsSameCharType(QualType T1, QualType T2) {
10075 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10076 if (!BT1)
10077 return false;
10078
10079 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10080 if (!BT2)
10081 return false;
10082
10083 BuiltinType::Kind T1Kind = BT1->getKind();
10084 BuiltinType::Kind T2Kind = BT2->getKind();
10085
10086 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10087 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10088 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10089 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10090}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010091} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010092
10093void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10094 const Expr * const *ExprArgs) {
10095 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10096 bool IsPointerAttr = Attr->getIsPointer();
10097
10098 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10099 bool FoundWrongKind;
10100 TypeTagData TypeInfo;
10101 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10102 TypeTagForDatatypeMagicValues.get(),
10103 FoundWrongKind, TypeInfo)) {
10104 if (FoundWrongKind)
10105 Diag(TypeTagExpr->getExprLoc(),
10106 diag::warn_type_tag_for_datatype_wrong_kind)
10107 << TypeTagExpr->getSourceRange();
10108 return;
10109 }
10110
10111 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10112 if (IsPointerAttr) {
10113 // Skip implicit cast of pointer to `void *' (as a function argument).
10114 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010115 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010116 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010117 ArgumentExpr = ICE->getSubExpr();
10118 }
10119 QualType ArgumentType = ArgumentExpr->getType();
10120
10121 // Passing a `void*' pointer shouldn't trigger a warning.
10122 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10123 return;
10124
10125 if (TypeInfo.MustBeNull) {
10126 // Type tag with matching void type requires a null pointer.
10127 if (!ArgumentExpr->isNullPointerConstant(Context,
10128 Expr::NPC_ValueDependentIsNotNull)) {
10129 Diag(ArgumentExpr->getExprLoc(),
10130 diag::warn_type_safety_null_pointer_required)
10131 << ArgumentKind->getName()
10132 << ArgumentExpr->getSourceRange()
10133 << TypeTagExpr->getSourceRange();
10134 }
10135 return;
10136 }
10137
10138 QualType RequiredType = TypeInfo.Type;
10139 if (IsPointerAttr)
10140 RequiredType = Context.getPointerType(RequiredType);
10141
10142 bool mismatch = false;
10143 if (!TypeInfo.LayoutCompatible) {
10144 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10145
10146 // C++11 [basic.fundamental] p1:
10147 // Plain char, signed char, and unsigned char are three distinct types.
10148 //
10149 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10150 // char' depending on the current char signedness mode.
10151 if (mismatch)
10152 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10153 RequiredType->getPointeeType())) ||
10154 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10155 mismatch = false;
10156 } else
10157 if (IsPointerAttr)
10158 mismatch = !isLayoutCompatible(Context,
10159 ArgumentType->getPointeeType(),
10160 RequiredType->getPointeeType());
10161 else
10162 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10163
10164 if (mismatch)
10165 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010166 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010167 << TypeInfo.LayoutCompatible << RequiredType
10168 << ArgumentExpr->getSourceRange()
10169 << TypeTagExpr->getSourceRange();
10170}