blob: b51cf56f01ea4c24895abb7ef98a26927017ffe7 [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
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.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"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000318/// Diagnose integer type and any valid implicit convertion to it.
319static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
320 const QualType &IntType);
321
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000322static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000323 unsigned Start, unsigned End) {
324 bool IllegalParams = false;
325 for (unsigned I = Start; I <= End; ++I)
326 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
327 S.Context.getSizeType());
328 return IllegalParams;
329}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000330
331/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
332/// 'local void*' parameter of passed block.
333static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
334 Expr *BlockArg,
335 unsigned NumNonVarArgs) {
336 const BlockPointerType *BPT =
337 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
338 unsigned NumBlockParams =
339 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
340 unsigned TotalNumArgs = TheCall->getNumArgs();
341
342 // For each argument passed to the block, a corresponding uint needs to
343 // be passed to describe the size of the local memory.
344 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
345 S.Diag(TheCall->getLocStart(),
346 diag::err_opencl_enqueue_kernel_local_size_args);
347 return true;
348 }
349
350 // Check that the sizes of the local memory are specified by integers.
351 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
352 TotalNumArgs - 1);
353}
354
355/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
356/// overload formats specified in Table 6.13.17.1.
357/// int enqueue_kernel(queue_t queue,
358/// kernel_enqueue_flags_t flags,
359/// const ndrange_t ndrange,
360/// void (^block)(void))
361/// int enqueue_kernel(queue_t queue,
362/// kernel_enqueue_flags_t flags,
363/// const ndrange_t ndrange,
364/// uint num_events_in_wait_list,
365/// clk_event_t *event_wait_list,
366/// clk_event_t *event_ret,
367/// void (^block)(void))
368/// int enqueue_kernel(queue_t queue,
369/// kernel_enqueue_flags_t flags,
370/// const ndrange_t ndrange,
371/// void (^block)(local void*, ...),
372/// uint size0, ...)
373/// int enqueue_kernel(queue_t queue,
374/// kernel_enqueue_flags_t flags,
375/// const ndrange_t ndrange,
376/// uint num_events_in_wait_list,
377/// clk_event_t *event_wait_list,
378/// clk_event_t *event_ret,
379/// void (^block)(local void*, ...),
380/// uint size0, ...)
381static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
382 unsigned NumArgs = TheCall->getNumArgs();
383
384 if (NumArgs < 4) {
385 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
386 return true;
387 }
388
389 Expr *Arg0 = TheCall->getArg(0);
390 Expr *Arg1 = TheCall->getArg(1);
391 Expr *Arg2 = TheCall->getArg(2);
392 Expr *Arg3 = TheCall->getArg(3);
393
394 // First argument always needs to be a queue_t type.
395 if (!Arg0->getType()->isQueueT()) {
396 S.Diag(TheCall->getArg(0)->getLocStart(),
397 diag::err_opencl_enqueue_kernel_expected_type)
398 << S.Context.OCLQueueTy;
399 return true;
400 }
401
402 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
403 if (!Arg1->getType()->isIntegerType()) {
404 S.Diag(TheCall->getArg(1)->getLocStart(),
405 diag::err_opencl_enqueue_kernel_expected_type)
406 << "'kernel_enqueue_flags_t' (i.e. uint)";
407 return true;
408 }
409
410 // Third argument is always an ndrange_t type.
411 if (!Arg2->getType()->isNDRangeT()) {
412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
414 << S.Context.OCLNDRangeTy;
415 return true;
416 }
417
418 // With four arguments, there is only one form that the function could be
419 // called in: no events and no variable arguments.
420 if (NumArgs == 4) {
421 // check that the last argument is the right block type.
422 if (!isBlockPointer(Arg3)) {
423 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
424 << "block";
425 return true;
426 }
427 // we have a block type, check the prototype
428 const BlockPointerType *BPT =
429 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
430 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
431 S.Diag(Arg3->getLocStart(),
432 diag::err_opencl_enqueue_kernel_blocks_no_args);
433 return true;
434 }
435 return false;
436 }
437 // we can have block + varargs.
438 if (isBlockPointer(Arg3))
439 return (checkOpenCLBlockArgs(S, Arg3) ||
440 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
441 // last two cases with either exactly 7 args or 7 args and varargs.
442 if (NumArgs >= 7) {
443 // check common block argument.
444 Expr *Arg6 = TheCall->getArg(6);
445 if (!isBlockPointer(Arg6)) {
446 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
447 << "block";
448 return true;
449 }
450 if (checkOpenCLBlockArgs(S, Arg6))
451 return true;
452
453 // Forth argument has to be any integer type.
454 if (!Arg3->getType()->isIntegerType()) {
455 S.Diag(TheCall->getArg(3)->getLocStart(),
456 diag::err_opencl_enqueue_kernel_expected_type)
457 << "integer";
458 return true;
459 }
460 // check remaining common arguments.
461 Expr *Arg4 = TheCall->getArg(4);
462 Expr *Arg5 = TheCall->getArg(5);
463
Anastasia Stulova2b461202016-11-14 15:34:01 +0000464 // Fifth argument is always passed as a pointer to clk_event_t.
465 if (!Arg4->isNullPointerConstant(S.Context,
466 Expr::NPC_ValueDependentIsNotNull) &&
467 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000468 S.Diag(TheCall->getArg(4)->getLocStart(),
469 diag::err_opencl_enqueue_kernel_expected_type)
470 << S.Context.getPointerType(S.Context.OCLClkEventTy);
471 return true;
472 }
473
Anastasia Stulova2b461202016-11-14 15:34:01 +0000474 // Sixth argument is always passed as a pointer to clk_event_t.
475 if (!Arg5->isNullPointerConstant(S.Context,
476 Expr::NPC_ValueDependentIsNotNull) &&
477 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000478 Arg5->getType()->getPointeeType()->isClkEventT())) {
479 S.Diag(TheCall->getArg(5)->getLocStart(),
480 diag::err_opencl_enqueue_kernel_expected_type)
481 << S.Context.getPointerType(S.Context.OCLClkEventTy);
482 return true;
483 }
484
485 if (NumArgs == 7)
486 return false;
487
488 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
489 }
490
491 // None of the specific case has been detected, give generic error
492 S.Diag(TheCall->getLocStart(),
493 diag::err_opencl_enqueue_kernel_incorrect_args);
494 return true;
495}
496
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000497/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000498static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000499 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000500}
501
502/// Returns true if pipe element type is different from the pointer.
503static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
504 const Expr *Arg0 = Call->getArg(0);
505 // First argument type should always be pipe.
506 if (!Arg0->getType()->isPipeType()) {
507 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000508 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000509 return true;
510 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000511 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000512 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
513 // Validates the access qualifier is compatible with the call.
514 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
515 // read_only and write_only, and assumed to be read_only if no qualifier is
516 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000517 switch (Call->getDirectCallee()->getBuiltinID()) {
518 case Builtin::BIread_pipe:
519 case Builtin::BIreserve_read_pipe:
520 case Builtin::BIcommit_read_pipe:
521 case Builtin::BIwork_group_reserve_read_pipe:
522 case Builtin::BIsub_group_reserve_read_pipe:
523 case Builtin::BIwork_group_commit_read_pipe:
524 case Builtin::BIsub_group_commit_read_pipe:
525 if (!(!AccessQual || AccessQual->isReadOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "read_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 case Builtin::BIwrite_pipe:
533 case Builtin::BIreserve_write_pipe:
534 case Builtin::BIcommit_write_pipe:
535 case Builtin::BIwork_group_reserve_write_pipe:
536 case Builtin::BIsub_group_reserve_write_pipe:
537 case Builtin::BIwork_group_commit_write_pipe:
538 case Builtin::BIsub_group_commit_write_pipe:
539 if (!(AccessQual && AccessQual->isWriteOnly())) {
540 S.Diag(Arg0->getLocStart(),
541 diag::err_opencl_builtin_pipe_invalid_access_modifier)
542 << "write_only" << Arg0->getSourceRange();
543 return true;
544 }
545 break;
546 default:
547 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000548 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000549 return false;
550}
551
552/// Returns true if pipe element type is different from the pointer.
553static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
554 const Expr *Arg0 = Call->getArg(0);
555 const Expr *ArgIdx = Call->getArg(Idx);
556 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000557 const QualType EltTy = PipeTy->getElementType();
558 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000559 // The Idx argument should be a pointer and the type of the pointer and
560 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000561 if (!ArgTy ||
562 !S.Context.hasSameType(
563 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000564 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000565 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000566 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000567 return true;
568 }
569 return false;
570}
571
572// \brief Performs semantic analysis for the read/write_pipe call.
573// \param S Reference to the semantic analyzer.
574// \param Call A pointer to the builtin call.
575// \return True if a semantic error has been found, false otherwise.
576static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000577 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
578 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000579 switch (Call->getNumArgs()) {
580 case 2: {
581 if (checkOpenCLPipeArg(S, Call))
582 return true;
583 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 // read/write_pipe(pipe T, T*).
585 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 if (checkOpenCLPipePacketType(S, Call, 1))
587 return true;
588 } break;
589
590 case 4: {
591 if (checkOpenCLPipeArg(S, Call))
592 return true;
593 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
595 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 if (!Call->getArg(1)->getType()->isReserveIDT()) {
597 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000598 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000599 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 return true;
601 }
602
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000603 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000604 const Expr *Arg2 = Call->getArg(2);
605 if (!Arg2->getType()->isIntegerType() &&
606 !Arg2->getType()->isUnsignedIntegerType()) {
607 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000608 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000609 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return true;
611 }
612
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000613 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614 if (checkOpenCLPipePacketType(S, Call, 3))
615 return true;
616 } break;
617 default:
618 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000619 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 return true;
621 }
622
623 return false;
624}
625
626// \brief Performs a semantic analysis on the {work_group_/sub_group_
627// /_}reserve_{read/write}_pipe
628// \param S Reference to the semantic analyzer.
629// \param Call The call to the builtin function to be analyzed.
630// \return True if a semantic error was found, false otherwise.
631static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
632 if (checkArgCount(S, Call, 2))
633 return true;
634
635 if (checkOpenCLPipeArg(S, Call))
636 return true;
637
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 if (!Call->getArg(1)->getType()->isIntegerType() &&
640 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
641 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000642 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000643 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000644 return true;
645 }
646
647 return false;
648}
649
650// \brief Performs a semantic analysis on {work_group_/sub_group_
651// /_}commit_{read/write}_pipe
652// \param S Reference to the semantic analyzer.
653// \param Call The call to the builtin function to be analyzed.
654// \return True if a semantic error was found, false otherwise.
655static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
656 if (checkArgCount(S, Call, 2))
657 return true;
658
659 if (checkOpenCLPipeArg(S, Call))
660 return true;
661
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000662 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 if (!Call->getArg(1)->getType()->isReserveIDT()) {
664 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000665 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000666 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000667 return true;
668 }
669
670 return false;
671}
672
673// \brief Performs a semantic analysis on the call to built-in Pipe
674// Query Functions.
675// \param S Reference to the semantic analyzer.
676// \param Call The call to the builtin function to be analyzed.
677// \return True if a semantic error was found, false otherwise.
678static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
679 if (checkArgCount(S, Call, 1))
680 return true;
681
682 if (!Call->getArg(0)->getType()->isPipeType()) {
683 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000685 return true;
686 }
687
688 return false;
689}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000690// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000691// \brief Performs semantic analysis for the to_global/local/private call.
692// \param S Reference to the semantic analyzer.
693// \param BuiltinID ID of the builtin function.
694// \param Call A pointer to the builtin call.
695// \return True if a semantic error has been found, false otherwise.
696static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
697 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000698 if (Call->getNumArgs() != 1) {
699 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
700 << Call->getDirectCallee() << Call->getSourceRange();
701 return true;
702 }
703
704 auto RT = Call->getArg(0)->getType();
705 if (!RT->isPointerType() || RT->getPointeeType()
706 .getAddressSpace() == LangAS::opencl_constant) {
707 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
708 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
709 return true;
710 }
711
712 RT = RT->getPointeeType();
713 auto Qual = RT.getQualifiers();
714 switch (BuiltinID) {
715 case Builtin::BIto_global:
716 Qual.setAddressSpace(LangAS::opencl_global);
717 break;
718 case Builtin::BIto_local:
719 Qual.setAddressSpace(LangAS::opencl_local);
720 break;
721 default:
722 Qual.removeAddressSpace();
723 }
724 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
725 RT.getUnqualifiedType(), Qual)));
726
727 return false;
728}
729
John McCalldadc5752010-08-24 06:29:42 +0000730ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000731Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
732 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000733 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000734
Chris Lattner3be167f2010-10-01 23:23:24 +0000735 // Find out if any arguments are required to be integer constant expressions.
736 unsigned ICEArguments = 0;
737 ASTContext::GetBuiltinTypeError Error;
738 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
739 if (Error != ASTContext::GE_None)
740 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
741
742 // If any arguments are required to be ICE's, check and diagnose.
743 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
744 // Skip arguments not required to be ICE's.
745 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
746
747 llvm::APSInt Result;
748 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
749 return true;
750 ICEArguments &= ~(1 << ArgNo);
751 }
752
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000753 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000754 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000755 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000756 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000757 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000758 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000759 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000760 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000761 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000762 if (SemaBuiltinVAStart(TheCall))
763 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000764 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000765 case Builtin::BI__va_start: {
766 switch (Context.getTargetInfo().getTriple().getArch()) {
767 case llvm::Triple::arm:
768 case llvm::Triple::thumb:
769 if (SemaBuiltinVAStartARM(TheCall))
770 return ExprError();
771 break;
772 default:
773 if (SemaBuiltinVAStart(TheCall))
774 return ExprError();
775 break;
776 }
777 break;
778 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000779 case Builtin::BI__builtin_isgreater:
780 case Builtin::BI__builtin_isgreaterequal:
781 case Builtin::BI__builtin_isless:
782 case Builtin::BI__builtin_islessequal:
783 case Builtin::BI__builtin_islessgreater:
784 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000785 if (SemaBuiltinUnorderedCompare(TheCall))
786 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000787 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000788 case Builtin::BI__builtin_fpclassify:
789 if (SemaBuiltinFPClassification(TheCall, 6))
790 return ExprError();
791 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000792 case Builtin::BI__builtin_isfinite:
793 case Builtin::BI__builtin_isinf:
794 case Builtin::BI__builtin_isinf_sign:
795 case Builtin::BI__builtin_isnan:
796 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000797 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000798 return ExprError();
799 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000800 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000801 return SemaBuiltinShuffleVector(TheCall);
802 // TheCall will be freed by the smart pointer here, but that's fine, since
803 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 if (SemaBuiltinPrefetch(TheCall))
806 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000807 break;
David Majnemer51169932016-10-31 05:37:48 +0000808 case Builtin::BI__builtin_alloca_with_align:
809 if (SemaBuiltinAllocaWithAlign(TheCall))
810 return ExprError();
811 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000812 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000813 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000814 if (SemaBuiltinAssume(TheCall))
815 return ExprError();
816 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000817 case Builtin::BI__builtin_assume_aligned:
818 if (SemaBuiltinAssumeAligned(TheCall))
819 return ExprError();
820 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000821 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000822 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000823 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000824 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000825 case Builtin::BI__builtin_longjmp:
826 if (SemaBuiltinLongjmp(TheCall))
827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000829 case Builtin::BI__builtin_setjmp:
830 if (SemaBuiltinSetjmp(TheCall))
831 return ExprError();
832 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000833 case Builtin::BI_setjmp:
834 case Builtin::BI_setjmpex:
835 if (checkArgCount(*this, TheCall, 1))
836 return true;
837 break;
John McCallbebede42011-02-26 05:39:39 +0000838
839 case Builtin::BI__builtin_classify_type:
840 if (checkArgCount(*this, TheCall, 1)) return true;
841 TheCall->setType(Context.IntTy);
842 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000843 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000847 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000848 case Builtin::BI__sync_fetch_and_add_1:
849 case Builtin::BI__sync_fetch_and_add_2:
850 case Builtin::BI__sync_fetch_and_add_4:
851 case Builtin::BI__sync_fetch_and_add_8:
852 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000853 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000854 case Builtin::BI__sync_fetch_and_sub_1:
855 case Builtin::BI__sync_fetch_and_sub_2:
856 case Builtin::BI__sync_fetch_and_sub_4:
857 case Builtin::BI__sync_fetch_and_sub_8:
858 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000859 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000860 case Builtin::BI__sync_fetch_and_or_1:
861 case Builtin::BI__sync_fetch_and_or_2:
862 case Builtin::BI__sync_fetch_and_or_4:
863 case Builtin::BI__sync_fetch_and_or_8:
864 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000865 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000866 case Builtin::BI__sync_fetch_and_and_1:
867 case Builtin::BI__sync_fetch_and_and_2:
868 case Builtin::BI__sync_fetch_and_and_4:
869 case Builtin::BI__sync_fetch_and_and_8:
870 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000871 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000872 case Builtin::BI__sync_fetch_and_xor_1:
873 case Builtin::BI__sync_fetch_and_xor_2:
874 case Builtin::BI__sync_fetch_and_xor_4:
875 case Builtin::BI__sync_fetch_and_xor_8:
876 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000877 case Builtin::BI__sync_fetch_and_nand:
878 case Builtin::BI__sync_fetch_and_nand_1:
879 case Builtin::BI__sync_fetch_and_nand_2:
880 case Builtin::BI__sync_fetch_and_nand_4:
881 case Builtin::BI__sync_fetch_and_nand_8:
882 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000883 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000884 case Builtin::BI__sync_add_and_fetch_1:
885 case Builtin::BI__sync_add_and_fetch_2:
886 case Builtin::BI__sync_add_and_fetch_4:
887 case Builtin::BI__sync_add_and_fetch_8:
888 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000889 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000890 case Builtin::BI__sync_sub_and_fetch_1:
891 case Builtin::BI__sync_sub_and_fetch_2:
892 case Builtin::BI__sync_sub_and_fetch_4:
893 case Builtin::BI__sync_sub_and_fetch_8:
894 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000895 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000896 case Builtin::BI__sync_and_and_fetch_1:
897 case Builtin::BI__sync_and_and_fetch_2:
898 case Builtin::BI__sync_and_and_fetch_4:
899 case Builtin::BI__sync_and_and_fetch_8:
900 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000901 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000902 case Builtin::BI__sync_or_and_fetch_1:
903 case Builtin::BI__sync_or_and_fetch_2:
904 case Builtin::BI__sync_or_and_fetch_4:
905 case Builtin::BI__sync_or_and_fetch_8:
906 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000907 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000908 case Builtin::BI__sync_xor_and_fetch_1:
909 case Builtin::BI__sync_xor_and_fetch_2:
910 case Builtin::BI__sync_xor_and_fetch_4:
911 case Builtin::BI__sync_xor_and_fetch_8:
912 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000913 case Builtin::BI__sync_nand_and_fetch:
914 case Builtin::BI__sync_nand_and_fetch_1:
915 case Builtin::BI__sync_nand_and_fetch_2:
916 case Builtin::BI__sync_nand_and_fetch_4:
917 case Builtin::BI__sync_nand_and_fetch_8:
918 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000919 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000920 case Builtin::BI__sync_val_compare_and_swap_1:
921 case Builtin::BI__sync_val_compare_and_swap_2:
922 case Builtin::BI__sync_val_compare_and_swap_4:
923 case Builtin::BI__sync_val_compare_and_swap_8:
924 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000925 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000926 case Builtin::BI__sync_bool_compare_and_swap_1:
927 case Builtin::BI__sync_bool_compare_and_swap_2:
928 case Builtin::BI__sync_bool_compare_and_swap_4:
929 case Builtin::BI__sync_bool_compare_and_swap_8:
930 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000931 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000932 case Builtin::BI__sync_lock_test_and_set_1:
933 case Builtin::BI__sync_lock_test_and_set_2:
934 case Builtin::BI__sync_lock_test_and_set_4:
935 case Builtin::BI__sync_lock_test_and_set_8:
936 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000937 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000938 case Builtin::BI__sync_lock_release_1:
939 case Builtin::BI__sync_lock_release_2:
940 case Builtin::BI__sync_lock_release_4:
941 case Builtin::BI__sync_lock_release_8:
942 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000943 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000944 case Builtin::BI__sync_swap_1:
945 case Builtin::BI__sync_swap_2:
946 case Builtin::BI__sync_swap_4:
947 case Builtin::BI__sync_swap_8:
948 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000949 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000950 case Builtin::BI__builtin_nontemporal_load:
951 case Builtin::BI__builtin_nontemporal_store:
952 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000953#define BUILTIN(ID, TYPE, ATTRS)
954#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
955 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000956 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000957#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000958 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000959 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000960 return ExprError();
961 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000962 case Builtin::BI__builtin_addressof:
963 if (SemaBuiltinAddressof(*this, TheCall))
964 return ExprError();
965 break;
John McCall03107a42015-10-29 20:48:01 +0000966 case Builtin::BI__builtin_add_overflow:
967 case Builtin::BI__builtin_sub_overflow:
968 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000969 if (SemaBuiltinOverflow(*this, TheCall))
970 return ExprError();
971 break;
Richard Smith760520b2014-06-03 23:27:44 +0000972 case Builtin::BI__builtin_operator_new:
973 case Builtin::BI__builtin_operator_delete:
974 if (!getLangOpts().CPlusPlus) {
975 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
976 << (BuiltinID == Builtin::BI__builtin_operator_new
977 ? "__builtin_operator_new"
978 : "__builtin_operator_delete")
979 << "C++";
980 return ExprError();
981 }
982 // CodeGen assumes it can find the global new and delete to call,
983 // so ensure that they are declared.
984 DeclareGlobalNewDelete();
985 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000986
987 // check secure string manipulation functions where overflows
988 // are detectable at compile time
989 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000990 case Builtin::BI__builtin___memmove_chk:
991 case Builtin::BI__builtin___memset_chk:
992 case Builtin::BI__builtin___strlcat_chk:
993 case Builtin::BI__builtin___strlcpy_chk:
994 case Builtin::BI__builtin___strncat_chk:
995 case Builtin::BI__builtin___strncpy_chk:
996 case Builtin::BI__builtin___stpncpy_chk:
997 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
998 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000999 case Builtin::BI__builtin___memccpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1001 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001002 case Builtin::BI__builtin___snprintf_chk:
1003 case Builtin::BI__builtin___vsnprintf_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1005 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001006 case Builtin::BI__builtin_call_with_static_chain:
1007 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1008 return ExprError();
1009 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001010 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001011 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001012 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1013 diag::err_seh___except_block))
1014 return ExprError();
1015 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001016 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001017 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001018 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1019 diag::err_seh___except_filter))
1020 return ExprError();
1021 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001022 case Builtin::BI__GetExceptionInfo:
1023 if (checkArgCount(*this, TheCall, 1))
1024 return ExprError();
1025
1026 if (CheckCXXThrowOperand(
1027 TheCall->getLocStart(),
1028 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1029 TheCall))
1030 return ExprError();
1031
1032 TheCall->setType(Context.VoidPtrTy);
1033 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001034 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001035 case Builtin::BIread_pipe:
1036 case Builtin::BIwrite_pipe:
1037 // Since those two functions are declared with var args, we need a semantic
1038 // check for the argument.
1039 if (SemaBuiltinRWPipe(*this, TheCall))
1040 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001041 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001042 break;
1043 case Builtin::BIreserve_read_pipe:
1044 case Builtin::BIreserve_write_pipe:
1045 case Builtin::BIwork_group_reserve_read_pipe:
1046 case Builtin::BIwork_group_reserve_write_pipe:
1047 case Builtin::BIsub_group_reserve_read_pipe:
1048 case Builtin::BIsub_group_reserve_write_pipe:
1049 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1050 return ExprError();
1051 // Since return type of reserve_read/write_pipe built-in function is
1052 // reserve_id_t, which is not defined in the builtin def file , we used int
1053 // as return type and need to override the return type of these functions.
1054 TheCall->setType(Context.OCLReserveIDTy);
1055 break;
1056 case Builtin::BIcommit_read_pipe:
1057 case Builtin::BIcommit_write_pipe:
1058 case Builtin::BIwork_group_commit_read_pipe:
1059 case Builtin::BIwork_group_commit_write_pipe:
1060 case Builtin::BIsub_group_commit_read_pipe:
1061 case Builtin::BIsub_group_commit_write_pipe:
1062 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1063 return ExprError();
1064 break;
1065 case Builtin::BIget_pipe_num_packets:
1066 case Builtin::BIget_pipe_max_packets:
1067 if (SemaBuiltinPipePackets(*this, TheCall))
1068 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001069 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001070 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001071 case Builtin::BIto_global:
1072 case Builtin::BIto_local:
1073 case Builtin::BIto_private:
1074 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1075 return ExprError();
1076 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001077 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1078 case Builtin::BIenqueue_kernel:
1079 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1080 return ExprError();
1081 break;
1082 case Builtin::BIget_kernel_work_group_size:
1083 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1084 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1085 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001086 break;
1087 case Builtin::BI__builtin_os_log_format:
1088 case Builtin::BI__builtin_os_log_format_buffer_size:
1089 if (SemaBuiltinOSLogFormat(TheCall)) {
1090 return ExprError();
1091 }
1092 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001093 }
Richard Smith760520b2014-06-03 23:27:44 +00001094
Nate Begeman4904e322010-06-08 02:47:44 +00001095 // Since the target specific builtins for each arch overlap, only check those
1096 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001097 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001099 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001100 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001101 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001102 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001103 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1104 return ExprError();
1105 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001106 case llvm::Triple::aarch64:
1107 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001108 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001109 return ExprError();
1110 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001111 case llvm::Triple::mips:
1112 case llvm::Triple::mipsel:
1113 case llvm::Triple::mips64:
1114 case llvm::Triple::mips64el:
1115 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1116 return ExprError();
1117 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001118 case llvm::Triple::systemz:
1119 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1120 return ExprError();
1121 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001122 case llvm::Triple::x86:
1123 case llvm::Triple::x86_64:
1124 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1125 return ExprError();
1126 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001127 case llvm::Triple::ppc:
1128 case llvm::Triple::ppc64:
1129 case llvm::Triple::ppc64le:
1130 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1131 return ExprError();
1132 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001133 default:
1134 break;
1135 }
1136 }
1137
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001138 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001139}
1140
Nate Begeman91e1fea2010-06-14 05:21:25 +00001141// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001142static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001143 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001144 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001145 switch (Type.getEltType()) {
1146 case NeonTypeFlags::Int8:
1147 case NeonTypeFlags::Poly8:
1148 return shift ? 7 : (8 << IsQuad) - 1;
1149 case NeonTypeFlags::Int16:
1150 case NeonTypeFlags::Poly16:
1151 return shift ? 15 : (4 << IsQuad) - 1;
1152 case NeonTypeFlags::Int32:
1153 return shift ? 31 : (2 << IsQuad) - 1;
1154 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001155 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001156 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001157 case NeonTypeFlags::Poly128:
1158 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 case NeonTypeFlags::Float16:
1160 assert(!shift && "cannot shift float types!");
1161 return (4 << IsQuad) - 1;
1162 case NeonTypeFlags::Float32:
1163 assert(!shift && "cannot shift float types!");
1164 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001165 case NeonTypeFlags::Float64:
1166 assert(!shift && "cannot shift float types!");
1167 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001168 }
David Blaikie8a40f702012-01-17 06:56:22 +00001169 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001170}
1171
Bob Wilsone4d77232011-11-08 05:04:11 +00001172/// getNeonEltType - Return the QualType corresponding to the elements of
1173/// the vector type specified by the NeonTypeFlags. This is used to check
1174/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001175static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001176 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001177 switch (Flags.getEltType()) {
1178 case NeonTypeFlags::Int8:
1179 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1180 case NeonTypeFlags::Int16:
1181 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1182 case NeonTypeFlags::Int32:
1183 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1184 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001185 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001186 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1187 else
1188 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1189 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001190 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001191 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001192 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001193 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001194 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001195 if (IsInt64Long)
1196 return Context.UnsignedLongTy;
1197 else
1198 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001199 case NeonTypeFlags::Poly128:
1200 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001201 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001202 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001203 case NeonTypeFlags::Float32:
1204 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001205 case NeonTypeFlags::Float64:
1206 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001207 }
David Blaikie8a40f702012-01-17 06:56:22 +00001208 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001209}
1210
Tim Northover12670412014-02-19 10:37:05 +00001211bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001212 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001213 uint64_t mask = 0;
1214 unsigned TV = 0;
1215 int PtrArgNum = -1;
1216 bool HasConstPtr = false;
1217 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001218#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001219#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001220#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001221 }
1222
1223 // For NEON intrinsics which are overloaded on vector element type, validate
1224 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001225 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001226 if (mask) {
1227 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1228 return true;
1229
1230 TV = Result.getLimitedValue(64);
1231 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1232 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001233 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001234 }
1235
1236 if (PtrArgNum >= 0) {
1237 // Check that pointer arguments have the specified type.
1238 Expr *Arg = TheCall->getArg(PtrArgNum);
1239 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1240 Arg = ICE->getSubExpr();
1241 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1242 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001243
Tim Northovera2ee4332014-03-29 15:09:45 +00001244 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001246 bool IsInt64Long =
1247 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1248 QualType EltTy =
1249 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001250 if (HasConstPtr)
1251 EltTy = EltTy.withConst();
1252 QualType LHSTy = Context.getPointerType(EltTy);
1253 AssignConvertType ConvTy;
1254 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1255 if (RHS.isInvalid())
1256 return true;
1257 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1258 RHS.get(), AA_Assigning))
1259 return true;
1260 }
1261
1262 // For NEON intrinsics which take an immediate value as part of the
1263 // instruction, range check them here.
1264 unsigned i = 0, l = 0, u = 0;
1265 switch (BuiltinID) {
1266 default:
1267 return false;
Tim Northover12670412014-02-19 10:37:05 +00001268#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001269#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001270#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001271 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001272
Richard Sandiford28940af2014-04-16 08:47:51 +00001273 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001274}
1275
Tim Northovera2ee4332014-03-29 15:09:45 +00001276bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1277 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001278 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001279 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001280 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001281 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001282 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001283 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1284 BuiltinID == AArch64::BI__builtin_arm_strex ||
1285 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001286 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001287 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001288 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001291
1292 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1293
1294 // Ensure that we have the proper number of arguments.
1295 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1296 return true;
1297
1298 // Inspect the pointer argument of the atomic builtin. This should always be
1299 // a pointer type, whose element is an integral scalar or pointer type.
1300 // Because it is a pointer type, we don't have to worry about any implicit
1301 // casts here.
1302 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1303 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1304 if (PointerArgRes.isInvalid())
1305 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001306 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001307
1308 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1309 if (!pointerType) {
1310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1311 << PointerArg->getType() << PointerArg->getSourceRange();
1312 return true;
1313 }
1314
1315 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1316 // task is to insert the appropriate casts into the AST. First work out just
1317 // what the appropriate type is.
1318 QualType ValType = pointerType->getPointeeType();
1319 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1320 if (IsLdrex)
1321 AddrType.addConst();
1322
1323 // Issue a warning if the cast is dodgy.
1324 CastKind CastNeeded = CK_NoOp;
1325 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1326 CastNeeded = CK_BitCast;
1327 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1328 << PointerArg->getType()
1329 << Context.getPointerType(AddrType)
1330 << AA_Passing << PointerArg->getSourceRange();
1331 }
1332
1333 // Finally, do the cast and replace the argument with the corrected version.
1334 AddrType = Context.getPointerType(AddrType);
1335 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1336 if (PointerArgRes.isInvalid())
1337 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001338 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001339
1340 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1341
1342 // In general, we allow ints, floats and pointers to be loaded and stored.
1343 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1344 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1345 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1346 << PointerArg->getType() << PointerArg->getSourceRange();
1347 return true;
1348 }
1349
1350 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001351 if (Context.getTypeSize(ValType) > MaxWidth) {
1352 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001353 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1354 << PointerArg->getType() << PointerArg->getSourceRange();
1355 return true;
1356 }
1357
1358 switch (ValType.getObjCLifetime()) {
1359 case Qualifiers::OCL_None:
1360 case Qualifiers::OCL_ExplicitNone:
1361 // okay
1362 break;
1363
1364 case Qualifiers::OCL_Weak:
1365 case Qualifiers::OCL_Strong:
1366 case Qualifiers::OCL_Autoreleasing:
1367 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1368 << ValType << PointerArg->getSourceRange();
1369 return true;
1370 }
1371
Tim Northover6aacd492013-07-16 09:47:53 +00001372 if (IsLdrex) {
1373 TheCall->setType(ValType);
1374 return false;
1375 }
1376
1377 // Initialize the argument to be stored.
1378 ExprResult ValArg = TheCall->getArg(0);
1379 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1380 Context, ValType, /*consume*/ false);
1381 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1382 if (ValArg.isInvalid())
1383 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001384 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001385
1386 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1387 // but the custom checker bypasses all default analysis.
1388 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001389 return false;
1390}
1391
Nate Begeman4904e322010-06-08 02:47:44 +00001392bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001393 llvm::APSInt Result;
1394
Tim Northover6aacd492013-07-16 09:47:53 +00001395 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001396 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1397 BuiltinID == ARM::BI__builtin_arm_strex ||
1398 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001399 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001400 }
1401
Yi Kong26d104a2014-08-13 19:18:14 +00001402 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1403 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1404 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1405 }
1406
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001407 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1408 BuiltinID == ARM::BI__builtin_arm_wsr64)
1409 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1410
1411 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1412 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1413 BuiltinID == ARM::BI__builtin_arm_wsr ||
1414 BuiltinID == ARM::BI__builtin_arm_wsrp)
1415 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1416
Tim Northover12670412014-02-19 10:37:05 +00001417 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1418 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001419
Yi Kong4efadfb2014-07-03 16:01:25 +00001420 // For intrinsics which take an immediate value as part of the instruction,
1421 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001422 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001423 switch (BuiltinID) {
1424 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001427 case ARM::BI__builtin_arm_vcvtr_f:
1428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001429 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001430 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001431 case ARM::BI__builtin_arm_isb:
1432 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001433 }
Nate Begemand773fe62010-06-13 04:47:52 +00001434
Nate Begemanf568b072010-08-03 21:32:34 +00001435 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001436 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001437}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001438
Tim Northover573cbee2014-05-24 12:52:07 +00001439bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001440 CallExpr *TheCall) {
1441 llvm::APSInt Result;
1442
Tim Northover573cbee2014-05-24 12:52:07 +00001443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001444 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445 BuiltinID == AArch64::BI__builtin_arm_strex ||
1446 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448 }
1449
Yi Konga5548432014-08-13 19:18:20 +00001450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455 }
1456
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001460
1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466
Tim Northovera2ee4332014-03-29 15:09:45 +00001467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468 return true;
1469
Yi Kong19a29ac2014-07-17 10:52:06 +00001470 // For intrinsics which take an immediate value as part of the instruction,
1471 // range check them here.
1472 unsigned i = 0, l = 0, u = 0;
1473 switch (BuiltinID) {
1474 default: return false;
1475 case AArch64::BI__builtin_arm_dmb:
1476 case AArch64::BI__builtin_arm_dsb:
1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478 }
1479
Yi Kong19a29ac2014-07-17 10:52:06 +00001480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001481}
1482
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001483// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485// ordering for DSP is unspecified. MSA is ordered by the data format used
1486// by the underlying instruction i.e., df/m, df/n and then by size.
1487//
1488// FIXME: The size tests here should instead be tablegen'd along with the
1489// definitions from include/clang/Basic/BuiltinsMips.def.
1490// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001492bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001493 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001494 switch (BuiltinID) {
1495 default: return false;
1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504 // df/m field.
1505 // These intrinsics take an unsigned 3 bit immediate.
1506 case Mips::BI__builtin_msa_bclri_b:
1507 case Mips::BI__builtin_msa_bnegi_b:
1508 case Mips::BI__builtin_msa_bseti_b:
1509 case Mips::BI__builtin_msa_sat_s_b:
1510 case Mips::BI__builtin_msa_sat_u_b:
1511 case Mips::BI__builtin_msa_slli_b:
1512 case Mips::BI__builtin_msa_srai_b:
1513 case Mips::BI__builtin_msa_srari_b:
1514 case Mips::BI__builtin_msa_srli_b:
1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516 case Mips::BI__builtin_msa_binsli_b:
1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518 // These intrinsics take an unsigned 4 bit immediate.
1519 case Mips::BI__builtin_msa_bclri_h:
1520 case Mips::BI__builtin_msa_bnegi_h:
1521 case Mips::BI__builtin_msa_bseti_h:
1522 case Mips::BI__builtin_msa_sat_s_h:
1523 case Mips::BI__builtin_msa_sat_u_h:
1524 case Mips::BI__builtin_msa_slli_h:
1525 case Mips::BI__builtin_msa_srai_h:
1526 case Mips::BI__builtin_msa_srari_h:
1527 case Mips::BI__builtin_msa_srli_h:
1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529 case Mips::BI__builtin_msa_binsli_h:
1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531 // These intrinsics take an unsigned 5 bit immedate.
1532 // The first block of intrinsics actually have an unsigned 5 bit field,
1533 // not a df/n field.
1534 case Mips::BI__builtin_msa_clei_u_b:
1535 case Mips::BI__builtin_msa_clei_u_h:
1536 case Mips::BI__builtin_msa_clei_u_w:
1537 case Mips::BI__builtin_msa_clei_u_d:
1538 case Mips::BI__builtin_msa_clti_u_b:
1539 case Mips::BI__builtin_msa_clti_u_h:
1540 case Mips::BI__builtin_msa_clti_u_w:
1541 case Mips::BI__builtin_msa_clti_u_d:
1542 case Mips::BI__builtin_msa_maxi_u_b:
1543 case Mips::BI__builtin_msa_maxi_u_h:
1544 case Mips::BI__builtin_msa_maxi_u_w:
1545 case Mips::BI__builtin_msa_maxi_u_d:
1546 case Mips::BI__builtin_msa_mini_u_b:
1547 case Mips::BI__builtin_msa_mini_u_h:
1548 case Mips::BI__builtin_msa_mini_u_w:
1549 case Mips::BI__builtin_msa_mini_u_d:
1550 case Mips::BI__builtin_msa_addvi_b:
1551 case Mips::BI__builtin_msa_addvi_h:
1552 case Mips::BI__builtin_msa_addvi_w:
1553 case Mips::BI__builtin_msa_addvi_d:
1554 case Mips::BI__builtin_msa_bclri_w:
1555 case Mips::BI__builtin_msa_bnegi_w:
1556 case Mips::BI__builtin_msa_bseti_w:
1557 case Mips::BI__builtin_msa_sat_s_w:
1558 case Mips::BI__builtin_msa_sat_u_w:
1559 case Mips::BI__builtin_msa_slli_w:
1560 case Mips::BI__builtin_msa_srai_w:
1561 case Mips::BI__builtin_msa_srari_w:
1562 case Mips::BI__builtin_msa_srli_w:
1563 case Mips::BI__builtin_msa_srlri_w:
1564 case Mips::BI__builtin_msa_subvi_b:
1565 case Mips::BI__builtin_msa_subvi_h:
1566 case Mips::BI__builtin_msa_subvi_w:
1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568 case Mips::BI__builtin_msa_binsli_w:
1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570 // These intrinsics take an unsigned 6 bit immediate.
1571 case Mips::BI__builtin_msa_bclri_d:
1572 case Mips::BI__builtin_msa_bnegi_d:
1573 case Mips::BI__builtin_msa_bseti_d:
1574 case Mips::BI__builtin_msa_sat_s_d:
1575 case Mips::BI__builtin_msa_sat_u_d:
1576 case Mips::BI__builtin_msa_slli_d:
1577 case Mips::BI__builtin_msa_srai_d:
1578 case Mips::BI__builtin_msa_srari_d:
1579 case Mips::BI__builtin_msa_srli_d:
1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581 case Mips::BI__builtin_msa_binsli_d:
1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583 // These intrinsics take a signed 5 bit immediate.
1584 case Mips::BI__builtin_msa_ceqi_b:
1585 case Mips::BI__builtin_msa_ceqi_h:
1586 case Mips::BI__builtin_msa_ceqi_w:
1587 case Mips::BI__builtin_msa_ceqi_d:
1588 case Mips::BI__builtin_msa_clti_s_b:
1589 case Mips::BI__builtin_msa_clti_s_h:
1590 case Mips::BI__builtin_msa_clti_s_w:
1591 case Mips::BI__builtin_msa_clti_s_d:
1592 case Mips::BI__builtin_msa_clei_s_b:
1593 case Mips::BI__builtin_msa_clei_s_h:
1594 case Mips::BI__builtin_msa_clei_s_w:
1595 case Mips::BI__builtin_msa_clei_s_d:
1596 case Mips::BI__builtin_msa_maxi_s_b:
1597 case Mips::BI__builtin_msa_maxi_s_h:
1598 case Mips::BI__builtin_msa_maxi_s_w:
1599 case Mips::BI__builtin_msa_maxi_s_d:
1600 case Mips::BI__builtin_msa_mini_s_b:
1601 case Mips::BI__builtin_msa_mini_s_h:
1602 case Mips::BI__builtin_msa_mini_s_w:
1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604 // These intrinsics take an unsigned 8 bit immediate.
1605 case Mips::BI__builtin_msa_andi_b:
1606 case Mips::BI__builtin_msa_nori_b:
1607 case Mips::BI__builtin_msa_ori_b:
1608 case Mips::BI__builtin_msa_shf_b:
1609 case Mips::BI__builtin_msa_shf_h:
1610 case Mips::BI__builtin_msa_shf_w:
1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612 case Mips::BI__builtin_msa_bseli_b:
1613 case Mips::BI__builtin_msa_bmnzi_b:
1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615 // df/n format
1616 // These intrinsics take an unsigned 4 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_b:
1618 case Mips::BI__builtin_msa_copy_u_b:
1619 case Mips::BI__builtin_msa_insve_b:
1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1621 case Mips::BI__builtin_msa_sld_b:
1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1628 case Mips::BI__builtin_msa_sld_h:
1629 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1630 // These intrinsics take an unsigned 2 bit immediate.
1631 case Mips::BI__builtin_msa_copy_s_w:
1632 case Mips::BI__builtin_msa_copy_u_w:
1633 case Mips::BI__builtin_msa_insve_w:
1634 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1635 case Mips::BI__builtin_msa_sld_w:
1636 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1637 // These intrinsics take an unsigned 1 bit immediate.
1638 case Mips::BI__builtin_msa_copy_s_d:
1639 case Mips::BI__builtin_msa_copy_u_d:
1640 case Mips::BI__builtin_msa_insve_d:
1641 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1642 case Mips::BI__builtin_msa_sld_d:
1643 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1644 // Memory offsets and immediate loads.
1645 // These intrinsics take a signed 10 bit immediate.
1646 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1647 case Mips::BI__builtin_msa_ldi_h:
1648 case Mips::BI__builtin_msa_ldi_w:
1649 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1650 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1651 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1654 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1655 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1656 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1657 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001658 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001659
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001660 if (!m)
1661 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1662
1663 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1664 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001665}
1666
Kit Bartone50adcb2015-03-30 19:40:59 +00001667bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1668 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001669 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1670 BuiltinID == PPC::BI__builtin_divdeu ||
1671 BuiltinID == PPC::BI__builtin_bpermd;
1672 bool IsTarget64Bit = Context.getTargetInfo()
1673 .getTypeWidth(Context
1674 .getTargetInfo()
1675 .getIntPtrType()) == 64;
1676 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1677 BuiltinID == PPC::BI__builtin_divweu ||
1678 BuiltinID == PPC::BI__builtin_divde ||
1679 BuiltinID == PPC::BI__builtin_divdeu;
1680
1681 if (Is64BitBltin && !IsTarget64Bit)
1682 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683 << TheCall->getSourceRange();
1684
1685 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1686 (BuiltinID == PPC::BI__builtin_bpermd &&
1687 !Context.getTargetInfo().hasFeature("bpermd")))
1688 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1689 << TheCall->getSourceRange();
1690
Kit Bartone50adcb2015-03-30 19:40:59 +00001691 switch (BuiltinID) {
1692 default: return false;
1693 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1694 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1696 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1697 case PPC::BI__builtin_tbegin:
1698 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1699 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1700 case PPC::BI__builtin_tabortwc:
1701 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1702 case PPC::BI__builtin_tabortwci:
1703 case PPC::BI__builtin_tabortdci:
1704 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1705 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1706 }
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708}
1709
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001710bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711 CallExpr *TheCall) {
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713 Expr *Arg = TheCall->getArg(0);
1714 llvm::APSInt AbortCode(32);
1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718 << Arg->getSourceRange();
1719 }
1720
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1743 case SystemZ::BI__builtin_s390_vfidb:
1744 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1745 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1746 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1747 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1748 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vstrcb:
1751 case SystemZ::BI__builtin_s390_vstrch:
1752 case SystemZ::BI__builtin_s390_vstrcf:
1753 case SystemZ::BI__builtin_s390_vstrczb:
1754 case SystemZ::BI__builtin_s390_vstrczh:
1755 case SystemZ::BI__builtin_s390_vstrczf:
1756 case SystemZ::BI__builtin_s390_vstrcbs:
1757 case SystemZ::BI__builtin_s390_vstrchs:
1758 case SystemZ::BI__builtin_s390_vstrcfs:
1759 case SystemZ::BI__builtin_s390_vstrczbs:
1760 case SystemZ::BI__builtin_s390_vstrczhs:
1761 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1762 }
1763 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001764}
1765
Craig Topper5ba2c502015-11-07 08:08:31 +00001766/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1767/// This checks that the target supports __builtin_cpu_supports and
1768/// that the string argument is constant and valid.
1769static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1770 Expr *Arg = TheCall->getArg(0);
1771
1772 // Check if the argument is a string literal.
1773 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1774 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1775 << Arg->getSourceRange();
1776
1777 // Check the contents of the string.
1778 StringRef Feature =
1779 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1780 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1781 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1782 << Arg->getSourceRange();
1783 return false;
1784}
1785
Craig Toppera7e253e2016-09-23 04:48:31 +00001786// Check if the rounding mode is legal.
1787bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1788 // Indicates if this instruction has rounding control or just SAE.
1789 bool HasRC = false;
1790
1791 unsigned ArgNum = 0;
1792 switch (BuiltinID) {
1793 default:
1794 return false;
1795 case X86::BI__builtin_ia32_vcvttsd2si32:
1796 case X86::BI__builtin_ia32_vcvttsd2si64:
1797 case X86::BI__builtin_ia32_vcvttsd2usi32:
1798 case X86::BI__builtin_ia32_vcvttsd2usi64:
1799 case X86::BI__builtin_ia32_vcvttss2si32:
1800 case X86::BI__builtin_ia32_vcvttss2si64:
1801 case X86::BI__builtin_ia32_vcvttss2usi32:
1802 case X86::BI__builtin_ia32_vcvttss2usi64:
1803 ArgNum = 1;
1804 break;
1805 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1814 case X86::BI__builtin_ia32_exp2pd_mask:
1815 case X86::BI__builtin_ia32_exp2ps_mask:
1816 case X86::BI__builtin_ia32_getexppd512_mask:
1817 case X86::BI__builtin_ia32_getexpps512_mask:
1818 case X86::BI__builtin_ia32_rcp28pd_mask:
1819 case X86::BI__builtin_ia32_rcp28ps_mask:
1820 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1821 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1822 case X86::BI__builtin_ia32_vcomisd:
1823 case X86::BI__builtin_ia32_vcomiss:
1824 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1825 ArgNum = 3;
1826 break;
1827 case X86::BI__builtin_ia32_cmppd512_mask:
1828 case X86::BI__builtin_ia32_cmpps512_mask:
1829 case X86::BI__builtin_ia32_cmpsd_mask:
1830 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001831 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001832 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1833 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001834 case X86::BI__builtin_ia32_maxpd512_mask:
1835 case X86::BI__builtin_ia32_maxps512_mask:
1836 case X86::BI__builtin_ia32_maxsd_round_mask:
1837 case X86::BI__builtin_ia32_maxss_round_mask:
1838 case X86::BI__builtin_ia32_minpd512_mask:
1839 case X86::BI__builtin_ia32_minps512_mask:
1840 case X86::BI__builtin_ia32_minsd_round_mask:
1841 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001842 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1843 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1844 case X86::BI__builtin_ia32_reducepd512_mask:
1845 case X86::BI__builtin_ia32_reduceps512_mask:
1846 case X86::BI__builtin_ia32_rndscalepd_mask:
1847 case X86::BI__builtin_ia32_rndscaleps_mask:
1848 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1849 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1850 ArgNum = 4;
1851 break;
1852 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001853 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001854 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001855 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001856 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001857 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001858 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001859 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001860 case X86::BI__builtin_ia32_rangepd512_mask:
1861 case X86::BI__builtin_ia32_rangeps512_mask:
1862 case X86::BI__builtin_ia32_rangesd128_round_mask:
1863 case X86::BI__builtin_ia32_rangess128_round_mask:
1864 case X86::BI__builtin_ia32_reducesd_mask:
1865 case X86::BI__builtin_ia32_reducess_mask:
1866 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1867 case X86::BI__builtin_ia32_rndscaless_round_mask:
1868 ArgNum = 5;
1869 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001870 case X86::BI__builtin_ia32_vcvtsd2si64:
1871 case X86::BI__builtin_ia32_vcvtsd2si32:
1872 case X86::BI__builtin_ia32_vcvtsd2usi32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi64:
1874 case X86::BI__builtin_ia32_vcvtss2si32:
1875 case X86::BI__builtin_ia32_vcvtss2si64:
1876 case X86::BI__builtin_ia32_vcvtss2usi32:
1877 case X86::BI__builtin_ia32_vcvtss2usi64:
1878 ArgNum = 1;
1879 HasRC = true;
1880 break;
Craig Topper8e066312016-11-07 07:01:09 +00001881 case X86::BI__builtin_ia32_cvtsi2sd64:
1882 case X86::BI__builtin_ia32_cvtsi2ss32:
1883 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001884 case X86::BI__builtin_ia32_cvtusi2sd64:
1885 case X86::BI__builtin_ia32_cvtusi2ss32:
1886 case X86::BI__builtin_ia32_cvtusi2ss64:
1887 ArgNum = 2;
1888 HasRC = true;
1889 break;
1890 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1891 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1895 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1897 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001901 case X86::BI__builtin_ia32_sqrtpd512_mask:
1902 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001903 ArgNum = 3;
1904 HasRC = true;
1905 break;
1906 case X86::BI__builtin_ia32_addpd512_mask:
1907 case X86::BI__builtin_ia32_addps512_mask:
1908 case X86::BI__builtin_ia32_divpd512_mask:
1909 case X86::BI__builtin_ia32_divps512_mask:
1910 case X86::BI__builtin_ia32_mulpd512_mask:
1911 case X86::BI__builtin_ia32_mulps512_mask:
1912 case X86::BI__builtin_ia32_subpd512_mask:
1913 case X86::BI__builtin_ia32_subps512_mask:
1914 case X86::BI__builtin_ia32_addss_round_mask:
1915 case X86::BI__builtin_ia32_addsd_round_mask:
1916 case X86::BI__builtin_ia32_divss_round_mask:
1917 case X86::BI__builtin_ia32_divsd_round_mask:
1918 case X86::BI__builtin_ia32_mulss_round_mask:
1919 case X86::BI__builtin_ia32_mulsd_round_mask:
1920 case X86::BI__builtin_ia32_subss_round_mask:
1921 case X86::BI__builtin_ia32_subsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefpd512_mask:
1923 case X86::BI__builtin_ia32_scalefps512_mask:
1924 case X86::BI__builtin_ia32_scalefsd_round_mask:
1925 case X86::BI__builtin_ia32_scalefss_round_mask:
1926 case X86::BI__builtin_ia32_getmantpd512_mask:
1927 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001928 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1929 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1930 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001931 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1932 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddps512_mask:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1943 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1944 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1947 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1948 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1953 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1954 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1956 case X86::BI__builtin_ia32_vfmaddss3_mask:
1957 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1958 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1959 ArgNum = 4;
1960 HasRC = true;
1961 break;
1962 case X86::BI__builtin_ia32_getmantsd_round_mask:
1963 case X86::BI__builtin_ia32_getmantss_round_mask:
1964 ArgNum = 5;
1965 HasRC = true;
1966 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001967 }
1968
1969 llvm::APSInt Result;
1970
1971 // We can't check the value of a dependent argument.
1972 Expr *Arg = TheCall->getArg(ArgNum);
1973 if (Arg->isTypeDependent() || Arg->isValueDependent())
1974 return false;
1975
1976 // Check constant-ness first.
1977 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1978 return true;
1979
1980 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1981 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1982 // combined with ROUND_NO_EXC.
1983 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1984 Result == 8/*ROUND_NO_EXC*/ ||
1985 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1986 return false;
1987
1988 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1989 << Arg->getSourceRange();
1990}
1991
Craig Topperf0ddc892016-09-23 04:48:27 +00001992bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1993 if (BuiltinID == X86::BI__builtin_cpu_supports)
1994 return SemaBuiltinCpuSupports(*this, TheCall);
1995
1996 if (BuiltinID == X86::BI__builtin_ms_va_start)
1997 return SemaBuiltinMSVAStart(TheCall);
1998
Craig Toppera7e253e2016-09-23 04:48:31 +00001999 // If the intrinsic has rounding or SAE make sure its valid.
2000 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2001 return true;
2002
Craig Topperf0ddc892016-09-23 04:48:27 +00002003 // For intrinsics which take an immediate value as part of the instruction,
2004 // range check them here.
2005 int i = 0, l = 0, u = 0;
2006 switch (BuiltinID) {
2007 default:
2008 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002009 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002010 i = 1; l = 0; u = 3;
2011 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002012 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002013 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2014 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2015 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002017 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002018 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002019 case X86::BI__builtin_ia32_vpermil2pd:
2020 case X86::BI__builtin_ia32_vpermil2pd256:
2021 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002022 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002023 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002024 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002025 case X86::BI__builtin_ia32_cmpb128_mask:
2026 case X86::BI__builtin_ia32_cmpw128_mask:
2027 case X86::BI__builtin_ia32_cmpd128_mask:
2028 case X86::BI__builtin_ia32_cmpq128_mask:
2029 case X86::BI__builtin_ia32_cmpb256_mask:
2030 case X86::BI__builtin_ia32_cmpw256_mask:
2031 case X86::BI__builtin_ia32_cmpd256_mask:
2032 case X86::BI__builtin_ia32_cmpq256_mask:
2033 case X86::BI__builtin_ia32_cmpb512_mask:
2034 case X86::BI__builtin_ia32_cmpw512_mask:
2035 case X86::BI__builtin_ia32_cmpd512_mask:
2036 case X86::BI__builtin_ia32_cmpq512_mask:
2037 case X86::BI__builtin_ia32_ucmpb128_mask:
2038 case X86::BI__builtin_ia32_ucmpw128_mask:
2039 case X86::BI__builtin_ia32_ucmpd128_mask:
2040 case X86::BI__builtin_ia32_ucmpq128_mask:
2041 case X86::BI__builtin_ia32_ucmpb256_mask:
2042 case X86::BI__builtin_ia32_ucmpw256_mask:
2043 case X86::BI__builtin_ia32_ucmpd256_mask:
2044 case X86::BI__builtin_ia32_ucmpq256_mask:
2045 case X86::BI__builtin_ia32_ucmpb512_mask:
2046 case X86::BI__builtin_ia32_ucmpw512_mask:
2047 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002048 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002049 case X86::BI__builtin_ia32_vpcomub:
2050 case X86::BI__builtin_ia32_vpcomuw:
2051 case X86::BI__builtin_ia32_vpcomud:
2052 case X86::BI__builtin_ia32_vpcomuq:
2053 case X86::BI__builtin_ia32_vpcomb:
2054 case X86::BI__builtin_ia32_vpcomw:
2055 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002056 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002057 i = 2; l = 0; u = 7;
2058 break;
2059 case X86::BI__builtin_ia32_roundps:
2060 case X86::BI__builtin_ia32_roundpd:
2061 case X86::BI__builtin_ia32_roundps256:
2062 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002063 i = 1; l = 0; u = 15;
2064 break;
2065 case X86::BI__builtin_ia32_roundss:
2066 case X86::BI__builtin_ia32_roundsd:
2067 case X86::BI__builtin_ia32_rangepd128_mask:
2068 case X86::BI__builtin_ia32_rangepd256_mask:
2069 case X86::BI__builtin_ia32_rangepd512_mask:
2070 case X86::BI__builtin_ia32_rangeps128_mask:
2071 case X86::BI__builtin_ia32_rangeps256_mask:
2072 case X86::BI__builtin_ia32_rangeps512_mask:
2073 case X86::BI__builtin_ia32_getmantsd_round_mask:
2074 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002075 i = 2; l = 0; u = 15;
2076 break;
2077 case X86::BI__builtin_ia32_cmpps:
2078 case X86::BI__builtin_ia32_cmpss:
2079 case X86::BI__builtin_ia32_cmppd:
2080 case X86::BI__builtin_ia32_cmpsd:
2081 case X86::BI__builtin_ia32_cmpps256:
2082 case X86::BI__builtin_ia32_cmppd256:
2083 case X86::BI__builtin_ia32_cmpps128_mask:
2084 case X86::BI__builtin_ia32_cmppd128_mask:
2085 case X86::BI__builtin_ia32_cmpps256_mask:
2086 case X86::BI__builtin_ia32_cmppd256_mask:
2087 case X86::BI__builtin_ia32_cmpps512_mask:
2088 case X86::BI__builtin_ia32_cmppd512_mask:
2089 case X86::BI__builtin_ia32_cmpsd_mask:
2090 case X86::BI__builtin_ia32_cmpss_mask:
2091 i = 2; l = 0; u = 31;
2092 break;
2093 case X86::BI__builtin_ia32_xabort:
2094 i = 0; l = -128; u = 255;
2095 break;
2096 case X86::BI__builtin_ia32_pshufw:
2097 case X86::BI__builtin_ia32_aeskeygenassist128:
2098 i = 1; l = -128; u = 255;
2099 break;
2100 case X86::BI__builtin_ia32_vcvtps2ph:
2101 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002102 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2103 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2104 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2105 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2106 case X86::BI__builtin_ia32_rndscaleps_mask:
2107 case X86::BI__builtin_ia32_rndscalepd_mask:
2108 case X86::BI__builtin_ia32_reducepd128_mask:
2109 case X86::BI__builtin_ia32_reducepd256_mask:
2110 case X86::BI__builtin_ia32_reducepd512_mask:
2111 case X86::BI__builtin_ia32_reduceps128_mask:
2112 case X86::BI__builtin_ia32_reduceps256_mask:
2113 case X86::BI__builtin_ia32_reduceps512_mask:
2114 case X86::BI__builtin_ia32_prold512_mask:
2115 case X86::BI__builtin_ia32_prolq512_mask:
2116 case X86::BI__builtin_ia32_prold128_mask:
2117 case X86::BI__builtin_ia32_prold256_mask:
2118 case X86::BI__builtin_ia32_prolq128_mask:
2119 case X86::BI__builtin_ia32_prolq256_mask:
2120 case X86::BI__builtin_ia32_prord128_mask:
2121 case X86::BI__builtin_ia32_prord256_mask:
2122 case X86::BI__builtin_ia32_prorq128_mask:
2123 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002124 case X86::BI__builtin_ia32_fpclasspd128_mask:
2125 case X86::BI__builtin_ia32_fpclasspd256_mask:
2126 case X86::BI__builtin_ia32_fpclassps128_mask:
2127 case X86::BI__builtin_ia32_fpclassps256_mask:
2128 case X86::BI__builtin_ia32_fpclassps512_mask:
2129 case X86::BI__builtin_ia32_fpclasspd512_mask:
2130 case X86::BI__builtin_ia32_fpclasssd_mask:
2131 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002132 i = 1; l = 0; u = 255;
2133 break;
2134 case X86::BI__builtin_ia32_palignr:
2135 case X86::BI__builtin_ia32_insertps128:
2136 case X86::BI__builtin_ia32_dpps:
2137 case X86::BI__builtin_ia32_dppd:
2138 case X86::BI__builtin_ia32_dpps256:
2139 case X86::BI__builtin_ia32_mpsadbw128:
2140 case X86::BI__builtin_ia32_mpsadbw256:
2141 case X86::BI__builtin_ia32_pcmpistrm128:
2142 case X86::BI__builtin_ia32_pcmpistri128:
2143 case X86::BI__builtin_ia32_pcmpistria128:
2144 case X86::BI__builtin_ia32_pcmpistric128:
2145 case X86::BI__builtin_ia32_pcmpistrio128:
2146 case X86::BI__builtin_ia32_pcmpistris128:
2147 case X86::BI__builtin_ia32_pcmpistriz128:
2148 case X86::BI__builtin_ia32_pclmulqdq128:
2149 case X86::BI__builtin_ia32_vperm2f128_pd256:
2150 case X86::BI__builtin_ia32_vperm2f128_ps256:
2151 case X86::BI__builtin_ia32_vperm2f128_si256:
2152 case X86::BI__builtin_ia32_permti256:
2153 i = 2; l = -128; u = 255;
2154 break;
2155 case X86::BI__builtin_ia32_palignr128:
2156 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002157 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002158 case X86::BI__builtin_ia32_vcomisd:
2159 case X86::BI__builtin_ia32_vcomiss:
2160 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2161 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2162 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2163 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002164 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2165 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2167 i = 2; l = 0; u = 255;
2168 break;
2169 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2170 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2171 case X86::BI__builtin_ia32_fixupimmps512_mask:
2172 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2173 case X86::BI__builtin_ia32_fixupimmsd_mask:
2174 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2175 case X86::BI__builtin_ia32_fixupimmss_mask:
2176 case X86::BI__builtin_ia32_fixupimmss_maskz:
2177 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2178 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2179 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2180 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2181 case X86::BI__builtin_ia32_fixupimmps128_mask:
2182 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2183 case X86::BI__builtin_ia32_fixupimmps256_mask:
2184 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2185 case X86::BI__builtin_ia32_pternlogd512_mask:
2186 case X86::BI__builtin_ia32_pternlogd512_maskz:
2187 case X86::BI__builtin_ia32_pternlogq512_mask:
2188 case X86::BI__builtin_ia32_pternlogq512_maskz:
2189 case X86::BI__builtin_ia32_pternlogd128_mask:
2190 case X86::BI__builtin_ia32_pternlogd128_maskz:
2191 case X86::BI__builtin_ia32_pternlogd256_mask:
2192 case X86::BI__builtin_ia32_pternlogd256_maskz:
2193 case X86::BI__builtin_ia32_pternlogq128_mask:
2194 case X86::BI__builtin_ia32_pternlogq128_maskz:
2195 case X86::BI__builtin_ia32_pternlogq256_mask:
2196 case X86::BI__builtin_ia32_pternlogq256_maskz:
2197 i = 3; l = 0; u = 255;
2198 break;
2199 case X86::BI__builtin_ia32_pcmpestrm128:
2200 case X86::BI__builtin_ia32_pcmpestri128:
2201 case X86::BI__builtin_ia32_pcmpestria128:
2202 case X86::BI__builtin_ia32_pcmpestric128:
2203 case X86::BI__builtin_ia32_pcmpestrio128:
2204 case X86::BI__builtin_ia32_pcmpestris128:
2205 case X86::BI__builtin_ia32_pcmpestriz128:
2206 i = 4; l = -128; u = 255;
2207 break;
2208 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2209 case X86::BI__builtin_ia32_rndscaless_round_mask:
2210 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002211 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002212 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002213 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002214}
2215
Richard Smith55ce3522012-06-25 20:30:08 +00002216/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2217/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2218/// Returns true when the format fits the function and the FormatStringInfo has
2219/// been populated.
2220bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2221 FormatStringInfo *FSI) {
2222 FSI->HasVAListArg = Format->getFirstArg() == 0;
2223 FSI->FormatIdx = Format->getFormatIdx() - 1;
2224 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002225
Richard Smith55ce3522012-06-25 20:30:08 +00002226 // The way the format attribute works in GCC, the implicit this argument
2227 // of member functions is counted. However, it doesn't appear in our own
2228 // lists, so decrement format_idx in that case.
2229 if (IsCXXMember) {
2230 if(FSI->FormatIdx == 0)
2231 return false;
2232 --FSI->FormatIdx;
2233 if (FSI->FirstDataArg != 0)
2234 --FSI->FirstDataArg;
2235 }
2236 return true;
2237}
Mike Stump11289f42009-09-09 15:08:12 +00002238
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002239/// Checks if a the given expression evaluates to null.
2240///
2241/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002242static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002243 // If the expression has non-null type, it doesn't evaluate to null.
2244 if (auto nullability
2245 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2246 if (*nullability == NullabilityKind::NonNull)
2247 return false;
2248 }
2249
Ted Kremeneka146db32014-01-17 06:24:47 +00002250 // As a special case, transparent unions initialized with zero are
2251 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002252 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002253 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2254 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002255 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002256 if (const InitListExpr *ILE =
2257 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002258 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002259 }
2260
2261 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002262 return (!Expr->isValueDependent() &&
2263 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2264 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002265}
2266
2267static void CheckNonNullArgument(Sema &S,
2268 const Expr *ArgExpr,
2269 SourceLocation CallSiteLoc) {
2270 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002271 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2272 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002273}
2274
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002275bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2276 FormatStringInfo FSI;
2277 if ((GetFormatStringType(Format) == FST_NSString) &&
2278 getFormatStringInfo(Format, false, &FSI)) {
2279 Idx = FSI.FormatIdx;
2280 return true;
2281 }
2282 return false;
2283}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002284/// \brief Diagnose use of %s directive in an NSString which is being passed
2285/// as formatting string to formatting method.
2286static void
2287DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2288 const NamedDecl *FDecl,
2289 Expr **Args,
2290 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002291 unsigned Idx = 0;
2292 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002293 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2294 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002295 Idx = 2;
2296 Format = true;
2297 }
2298 else
2299 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2300 if (S.GetFormatNSStringIdx(I, Idx)) {
2301 Format = true;
2302 break;
2303 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002304 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002305 if (!Format || NumArgs <= Idx)
2306 return;
2307 const Expr *FormatExpr = Args[Idx];
2308 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2309 FormatExpr = CSCE->getSubExpr();
2310 const StringLiteral *FormatString;
2311 if (const ObjCStringLiteral *OSL =
2312 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2313 FormatString = OSL->getString();
2314 else
2315 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2316 if (!FormatString)
2317 return;
2318 if (S.FormatStringHasSArg(FormatString)) {
2319 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2320 << "%s" << 1 << 1;
2321 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2322 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002323 }
2324}
2325
Douglas Gregorb4866e82015-06-19 18:13:19 +00002326/// Determine whether the given type has a non-null nullability annotation.
2327static bool isNonNullType(ASTContext &ctx, QualType type) {
2328 if (auto nullability = type->getNullability(ctx))
2329 return *nullability == NullabilityKind::NonNull;
2330
2331 return false;
2332}
2333
Ted Kremenek2bc73332014-01-17 06:24:43 +00002334static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002335 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002336 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002337 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002338 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002339 assert((FDecl || Proto) && "Need a function declaration or prototype");
2340
Ted Kremenek9aedc152014-01-17 06:24:56 +00002341 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002342 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002343 if (FDecl) {
2344 // Handle the nonnull attribute on the function/method declaration itself.
2345 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2346 if (!NonNull->args_size()) {
2347 // Easy case: all pointer arguments are nonnull.
2348 for (const auto *Arg : Args)
2349 if (S.isValidPointerAttrType(Arg->getType()))
2350 CheckNonNullArgument(S, Arg, CallSiteLoc);
2351 return;
2352 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002353
Douglas Gregorb4866e82015-06-19 18:13:19 +00002354 for (unsigned Val : NonNull->args()) {
2355 if (Val >= Args.size())
2356 continue;
2357 if (NonNullArgs.empty())
2358 NonNullArgs.resize(Args.size());
2359 NonNullArgs.set(Val);
2360 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002361 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002362 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002363
Douglas Gregorb4866e82015-06-19 18:13:19 +00002364 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2365 // Handle the nonnull attribute on the parameters of the
2366 // function/method.
2367 ArrayRef<ParmVarDecl*> parms;
2368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2369 parms = FD->parameters();
2370 else
2371 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2372
2373 unsigned ParamIndex = 0;
2374 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2375 I != E; ++I, ++ParamIndex) {
2376 const ParmVarDecl *PVD = *I;
2377 if (PVD->hasAttr<NonNullAttr>() ||
2378 isNonNullType(S.Context, PVD->getType())) {
2379 if (NonNullArgs.empty())
2380 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002381
Douglas Gregorb4866e82015-06-19 18:13:19 +00002382 NonNullArgs.set(ParamIndex);
2383 }
2384 }
2385 } else {
2386 // If we have a non-function, non-method declaration but no
2387 // function prototype, try to dig out the function prototype.
2388 if (!Proto) {
2389 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2390 QualType type = VD->getType().getNonReferenceType();
2391 if (auto pointerType = type->getAs<PointerType>())
2392 type = pointerType->getPointeeType();
2393 else if (auto blockType = type->getAs<BlockPointerType>())
2394 type = blockType->getPointeeType();
2395 // FIXME: data member pointers?
2396
2397 // Dig out the function prototype, if there is one.
2398 Proto = type->getAs<FunctionProtoType>();
2399 }
2400 }
2401
2402 // Fill in non-null argument information from the nullability
2403 // information on the parameter types (if we have them).
2404 if (Proto) {
2405 unsigned Index = 0;
2406 for (auto paramType : Proto->getParamTypes()) {
2407 if (isNonNullType(S.Context, paramType)) {
2408 if (NonNullArgs.empty())
2409 NonNullArgs.resize(Args.size());
2410
2411 NonNullArgs.set(Index);
2412 }
2413
2414 ++Index;
2415 }
2416 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002417 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002418
Douglas Gregorb4866e82015-06-19 18:13:19 +00002419 // Check for non-null arguments.
2420 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2421 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002422 if (NonNullArgs[ArgIndex])
2423 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002424 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002425}
2426
Richard Smith55ce3522012-06-25 20:30:08 +00002427/// Handles the checks for format strings, non-POD arguments to vararg
2428/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002429void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2430 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002431 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002432 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002433 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002434 if (CurContext->isDependentContext())
2435 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002436
Ted Kremenekb8176da2010-09-09 04:33:05 +00002437 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002438 llvm::SmallBitVector CheckedVarArgs;
2439 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002440 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002441 // Only create vector if there are format attributes.
2442 CheckedVarArgs.resize(Args.size());
2443
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002444 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002445 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002446 }
Richard Smithd7293d72013-08-05 18:49:43 +00002447 }
Richard Smith55ce3522012-06-25 20:30:08 +00002448
2449 // Refuse POD arguments that weren't caught by the format string
2450 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002451 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002452 unsigned NumParams = Proto ? Proto->getNumParams()
2453 : FDecl && isa<FunctionDecl>(FDecl)
2454 ? cast<FunctionDecl>(FDecl)->getNumParams()
2455 : FDecl && isa<ObjCMethodDecl>(FDecl)
2456 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2457 : 0;
2458
Alp Toker9cacbab2014-01-20 20:26:09 +00002459 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002460 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002461 if (const Expr *Arg = Args[ArgIdx]) {
2462 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2463 checkVariadicArgument(Arg, CallType);
2464 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002465 }
Richard Smithd7293d72013-08-05 18:49:43 +00002466 }
Mike Stump11289f42009-09-09 15:08:12 +00002467
Douglas Gregorb4866e82015-06-19 18:13:19 +00002468 if (FDecl || Proto) {
2469 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002470
Richard Trieu41bc0992013-06-22 00:20:41 +00002471 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002472 if (FDecl) {
2473 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2474 CheckArgumentWithTypeTag(I, Args.data());
2475 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002476 }
Richard Smith55ce3522012-06-25 20:30:08 +00002477}
2478
2479/// CheckConstructorCall - Check a constructor call for correctness and safety
2480/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002481void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2482 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002483 const FunctionProtoType *Proto,
2484 SourceLocation Loc) {
2485 VariadicCallType CallType =
2486 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002487 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2488 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002489}
2490
2491/// CheckFunctionCall - Check a direct function call for various correctness
2492/// and safety properties not strictly enforced by the C type system.
2493bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2494 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002495 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2496 isa<CXXMethodDecl>(FDecl);
2497 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2498 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002499 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2500 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002501 Expr** Args = TheCall->getArgs();
2502 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002503 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002504 // If this is a call to a member operator, hide the first argument
2505 // from checkCall.
2506 // FIXME: Our choice of AST representation here is less than ideal.
2507 ++Args;
2508 --NumArgs;
2509 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002510 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002511 IsMemberFunction, TheCall->getRParenLoc(),
2512 TheCall->getCallee()->getSourceRange(), CallType);
2513
2514 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2515 // None of the checks below are needed for functions that don't have
2516 // simple names (e.g., C++ conversion functions).
2517 if (!FnInfo)
2518 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002519
Richard Trieua7f30b12016-12-06 01:42:28 +00002520 CheckAbsoluteValueFunction(TheCall, FDecl);
2521 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002522
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002523 if (getLangOpts().ObjC1)
2524 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002525
Anna Zaks22122702012-01-17 00:37:07 +00002526 unsigned CMId = FDecl->getMemoryFunctionKind();
2527 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002528 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002529
Anna Zaks201d4892012-01-13 21:52:01 +00002530 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002531 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002532 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002533 else if (CMId == Builtin::BIstrncat)
2534 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002535 else
Anna Zaks22122702012-01-17 00:37:07 +00002536 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002537
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002538 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002539}
2540
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002541bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002542 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002543 VariadicCallType CallType =
2544 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002545
Douglas Gregorb4866e82015-06-19 18:13:19 +00002546 checkCall(Method, nullptr, Args,
2547 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2548 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002549
2550 return false;
2551}
2552
Richard Trieu664c4c62013-06-20 21:03:13 +00002553bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2554 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002555 QualType Ty;
2556 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002557 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002558 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002559 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002560 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002561 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002562
Douglas Gregorb4866e82015-06-19 18:13:19 +00002563 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2564 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002565 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002566
Richard Trieu664c4c62013-06-20 21:03:13 +00002567 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002568 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002569 CallType = VariadicDoesNotApply;
2570 } else if (Ty->isBlockPointerType()) {
2571 CallType = VariadicBlock;
2572 } else { // Ty->isFunctionPointerType()
2573 CallType = VariadicFunction;
2574 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002575
Douglas Gregorb4866e82015-06-19 18:13:19 +00002576 checkCall(NDecl, Proto,
2577 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2578 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002579 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002580
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002581 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002582}
2583
Richard Trieu41bc0992013-06-22 00:20:41 +00002584/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2585/// such as function pointers returned from functions.
2586bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002587 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002588 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002589 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002590 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002591 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002592 TheCall->getCallee()->getSourceRange(), CallType);
2593
2594 return false;
2595}
2596
Tim Northovere94a34c2014-03-11 10:49:14 +00002597static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002598 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002599 return false;
2600
JF Bastiendda2cb12016-04-18 18:01:49 +00002601 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002602 switch (Op) {
2603 case AtomicExpr::AO__c11_atomic_init:
2604 llvm_unreachable("There is no ordering argument for an init");
2605
2606 case AtomicExpr::AO__c11_atomic_load:
2607 case AtomicExpr::AO__atomic_load_n:
2608 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002609 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2610 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002611
2612 case AtomicExpr::AO__c11_atomic_store:
2613 case AtomicExpr::AO__atomic_store:
2614 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002615 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2616 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2617 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002618
2619 default:
2620 return true;
2621 }
2622}
2623
Richard Smithfeea8832012-04-12 05:08:17 +00002624ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2625 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002626 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2627 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002628
Richard Smithfeea8832012-04-12 05:08:17 +00002629 // All these operations take one of the following forms:
2630 enum {
2631 // C __c11_atomic_init(A *, C)
2632 Init,
2633 // C __c11_atomic_load(A *, int)
2634 Load,
2635 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002636 LoadCopy,
2637 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002638 Copy,
2639 // C __c11_atomic_add(A *, M, int)
2640 Arithmetic,
2641 // C __atomic_exchange_n(A *, CP, int)
2642 Xchg,
2643 // void __atomic_exchange(A *, C *, CP, int)
2644 GNUXchg,
2645 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2646 C11CmpXchg,
2647 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2648 GNUCmpXchg
2649 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002650 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2651 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002652 // where:
2653 // C is an appropriate type,
2654 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2655 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2656 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2657 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002658
Gabor Horvath98bd0982015-03-16 09:59:54 +00002659 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2660 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2661 AtomicExpr::AO__atomic_load,
2662 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002663 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2664 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2665 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2666 Op == AtomicExpr::AO__atomic_store_n ||
2667 Op == AtomicExpr::AO__atomic_exchange_n ||
2668 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2669 bool IsAddSub = false;
2670
2671 switch (Op) {
2672 case AtomicExpr::AO__c11_atomic_init:
2673 Form = Init;
2674 break;
2675
2676 case AtomicExpr::AO__c11_atomic_load:
2677 case AtomicExpr::AO__atomic_load_n:
2678 Form = Load;
2679 break;
2680
Richard Smithfeea8832012-04-12 05:08:17 +00002681 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002682 Form = LoadCopy;
2683 break;
2684
2685 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002686 case AtomicExpr::AO__atomic_store:
2687 case AtomicExpr::AO__atomic_store_n:
2688 Form = Copy;
2689 break;
2690
2691 case AtomicExpr::AO__c11_atomic_fetch_add:
2692 case AtomicExpr::AO__c11_atomic_fetch_sub:
2693 case AtomicExpr::AO__atomic_fetch_add:
2694 case AtomicExpr::AO__atomic_fetch_sub:
2695 case AtomicExpr::AO__atomic_add_fetch:
2696 case AtomicExpr::AO__atomic_sub_fetch:
2697 IsAddSub = true;
2698 // Fall through.
2699 case AtomicExpr::AO__c11_atomic_fetch_and:
2700 case AtomicExpr::AO__c11_atomic_fetch_or:
2701 case AtomicExpr::AO__c11_atomic_fetch_xor:
2702 case AtomicExpr::AO__atomic_fetch_and:
2703 case AtomicExpr::AO__atomic_fetch_or:
2704 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002705 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002706 case AtomicExpr::AO__atomic_and_fetch:
2707 case AtomicExpr::AO__atomic_or_fetch:
2708 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002709 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002710 Form = Arithmetic;
2711 break;
2712
2713 case AtomicExpr::AO__c11_atomic_exchange:
2714 case AtomicExpr::AO__atomic_exchange_n:
2715 Form = Xchg;
2716 break;
2717
2718 case AtomicExpr::AO__atomic_exchange:
2719 Form = GNUXchg;
2720 break;
2721
2722 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2723 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2724 Form = C11CmpXchg;
2725 break;
2726
2727 case AtomicExpr::AO__atomic_compare_exchange:
2728 case AtomicExpr::AO__atomic_compare_exchange_n:
2729 Form = GNUCmpXchg;
2730 break;
2731 }
2732
2733 // Check we have the right number of arguments.
2734 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002735 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002736 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002737 << TheCall->getCallee()->getSourceRange();
2738 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002739 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2740 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002741 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002742 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002743 << TheCall->getCallee()->getSourceRange();
2744 return ExprError();
2745 }
2746
Richard Smithfeea8832012-04-12 05:08:17 +00002747 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002748 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002749 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2750 if (ConvertedPtr.isInvalid())
2751 return ExprError();
2752
2753 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002754 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2755 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002756 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002757 << Ptr->getType() << Ptr->getSourceRange();
2758 return ExprError();
2759 }
2760
Richard Smithfeea8832012-04-12 05:08:17 +00002761 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2762 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2763 QualType ValType = AtomTy; // 'C'
2764 if (IsC11) {
2765 if (!AtomTy->isAtomicType()) {
2766 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2767 << Ptr->getType() << Ptr->getSourceRange();
2768 return ExprError();
2769 }
Richard Smithe00921a2012-09-15 06:09:58 +00002770 if (AtomTy.isConstQualified()) {
2771 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2772 << Ptr->getType() << Ptr->getSourceRange();
2773 return ExprError();
2774 }
Richard Smithfeea8832012-04-12 05:08:17 +00002775 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002776 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002777 if (ValType.isConstQualified()) {
2778 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2779 << Ptr->getType() << Ptr->getSourceRange();
2780 return ExprError();
2781 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002782 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002783
Richard Smithfeea8832012-04-12 05:08:17 +00002784 // For an arithmetic operation, the implied arithmetic must be well-formed.
2785 if (Form == Arithmetic) {
2786 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2787 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2788 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2789 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2790 return ExprError();
2791 }
2792 if (!IsAddSub && !ValType->isIntegerType()) {
2793 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2794 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2795 return ExprError();
2796 }
David Majnemere85cff82015-01-28 05:48:06 +00002797 if (IsC11 && ValType->isPointerType() &&
2798 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2799 diag::err_incomplete_type)) {
2800 return ExprError();
2801 }
Richard Smithfeea8832012-04-12 05:08:17 +00002802 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2803 // For __atomic_*_n operations, the value type must be a scalar integral or
2804 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002805 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002806 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2807 return ExprError();
2808 }
2809
Eli Friedmanaa769812013-09-11 03:49:34 +00002810 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2811 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002812 // For GNU atomics, require a trivially-copyable type. This is not part of
2813 // the GNU atomics specification, but we enforce it for sanity.
2814 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002815 << Ptr->getType() << Ptr->getSourceRange();
2816 return ExprError();
2817 }
2818
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002819 switch (ValType.getObjCLifetime()) {
2820 case Qualifiers::OCL_None:
2821 case Qualifiers::OCL_ExplicitNone:
2822 // okay
2823 break;
2824
2825 case Qualifiers::OCL_Weak:
2826 case Qualifiers::OCL_Strong:
2827 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002828 // FIXME: Can this happen? By this point, ValType should be known
2829 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002830 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2831 << ValType << Ptr->getSourceRange();
2832 return ExprError();
2833 }
2834
David Majnemerc6eb6502015-06-03 00:26:35 +00002835 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2836 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002837 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002838 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002839 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002840 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002841 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002842 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002843 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002844 ResultType = Context.BoolTy;
2845
Richard Smithfeea8832012-04-12 05:08:17 +00002846 // The type of a parameter passed 'by value'. In the GNU atomics, such
2847 // arguments are actually passed as pointers.
2848 QualType ByValType = ValType; // 'CP'
2849 if (!IsC11 && !IsN)
2850 ByValType = Ptr->getType();
2851
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002852 // The first argument --- the pointer --- has a fixed type; we
2853 // deduce the types of the rest of the arguments accordingly. Walk
2854 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002855 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002856 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002857 if (i < NumVals[Form] + 1) {
2858 switch (i) {
2859 case 1:
2860 // The second argument is the non-atomic operand. For arithmetic, this
2861 // is always passed by value, and for a compare_exchange it is always
2862 // passed by address. For the rest, GNU uses by-address and C11 uses
2863 // by-value.
2864 assert(Form != Load);
2865 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2866 Ty = ValType;
2867 else if (Form == Copy || Form == Xchg)
2868 Ty = ByValType;
2869 else if (Form == Arithmetic)
2870 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002871 else {
2872 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002873 // Treat this argument as _Nonnull as we want to show a warning if
2874 // NULL is passed into it.
2875 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002876 unsigned AS = 0;
2877 // Keep address space of non-atomic pointer type.
2878 if (const PointerType *PtrTy =
2879 ValArg->getType()->getAs<PointerType>()) {
2880 AS = PtrTy->getPointeeType().getAddressSpace();
2881 }
2882 Ty = Context.getPointerType(
2883 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2884 }
Richard Smithfeea8832012-04-12 05:08:17 +00002885 break;
2886 case 2:
2887 // The third argument to compare_exchange / GNU exchange is a
2888 // (pointer to a) desired value.
2889 Ty = ByValType;
2890 break;
2891 case 3:
2892 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2893 Ty = Context.BoolTy;
2894 break;
2895 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002896 } else {
2897 // The order(s) are always converted to int.
2898 Ty = Context.IntTy;
2899 }
Richard Smithfeea8832012-04-12 05:08:17 +00002900
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002901 InitializedEntity Entity =
2902 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002903 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002904 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2905 if (Arg.isInvalid())
2906 return true;
2907 TheCall->setArg(i, Arg.get());
2908 }
2909
Richard Smithfeea8832012-04-12 05:08:17 +00002910 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002911 SmallVector<Expr*, 5> SubExprs;
2912 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002913 switch (Form) {
2914 case Init:
2915 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002916 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002917 break;
2918 case Load:
2919 SubExprs.push_back(TheCall->getArg(1)); // Order
2920 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002921 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002922 case Copy:
2923 case Arithmetic:
2924 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002925 SubExprs.push_back(TheCall->getArg(2)); // Order
2926 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002927 break;
2928 case GNUXchg:
2929 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2930 SubExprs.push_back(TheCall->getArg(3)); // Order
2931 SubExprs.push_back(TheCall->getArg(1)); // Val1
2932 SubExprs.push_back(TheCall->getArg(2)); // Val2
2933 break;
2934 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002935 SubExprs.push_back(TheCall->getArg(3)); // Order
2936 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002937 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002938 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002939 break;
2940 case GNUCmpXchg:
2941 SubExprs.push_back(TheCall->getArg(4)); // Order
2942 SubExprs.push_back(TheCall->getArg(1)); // Val1
2943 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2944 SubExprs.push_back(TheCall->getArg(2)); // Val2
2945 SubExprs.push_back(TheCall->getArg(3)); // Weak
2946 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002947 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002948
2949 if (SubExprs.size() >= 2 && Form != Init) {
2950 llvm::APSInt Result(32);
2951 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2952 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002953 Diag(SubExprs[1]->getLocStart(),
2954 diag::warn_atomic_op_has_invalid_memory_order)
2955 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002956 }
2957
Fariborz Jahanian615de762013-05-28 17:37:39 +00002958 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2959 SubExprs, ResultType, Op,
2960 TheCall->getRParenLoc());
2961
2962 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2963 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2964 Context.AtomicUsesUnsupportedLibcall(AE))
2965 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2966 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002967
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002968 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002969}
2970
John McCall29ad95b2011-08-27 01:09:30 +00002971/// checkBuiltinArgument - Given a call to a builtin function, perform
2972/// normal type-checking on the given argument, updating the call in
2973/// place. This is useful when a builtin function requires custom
2974/// type-checking for some of its arguments but not necessarily all of
2975/// them.
2976///
2977/// Returns true on error.
2978static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2979 FunctionDecl *Fn = E->getDirectCallee();
2980 assert(Fn && "builtin call without direct callee!");
2981
2982 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2983 InitializedEntity Entity =
2984 InitializedEntity::InitializeParameter(S.Context, Param);
2985
2986 ExprResult Arg = E->getArg(0);
2987 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2988 if (Arg.isInvalid())
2989 return true;
2990
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002991 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002992 return false;
2993}
2994
Chris Lattnerdc046542009-05-08 06:58:22 +00002995/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2996/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2997/// type of its first argument. The main ActOnCallExpr routines have already
2998/// promoted the types of arguments because all of these calls are prototyped as
2999/// void(...).
3000///
3001/// This function goes through and does final semantic checking for these
3002/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003003ExprResult
3004Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003005 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003006 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3007 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3008
3009 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003010 if (TheCall->getNumArgs() < 1) {
3011 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3012 << 0 << 1 << TheCall->getNumArgs()
3013 << TheCall->getCallee()->getSourceRange();
3014 return ExprError();
3015 }
Mike Stump11289f42009-09-09 15:08:12 +00003016
Chris Lattnerdc046542009-05-08 06:58:22 +00003017 // Inspect the first argument of the atomic builtin. This should always be
3018 // a pointer type, whose element is an integral scalar or pointer type.
3019 // Because it is a pointer type, we don't have to worry about any implicit
3020 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003021 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003022 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003023 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3024 if (FirstArgResult.isInvalid())
3025 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003026 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003027 TheCall->setArg(0, FirstArg);
3028
John McCall31168b02011-06-15 23:02:42 +00003029 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3030 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003031 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3032 << FirstArg->getType() << FirstArg->getSourceRange();
3033 return ExprError();
3034 }
Mike Stump11289f42009-09-09 15:08:12 +00003035
John McCall31168b02011-06-15 23:02:42 +00003036 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003037 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003038 !ValType->isBlockPointerType()) {
3039 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3040 << FirstArg->getType() << FirstArg->getSourceRange();
3041 return ExprError();
3042 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003043
John McCall31168b02011-06-15 23:02:42 +00003044 switch (ValType.getObjCLifetime()) {
3045 case Qualifiers::OCL_None:
3046 case Qualifiers::OCL_ExplicitNone:
3047 // okay
3048 break;
3049
3050 case Qualifiers::OCL_Weak:
3051 case Qualifiers::OCL_Strong:
3052 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003053 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003054 << ValType << FirstArg->getSourceRange();
3055 return ExprError();
3056 }
3057
John McCallb50451a2011-10-05 07:41:44 +00003058 // Strip any qualifiers off ValType.
3059 ValType = ValType.getUnqualifiedType();
3060
Chandler Carruth3973af72010-07-18 20:54:12 +00003061 // The majority of builtins return a value, but a few have special return
3062 // types, so allow them to override appropriately below.
3063 QualType ResultType = ValType;
3064
Chris Lattnerdc046542009-05-08 06:58:22 +00003065 // We need to figure out which concrete builtin this maps onto. For example,
3066 // __sync_fetch_and_add with a 2 byte object turns into
3067 // __sync_fetch_and_add_2.
3068#define BUILTIN_ROW(x) \
3069 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3070 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003071
Chris Lattnerdc046542009-05-08 06:58:22 +00003072 static const unsigned BuiltinIndices[][5] = {
3073 BUILTIN_ROW(__sync_fetch_and_add),
3074 BUILTIN_ROW(__sync_fetch_and_sub),
3075 BUILTIN_ROW(__sync_fetch_and_or),
3076 BUILTIN_ROW(__sync_fetch_and_and),
3077 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003078 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003079
Chris Lattnerdc046542009-05-08 06:58:22 +00003080 BUILTIN_ROW(__sync_add_and_fetch),
3081 BUILTIN_ROW(__sync_sub_and_fetch),
3082 BUILTIN_ROW(__sync_and_and_fetch),
3083 BUILTIN_ROW(__sync_or_and_fetch),
3084 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003085 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003086
Chris Lattnerdc046542009-05-08 06:58:22 +00003087 BUILTIN_ROW(__sync_val_compare_and_swap),
3088 BUILTIN_ROW(__sync_bool_compare_and_swap),
3089 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003090 BUILTIN_ROW(__sync_lock_release),
3091 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003092 };
Mike Stump11289f42009-09-09 15:08:12 +00003093#undef BUILTIN_ROW
3094
Chris Lattnerdc046542009-05-08 06:58:22 +00003095 // Determine the index of the size.
3096 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003097 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003098 case 1: SizeIndex = 0; break;
3099 case 2: SizeIndex = 1; break;
3100 case 4: SizeIndex = 2; break;
3101 case 8: SizeIndex = 3; break;
3102 case 16: SizeIndex = 4; break;
3103 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003104 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3105 << FirstArg->getType() << FirstArg->getSourceRange();
3106 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003107 }
Mike Stump11289f42009-09-09 15:08:12 +00003108
Chris Lattnerdc046542009-05-08 06:58:22 +00003109 // Each of these builtins has one pointer argument, followed by some number of
3110 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3111 // that we ignore. Find out which row of BuiltinIndices to read from as well
3112 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003113 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003114 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003115 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003116 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003117 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003118 case Builtin::BI__sync_fetch_and_add:
3119 case Builtin::BI__sync_fetch_and_add_1:
3120 case Builtin::BI__sync_fetch_and_add_2:
3121 case Builtin::BI__sync_fetch_and_add_4:
3122 case Builtin::BI__sync_fetch_and_add_8:
3123 case Builtin::BI__sync_fetch_and_add_16:
3124 BuiltinIndex = 0;
3125 break;
3126
3127 case Builtin::BI__sync_fetch_and_sub:
3128 case Builtin::BI__sync_fetch_and_sub_1:
3129 case Builtin::BI__sync_fetch_and_sub_2:
3130 case Builtin::BI__sync_fetch_and_sub_4:
3131 case Builtin::BI__sync_fetch_and_sub_8:
3132 case Builtin::BI__sync_fetch_and_sub_16:
3133 BuiltinIndex = 1;
3134 break;
3135
3136 case Builtin::BI__sync_fetch_and_or:
3137 case Builtin::BI__sync_fetch_and_or_1:
3138 case Builtin::BI__sync_fetch_and_or_2:
3139 case Builtin::BI__sync_fetch_and_or_4:
3140 case Builtin::BI__sync_fetch_and_or_8:
3141 case Builtin::BI__sync_fetch_and_or_16:
3142 BuiltinIndex = 2;
3143 break;
3144
3145 case Builtin::BI__sync_fetch_and_and:
3146 case Builtin::BI__sync_fetch_and_and_1:
3147 case Builtin::BI__sync_fetch_and_and_2:
3148 case Builtin::BI__sync_fetch_and_and_4:
3149 case Builtin::BI__sync_fetch_and_and_8:
3150 case Builtin::BI__sync_fetch_and_and_16:
3151 BuiltinIndex = 3;
3152 break;
Mike Stump11289f42009-09-09 15:08:12 +00003153
Douglas Gregor73722482011-11-28 16:30:08 +00003154 case Builtin::BI__sync_fetch_and_xor:
3155 case Builtin::BI__sync_fetch_and_xor_1:
3156 case Builtin::BI__sync_fetch_and_xor_2:
3157 case Builtin::BI__sync_fetch_and_xor_4:
3158 case Builtin::BI__sync_fetch_and_xor_8:
3159 case Builtin::BI__sync_fetch_and_xor_16:
3160 BuiltinIndex = 4;
3161 break;
3162
Hal Finkeld2208b52014-10-02 20:53:50 +00003163 case Builtin::BI__sync_fetch_and_nand:
3164 case Builtin::BI__sync_fetch_and_nand_1:
3165 case Builtin::BI__sync_fetch_and_nand_2:
3166 case Builtin::BI__sync_fetch_and_nand_4:
3167 case Builtin::BI__sync_fetch_and_nand_8:
3168 case Builtin::BI__sync_fetch_and_nand_16:
3169 BuiltinIndex = 5;
3170 WarnAboutSemanticsChange = true;
3171 break;
3172
Douglas Gregor73722482011-11-28 16:30:08 +00003173 case Builtin::BI__sync_add_and_fetch:
3174 case Builtin::BI__sync_add_and_fetch_1:
3175 case Builtin::BI__sync_add_and_fetch_2:
3176 case Builtin::BI__sync_add_and_fetch_4:
3177 case Builtin::BI__sync_add_and_fetch_8:
3178 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003179 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003180 break;
3181
3182 case Builtin::BI__sync_sub_and_fetch:
3183 case Builtin::BI__sync_sub_and_fetch_1:
3184 case Builtin::BI__sync_sub_and_fetch_2:
3185 case Builtin::BI__sync_sub_and_fetch_4:
3186 case Builtin::BI__sync_sub_and_fetch_8:
3187 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003188 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003189 break;
3190
3191 case Builtin::BI__sync_and_and_fetch:
3192 case Builtin::BI__sync_and_and_fetch_1:
3193 case Builtin::BI__sync_and_and_fetch_2:
3194 case Builtin::BI__sync_and_and_fetch_4:
3195 case Builtin::BI__sync_and_and_fetch_8:
3196 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003197 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003198 break;
3199
3200 case Builtin::BI__sync_or_and_fetch:
3201 case Builtin::BI__sync_or_and_fetch_1:
3202 case Builtin::BI__sync_or_and_fetch_2:
3203 case Builtin::BI__sync_or_and_fetch_4:
3204 case Builtin::BI__sync_or_and_fetch_8:
3205 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003206 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003207 break;
3208
3209 case Builtin::BI__sync_xor_and_fetch:
3210 case Builtin::BI__sync_xor_and_fetch_1:
3211 case Builtin::BI__sync_xor_and_fetch_2:
3212 case Builtin::BI__sync_xor_and_fetch_4:
3213 case Builtin::BI__sync_xor_and_fetch_8:
3214 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003215 BuiltinIndex = 10;
3216 break;
3217
3218 case Builtin::BI__sync_nand_and_fetch:
3219 case Builtin::BI__sync_nand_and_fetch_1:
3220 case Builtin::BI__sync_nand_and_fetch_2:
3221 case Builtin::BI__sync_nand_and_fetch_4:
3222 case Builtin::BI__sync_nand_and_fetch_8:
3223 case Builtin::BI__sync_nand_and_fetch_16:
3224 BuiltinIndex = 11;
3225 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003226 break;
Mike Stump11289f42009-09-09 15:08:12 +00003227
Chris Lattnerdc046542009-05-08 06:58:22 +00003228 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003229 case Builtin::BI__sync_val_compare_and_swap_1:
3230 case Builtin::BI__sync_val_compare_and_swap_2:
3231 case Builtin::BI__sync_val_compare_and_swap_4:
3232 case Builtin::BI__sync_val_compare_and_swap_8:
3233 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003234 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003235 NumFixed = 2;
3236 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003237
Chris Lattnerdc046542009-05-08 06:58:22 +00003238 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003239 case Builtin::BI__sync_bool_compare_and_swap_1:
3240 case Builtin::BI__sync_bool_compare_and_swap_2:
3241 case Builtin::BI__sync_bool_compare_and_swap_4:
3242 case Builtin::BI__sync_bool_compare_and_swap_8:
3243 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003244 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003245 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003246 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003247 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003248
3249 case Builtin::BI__sync_lock_test_and_set:
3250 case Builtin::BI__sync_lock_test_and_set_1:
3251 case Builtin::BI__sync_lock_test_and_set_2:
3252 case Builtin::BI__sync_lock_test_and_set_4:
3253 case Builtin::BI__sync_lock_test_and_set_8:
3254 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003255 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003256 break;
3257
Chris Lattnerdc046542009-05-08 06:58:22 +00003258 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003259 case Builtin::BI__sync_lock_release_1:
3260 case Builtin::BI__sync_lock_release_2:
3261 case Builtin::BI__sync_lock_release_4:
3262 case Builtin::BI__sync_lock_release_8:
3263 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003264 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003265 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003266 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003267 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003268
3269 case Builtin::BI__sync_swap:
3270 case Builtin::BI__sync_swap_1:
3271 case Builtin::BI__sync_swap_2:
3272 case Builtin::BI__sync_swap_4:
3273 case Builtin::BI__sync_swap_8:
3274 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003275 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003276 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003277 }
Mike Stump11289f42009-09-09 15:08:12 +00003278
Chris Lattnerdc046542009-05-08 06:58:22 +00003279 // Now that we know how many fixed arguments we expect, first check that we
3280 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003281 if (TheCall->getNumArgs() < 1+NumFixed) {
3282 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3283 << 0 << 1+NumFixed << TheCall->getNumArgs()
3284 << TheCall->getCallee()->getSourceRange();
3285 return ExprError();
3286 }
Mike Stump11289f42009-09-09 15:08:12 +00003287
Hal Finkeld2208b52014-10-02 20:53:50 +00003288 if (WarnAboutSemanticsChange) {
3289 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3290 << TheCall->getCallee()->getSourceRange();
3291 }
3292
Chris Lattner5b9241b2009-05-08 15:36:58 +00003293 // Get the decl for the concrete builtin from this, we can tell what the
3294 // concrete integer type we should convert to is.
3295 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003296 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003297 FunctionDecl *NewBuiltinDecl;
3298 if (NewBuiltinID == BuiltinID)
3299 NewBuiltinDecl = FDecl;
3300 else {
3301 // Perform builtin lookup to avoid redeclaring it.
3302 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3303 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3304 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3305 assert(Res.getFoundDecl());
3306 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003307 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003308 return ExprError();
3309 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003310
John McCallcf142162010-08-07 06:22:56 +00003311 // The first argument --- the pointer --- has a fixed type; we
3312 // deduce the types of the rest of the arguments accordingly. Walk
3313 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003314 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003315 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003316
Chris Lattnerdc046542009-05-08 06:58:22 +00003317 // GCC does an implicit conversion to the pointer or integer ValType. This
3318 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003319 // Initialize the argument.
3320 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3321 ValType, /*consume*/ false);
3322 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003323 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003324 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003325
Chris Lattnerdc046542009-05-08 06:58:22 +00003326 // Okay, we have something that *can* be converted to the right type. Check
3327 // to see if there is a potentially weird extension going on here. This can
3328 // happen when you do an atomic operation on something like an char* and
3329 // pass in 42. The 42 gets converted to char. This is even more strange
3330 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003331 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003332 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003333 }
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003335 ASTContext& Context = this->getASTContext();
3336
3337 // Create a new DeclRefExpr to refer to the new decl.
3338 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3339 Context,
3340 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003341 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003342 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003343 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003344 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003345 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003346 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003347
Chris Lattnerdc046542009-05-08 06:58:22 +00003348 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003349 // FIXME: This loses syntactic information.
3350 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3351 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3352 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003353 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003354
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003355 // Change the result type of the call to match the original value type. This
3356 // is arbitrary, but the codegen for these builtins ins design to handle it
3357 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003358 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003359
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003360 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003361}
3362
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003363/// SemaBuiltinNontemporalOverloaded - We have a call to
3364/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3365/// overloaded function based on the pointer type of its last argument.
3366///
3367/// This function goes through and does final semantic checking for these
3368/// builtins.
3369ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3370 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3371 DeclRefExpr *DRE =
3372 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3373 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3374 unsigned BuiltinID = FDecl->getBuiltinID();
3375 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3376 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3377 "Unexpected nontemporal load/store builtin!");
3378 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3379 unsigned numArgs = isStore ? 2 : 1;
3380
3381 // Ensure that we have the proper number of arguments.
3382 if (checkArgCount(*this, TheCall, numArgs))
3383 return ExprError();
3384
3385 // Inspect the last argument of the nontemporal builtin. This should always
3386 // be a pointer type, from which we imply the type of the memory access.
3387 // Because it is a pointer type, we don't have to worry about any implicit
3388 // casts here.
3389 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3390 ExprResult PointerArgResult =
3391 DefaultFunctionArrayLvalueConversion(PointerArg);
3392
3393 if (PointerArgResult.isInvalid())
3394 return ExprError();
3395 PointerArg = PointerArgResult.get();
3396 TheCall->setArg(numArgs - 1, PointerArg);
3397
3398 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3399 if (!pointerType) {
3400 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3401 << PointerArg->getType() << PointerArg->getSourceRange();
3402 return ExprError();
3403 }
3404
3405 QualType ValType = pointerType->getPointeeType();
3406
3407 // Strip any qualifiers off ValType.
3408 ValType = ValType.getUnqualifiedType();
3409 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3410 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3411 !ValType->isVectorType()) {
3412 Diag(DRE->getLocStart(),
3413 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3414 << PointerArg->getType() << PointerArg->getSourceRange();
3415 return ExprError();
3416 }
3417
3418 if (!isStore) {
3419 TheCall->setType(ValType);
3420 return TheCallResult;
3421 }
3422
3423 ExprResult ValArg = TheCall->getArg(0);
3424 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3425 Context, ValType, /*consume*/ false);
3426 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3427 if (ValArg.isInvalid())
3428 return ExprError();
3429
3430 TheCall->setArg(0, ValArg.get());
3431 TheCall->setType(Context.VoidTy);
3432 return TheCallResult;
3433}
3434
Chris Lattner6436fb62009-02-18 06:01:06 +00003435/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003436/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003437/// Note: It might also make sense to do the UTF-16 conversion here (would
3438/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003439bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003440 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003441 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3442
Douglas Gregorfb65e592011-07-27 05:40:30 +00003443 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003444 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3445 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003446 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003447 }
Mike Stump11289f42009-09-09 15:08:12 +00003448
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003449 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003450 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003451 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003452 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3453 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3454 llvm::UTF16 *ToPtr = &ToBuf[0];
3455
3456 llvm::ConversionResult Result =
3457 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3458 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003459 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003460 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003461 Diag(Arg->getLocStart(),
3462 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3463 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003464 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003465}
3466
Mehdi Amini06d367c2016-10-24 20:39:34 +00003467/// CheckObjCString - Checks that the format string argument to the os_log()
3468/// and os_trace() functions is correct, and converts it to const char *.
3469ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3470 Arg = Arg->IgnoreParenCasts();
3471 auto *Literal = dyn_cast<StringLiteral>(Arg);
3472 if (!Literal) {
3473 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3474 Literal = ObjcLiteral->getString();
3475 }
3476 }
3477
3478 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3479 return ExprError(
3480 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3481 << Arg->getSourceRange());
3482 }
3483
3484 ExprResult Result(Literal);
3485 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3486 InitializedEntity Entity =
3487 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3488 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3489 return Result;
3490}
3491
Charles Davisc7d5c942015-09-17 20:55:33 +00003492/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3493/// for validity. Emit an error and return true on failure; return false
3494/// on success.
3495bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003496 Expr *Fn = TheCall->getCallee();
3497 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003498 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003499 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003500 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3501 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003502 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003503 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003504 return true;
3505 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003506
3507 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003508 return Diag(TheCall->getLocEnd(),
3509 diag::err_typecheck_call_too_few_args_at_least)
3510 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003511 }
3512
John McCall29ad95b2011-08-27 01:09:30 +00003513 // Type-check the first argument normally.
3514 if (checkBuiltinArgument(*this, TheCall, 0))
3515 return true;
3516
Chris Lattnere202e6a2007-12-20 00:05:45 +00003517 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003518 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003519 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003520 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003521 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003522 else if (FunctionDecl *FD = getCurFunctionDecl())
3523 isVariadic = FD->isVariadic();
3524 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003525 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003526
Chris Lattnere202e6a2007-12-20 00:05:45 +00003527 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003528 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3529 return true;
3530 }
Mike Stump11289f42009-09-09 15:08:12 +00003531
Chris Lattner43be2e62007-12-19 23:59:04 +00003532 // Verify that the second argument to the builtin is the last argument of the
3533 // current function or method.
3534 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003535 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003536
Nico Weber9eea7642013-05-24 23:31:57 +00003537 // These are valid if SecondArgIsLastNamedArgument is false after the next
3538 // block.
3539 QualType Type;
3540 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003541 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003542
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003543 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3544 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003545 // FIXME: This isn't correct for methods (results in bogus warning).
3546 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003547 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003548 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003549 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003550 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003551 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003552 else
David Majnemera3debed2016-06-24 05:33:44 +00003553 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003554 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003555
3556 Type = PV->getType();
3557 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003558 IsCRegister =
3559 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003560 }
3561 }
Mike Stump11289f42009-09-09 15:08:12 +00003562
Chris Lattner43be2e62007-12-19 23:59:04 +00003563 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003564 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003565 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003566 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003567 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3568 // Promotable integers are UB, but enumerations need a bit of
3569 // extra checking to see what their promotable type actually is.
3570 if (!Type->isPromotableIntegerType())
3571 return false;
3572 if (!Type->isEnumeralType())
3573 return true;
3574 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3575 return !(ED &&
3576 Context.typesAreCompatible(ED->getPromotionType(), Type));
3577 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003578 unsigned Reason = 0;
3579 if (Type->isReferenceType()) Reason = 1;
3580 else if (IsCRegister) Reason = 2;
3581 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003582 Diag(ParamLoc, diag::note_parameter_type) << Type;
3583 }
3584
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003585 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003586 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003587}
Chris Lattner43be2e62007-12-19 23:59:04 +00003588
Charles Davisc7d5c942015-09-17 20:55:33 +00003589/// Check the arguments to '__builtin_va_start' for validity, and that
3590/// it was called from a function of the native ABI.
3591/// Emit an error and return true on failure; return false on success.
3592bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3593 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3594 // On x64 Windows, don't allow this in System V ABI functions.
3595 // (Yes, that means there's no corresponding way to support variadic
3596 // System V ABI functions on Windows.)
3597 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3598 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3599 clang::CallingConv CC = CC_C;
3600 if (const FunctionDecl *FD = getCurFunctionDecl())
3601 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3602 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3603 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3604 return Diag(TheCall->getCallee()->getLocStart(),
3605 diag::err_va_start_used_in_wrong_abi_function)
3606 << (OS != llvm::Triple::Win32);
3607 }
3608 return SemaBuiltinVAStartImpl(TheCall);
3609}
3610
3611/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3612/// it was called from a Win64 ABI function.
3613/// Emit an error and return true on failure; return false on success.
3614bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3615 // This only makes sense for x86-64.
3616 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3617 Expr *Callee = TheCall->getCallee();
3618 if (TT.getArch() != llvm::Triple::x86_64)
3619 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3620 // Don't allow this in System V ABI functions.
3621 clang::CallingConv CC = CC_C;
3622 if (const FunctionDecl *FD = getCurFunctionDecl())
3623 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3624 if (CC == CC_X86_64SysV ||
3625 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3626 return Diag(Callee->getLocStart(),
3627 diag::err_ms_va_start_used_in_sysv_function);
3628 return SemaBuiltinVAStartImpl(TheCall);
3629}
3630
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003631bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3632 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3633 // const char *named_addr);
3634
3635 Expr *Func = Call->getCallee();
3636
3637 if (Call->getNumArgs() < 3)
3638 return Diag(Call->getLocEnd(),
3639 diag::err_typecheck_call_too_few_args_at_least)
3640 << 0 /*function call*/ << 3 << Call->getNumArgs();
3641
3642 // Determine whether the current function is variadic or not.
3643 bool IsVariadic;
3644 if (BlockScopeInfo *CurBlock = getCurBlock())
3645 IsVariadic = CurBlock->TheDecl->isVariadic();
3646 else if (FunctionDecl *FD = getCurFunctionDecl())
3647 IsVariadic = FD->isVariadic();
3648 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3649 IsVariadic = MD->isVariadic();
3650 else
3651 llvm_unreachable("unexpected statement type");
3652
3653 if (!IsVariadic) {
3654 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3655 return true;
3656 }
3657
3658 // Type-check the first argument normally.
3659 if (checkBuiltinArgument(*this, Call, 0))
3660 return true;
3661
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003662 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003663 unsigned ArgNo;
3664 QualType Type;
3665 } ArgumentTypes[] = {
3666 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3667 { 2, Context.getSizeType() },
3668 };
3669
3670 for (const auto &AT : ArgumentTypes) {
3671 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3672 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3673 continue;
3674 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3675 << Arg->getType() << AT.Type << 1 /* different class */
3676 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3677 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3678 }
3679
3680 return false;
3681}
3682
Chris Lattner2da14fb2007-12-20 00:26:33 +00003683/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3684/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003685bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3686 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003687 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003688 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003689 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003690 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003691 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003692 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003693 << SourceRange(TheCall->getArg(2)->getLocStart(),
3694 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003695
John Wiegley01296292011-04-08 18:41:53 +00003696 ExprResult OrigArg0 = TheCall->getArg(0);
3697 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003698
Chris Lattner2da14fb2007-12-20 00:26:33 +00003699 // Do standard promotions between the two arguments, returning their common
3700 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003701 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003702 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3703 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003704
3705 // Make sure any conversions are pushed back into the call; this is
3706 // type safe since unordered compare builtins are declared as "_Bool
3707 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003708 TheCall->setArg(0, OrigArg0.get());
3709 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003710
John Wiegley01296292011-04-08 18:41:53 +00003711 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003712 return false;
3713
Chris Lattner2da14fb2007-12-20 00:26:33 +00003714 // If the common type isn't a real floating type, then the arguments were
3715 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003716 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003717 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003718 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003719 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3720 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003721
Chris Lattner2da14fb2007-12-20 00:26:33 +00003722 return false;
3723}
3724
Benjamin Kramer634fc102010-02-15 22:42:31 +00003725/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3726/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003727/// to check everything. We expect the last argument to be a floating point
3728/// value.
3729bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3730 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003731 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003732 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003733 if (TheCall->getNumArgs() > NumArgs)
3734 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003735 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003736 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003737 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003738 (*(TheCall->arg_end()-1))->getLocEnd());
3739
Benjamin Kramer64aae502010-02-16 10:07:31 +00003740 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003741
Eli Friedman7e4faac2009-08-31 20:06:00 +00003742 if (OrigArg->isTypeDependent())
3743 return false;
3744
Chris Lattner68784ef2010-05-06 05:50:07 +00003745 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003746 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003747 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003748 diag::err_typecheck_call_invalid_unary_fp)
3749 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003750
Neil Hickey88c0fac2016-12-13 16:22:50 +00003751 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003752 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3753 Expr *CastArg = Cast->getSubExpr();
3754 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Neil Hickey88c0fac2016-12-13 16:22:50 +00003755 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3756 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3757 "promotion from float to either float or double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003758 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003759 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003760 }
3761 }
3762
Eli Friedman7e4faac2009-08-31 20:06:00 +00003763 return false;
3764}
3765
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003766/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3767// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003768ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003769 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003770 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003771 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003772 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3773 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003774
Nate Begemana0110022010-06-08 00:16:34 +00003775 // Determine which of the following types of shufflevector we're checking:
3776 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003777 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003778 QualType resType = TheCall->getArg(0)->getType();
3779 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003780
Douglas Gregorc25f7662009-05-19 22:10:17 +00003781 if (!TheCall->getArg(0)->isTypeDependent() &&
3782 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003783 QualType LHSType = TheCall->getArg(0)->getType();
3784 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003785
Craig Topperbaca3892013-07-29 06:47:04 +00003786 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3787 return ExprError(Diag(TheCall->getLocStart(),
3788 diag::err_shufflevector_non_vector)
3789 << SourceRange(TheCall->getArg(0)->getLocStart(),
3790 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003791
Nate Begemana0110022010-06-08 00:16:34 +00003792 numElements = LHSType->getAs<VectorType>()->getNumElements();
3793 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003794
Nate Begemana0110022010-06-08 00:16:34 +00003795 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3796 // with mask. If so, verify that RHS is an integer vector type with the
3797 // same number of elts as lhs.
3798 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003799 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003800 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003801 return ExprError(Diag(TheCall->getLocStart(),
3802 diag::err_shufflevector_incompatible_vector)
3803 << SourceRange(TheCall->getArg(1)->getLocStart(),
3804 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003805 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003806 return ExprError(Diag(TheCall->getLocStart(),
3807 diag::err_shufflevector_incompatible_vector)
3808 << SourceRange(TheCall->getArg(0)->getLocStart(),
3809 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003810 } else if (numElements != numResElements) {
3811 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003812 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003813 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003814 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003815 }
3816
3817 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003818 if (TheCall->getArg(i)->isTypeDependent() ||
3819 TheCall->getArg(i)->isValueDependent())
3820 continue;
3821
Nate Begemana0110022010-06-08 00:16:34 +00003822 llvm::APSInt Result(32);
3823 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3824 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003825 diag::err_shufflevector_nonconstant_argument)
3826 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003827
Craig Topper50ad5b72013-08-03 17:40:38 +00003828 // Allow -1 which will be translated to undef in the IR.
3829 if (Result.isSigned() && Result.isAllOnesValue())
3830 continue;
3831
Chris Lattner7ab824e2008-08-10 02:05:13 +00003832 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003833 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003834 diag::err_shufflevector_argument_too_large)
3835 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003836 }
3837
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003838 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003839
Chris Lattner7ab824e2008-08-10 02:05:13 +00003840 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003841 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003842 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003843 }
3844
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003845 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3846 TheCall->getCallee()->getLocStart(),
3847 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003848}
Chris Lattner43be2e62007-12-19 23:59:04 +00003849
Hal Finkelc4d7c822013-09-18 03:29:45 +00003850/// SemaConvertVectorExpr - Handle __builtin_convertvector
3851ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3852 SourceLocation BuiltinLoc,
3853 SourceLocation RParenLoc) {
3854 ExprValueKind VK = VK_RValue;
3855 ExprObjectKind OK = OK_Ordinary;
3856 QualType DstTy = TInfo->getType();
3857 QualType SrcTy = E->getType();
3858
3859 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3860 return ExprError(Diag(BuiltinLoc,
3861 diag::err_convertvector_non_vector)
3862 << E->getSourceRange());
3863 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3864 return ExprError(Diag(BuiltinLoc,
3865 diag::err_convertvector_non_vector_type));
3866
3867 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3868 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3869 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3870 if (SrcElts != DstElts)
3871 return ExprError(Diag(BuiltinLoc,
3872 diag::err_convertvector_incompatible_vector)
3873 << E->getSourceRange());
3874 }
3875
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003876 return new (Context)
3877 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003878}
3879
Daniel Dunbarb7257262008-07-21 22:59:13 +00003880/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3881// This is declared to take (const void*, ...) and can take two
3882// optional constant int args.
3883bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003884 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003885
Chris Lattner3b054132008-11-19 05:08:23 +00003886 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003887 return Diag(TheCall->getLocEnd(),
3888 diag::err_typecheck_call_too_many_args_at_most)
3889 << 0 /*function call*/ << 3 << NumArgs
3890 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003891
3892 // Argument 0 is checked for us and the remaining arguments must be
3893 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003894 for (unsigned i = 1; i != NumArgs; ++i)
3895 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003896 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003897
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003898 return false;
3899}
3900
Hal Finkelf0417332014-07-17 14:25:55 +00003901/// SemaBuiltinAssume - Handle __assume (MS Extension).
3902// __assume does not evaluate its arguments, and should warn if its argument
3903// has side effects.
3904bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3905 Expr *Arg = TheCall->getArg(0);
3906 if (Arg->isInstantiationDependent()) return false;
3907
3908 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003909 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003910 << Arg->getSourceRange()
3911 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3912
3913 return false;
3914}
3915
David Majnemer86b1bfa2016-10-31 18:07:57 +00003916/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003917/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3918/// than 8.
3919bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3920 // The alignment must be a constant integer.
3921 Expr *Arg = TheCall->getArg(1);
3922
3923 // We can't check the value of a dependent argument.
3924 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003925 if (const auto *UE =
3926 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3927 if (UE->getKind() == UETT_AlignOf)
3928 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3929 << Arg->getSourceRange();
3930
David Majnemer51169932016-10-31 05:37:48 +00003931 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3932
3933 if (!Result.isPowerOf2())
3934 return Diag(TheCall->getLocStart(),
3935 diag::err_alignment_not_power_of_two)
3936 << Arg->getSourceRange();
3937
3938 if (Result < Context.getCharWidth())
3939 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3940 << (unsigned)Context.getCharWidth()
3941 << Arg->getSourceRange();
3942
3943 if (Result > INT32_MAX)
3944 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3945 << INT32_MAX
3946 << Arg->getSourceRange();
3947 }
3948
3949 return false;
3950}
3951
3952/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003953/// as (const void*, size_t, ...) and can take one optional constant int arg.
3954bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3955 unsigned NumArgs = TheCall->getNumArgs();
3956
3957 if (NumArgs > 3)
3958 return Diag(TheCall->getLocEnd(),
3959 diag::err_typecheck_call_too_many_args_at_most)
3960 << 0 /*function call*/ << 3 << NumArgs
3961 << TheCall->getSourceRange();
3962
3963 // The alignment must be a constant integer.
3964 Expr *Arg = TheCall->getArg(1);
3965
3966 // We can't check the value of a dependent argument.
3967 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3968 llvm::APSInt Result;
3969 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3970 return true;
3971
3972 if (!Result.isPowerOf2())
3973 return Diag(TheCall->getLocStart(),
3974 diag::err_alignment_not_power_of_two)
3975 << Arg->getSourceRange();
3976 }
3977
3978 if (NumArgs > 2) {
3979 ExprResult Arg(TheCall->getArg(2));
3980 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3981 Context.getSizeType(), false);
3982 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3983 if (Arg.isInvalid()) return true;
3984 TheCall->setArg(2, Arg.get());
3985 }
Hal Finkelf0417332014-07-17 14:25:55 +00003986
3987 return false;
3988}
3989
Mehdi Amini06d367c2016-10-24 20:39:34 +00003990bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3991 unsigned BuiltinID =
3992 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3993 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3994
3995 unsigned NumArgs = TheCall->getNumArgs();
3996 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3997 if (NumArgs < NumRequiredArgs) {
3998 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3999 << 0 /* function call */ << NumRequiredArgs << NumArgs
4000 << TheCall->getSourceRange();
4001 }
4002 if (NumArgs >= NumRequiredArgs + 0x100) {
4003 return Diag(TheCall->getLocEnd(),
4004 diag::err_typecheck_call_too_many_args_at_most)
4005 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4006 << TheCall->getSourceRange();
4007 }
4008 unsigned i = 0;
4009
4010 // For formatting call, check buffer arg.
4011 if (!IsSizeCall) {
4012 ExprResult Arg(TheCall->getArg(i));
4013 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4014 Context, Context.VoidPtrTy, false);
4015 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4016 if (Arg.isInvalid())
4017 return true;
4018 TheCall->setArg(i, Arg.get());
4019 i++;
4020 }
4021
4022 // Check string literal arg.
4023 unsigned FormatIdx = i;
4024 {
4025 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4026 if (Arg.isInvalid())
4027 return true;
4028 TheCall->setArg(i, Arg.get());
4029 i++;
4030 }
4031
4032 // Make sure variadic args are scalar.
4033 unsigned FirstDataArg = i;
4034 while (i < NumArgs) {
4035 ExprResult Arg = DefaultVariadicArgumentPromotion(
4036 TheCall->getArg(i), VariadicFunction, nullptr);
4037 if (Arg.isInvalid())
4038 return true;
4039 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4040 if (ArgSize.getQuantity() >= 0x100) {
4041 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4042 << i << (int)ArgSize.getQuantity() << 0xff
4043 << TheCall->getSourceRange();
4044 }
4045 TheCall->setArg(i, Arg.get());
4046 i++;
4047 }
4048
4049 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4050 // call to avoid duplicate diagnostics.
4051 if (!IsSizeCall) {
4052 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4053 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4054 bool Success = CheckFormatArguments(
4055 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4056 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4057 CheckedVarArgs);
4058 if (!Success)
4059 return true;
4060 }
4061
4062 if (IsSizeCall) {
4063 TheCall->setType(Context.getSizeType());
4064 } else {
4065 TheCall->setType(Context.VoidPtrTy);
4066 }
4067 return false;
4068}
4069
Eric Christopher8d0c6212010-04-17 02:26:23 +00004070/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4071/// TheCall is a constant expression.
4072bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4073 llvm::APSInt &Result) {
4074 Expr *Arg = TheCall->getArg(ArgNum);
4075 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4076 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4077
4078 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4079
4080 if (!Arg->isIntegerConstantExpr(Result, Context))
4081 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004082 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004083
Chris Lattnerd545ad12009-09-23 06:06:36 +00004084 return false;
4085}
4086
Richard Sandiford28940af2014-04-16 08:47:51 +00004087/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4088/// TheCall is a constant expression in the range [Low, High].
4089bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4090 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004091 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004092
4093 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004094 Expr *Arg = TheCall->getArg(ArgNum);
4095 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004096 return false;
4097
Eric Christopher8d0c6212010-04-17 02:26:23 +00004098 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004099 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004100 return true;
4101
Richard Sandiford28940af2014-04-16 08:47:51 +00004102 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004103 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004104 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004105
4106 return false;
4107}
4108
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004109/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4110/// TheCall is a constant expression is a multiple of Num..
4111bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4112 unsigned Num) {
4113 llvm::APSInt Result;
4114
4115 // We can't check the value of a dependent argument.
4116 Expr *Arg = TheCall->getArg(ArgNum);
4117 if (Arg->isTypeDependent() || Arg->isValueDependent())
4118 return false;
4119
4120 // Check constant-ness first.
4121 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4122 return true;
4123
4124 if (Result.getSExtValue() % Num != 0)
4125 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4126 << Num << Arg->getSourceRange();
4127
4128 return false;
4129}
4130
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004131/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4132/// TheCall is an ARM/AArch64 special register string literal.
4133bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4134 int ArgNum, unsigned ExpectedFieldNum,
4135 bool AllowName) {
4136 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4137 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4138 BuiltinID == ARM::BI__builtin_arm_rsr ||
4139 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4140 BuiltinID == ARM::BI__builtin_arm_wsr ||
4141 BuiltinID == ARM::BI__builtin_arm_wsrp;
4142 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4143 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4144 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4145 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4146 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4147 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4148 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4149
4150 // We can't check the value of a dependent argument.
4151 Expr *Arg = TheCall->getArg(ArgNum);
4152 if (Arg->isTypeDependent() || Arg->isValueDependent())
4153 return false;
4154
4155 // Check if the argument is a string literal.
4156 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4157 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4158 << Arg->getSourceRange();
4159
4160 // Check the type of special register given.
4161 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4162 SmallVector<StringRef, 6> Fields;
4163 Reg.split(Fields, ":");
4164
4165 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4166 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4167 << Arg->getSourceRange();
4168
4169 // If the string is the name of a register then we cannot check that it is
4170 // valid here but if the string is of one the forms described in ACLE then we
4171 // can check that the supplied fields are integers and within the valid
4172 // ranges.
4173 if (Fields.size() > 1) {
4174 bool FiveFields = Fields.size() == 5;
4175
4176 bool ValidString = true;
4177 if (IsARMBuiltin) {
4178 ValidString &= Fields[0].startswith_lower("cp") ||
4179 Fields[0].startswith_lower("p");
4180 if (ValidString)
4181 Fields[0] =
4182 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4183
4184 ValidString &= Fields[2].startswith_lower("c");
4185 if (ValidString)
4186 Fields[2] = Fields[2].drop_front(1);
4187
4188 if (FiveFields) {
4189 ValidString &= Fields[3].startswith_lower("c");
4190 if (ValidString)
4191 Fields[3] = Fields[3].drop_front(1);
4192 }
4193 }
4194
4195 SmallVector<int, 5> Ranges;
4196 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004197 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004198 else
4199 Ranges.append({15, 7, 15});
4200
4201 for (unsigned i=0; i<Fields.size(); ++i) {
4202 int IntField;
4203 ValidString &= !Fields[i].getAsInteger(10, IntField);
4204 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4205 }
4206
4207 if (!ValidString)
4208 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4209 << Arg->getSourceRange();
4210
4211 } else if (IsAArch64Builtin && Fields.size() == 1) {
4212 // If the register name is one of those that appear in the condition below
4213 // and the special register builtin being used is one of the write builtins,
4214 // then we require that the argument provided for writing to the register
4215 // is an integer constant expression. This is because it will be lowered to
4216 // an MSR (immediate) instruction, so we need to know the immediate at
4217 // compile time.
4218 if (TheCall->getNumArgs() != 2)
4219 return false;
4220
4221 std::string RegLower = Reg.lower();
4222 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4223 RegLower != "pan" && RegLower != "uao")
4224 return false;
4225
4226 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4227 }
4228
4229 return false;
4230}
4231
Eli Friedmanc97d0142009-05-03 06:04:26 +00004232/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004233/// This checks that the target supports __builtin_longjmp and
4234/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004235bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004236 if (!Context.getTargetInfo().hasSjLjLowering())
4237 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4238 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4239
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004240 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004241 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004242
Eric Christopher8d0c6212010-04-17 02:26:23 +00004243 // TODO: This is less than ideal. Overload this to take a value.
4244 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4245 return true;
4246
4247 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004248 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4249 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4250
4251 return false;
4252}
4253
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004254/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4255/// This checks that the target supports __builtin_setjmp.
4256bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4257 if (!Context.getTargetInfo().hasSjLjLowering())
4258 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4259 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4260 return false;
4261}
4262
Richard Smithd7293d72013-08-05 18:49:43 +00004263namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004264class UncoveredArgHandler {
4265 enum { Unknown = -1, AllCovered = -2 };
4266 signed FirstUncoveredArg;
4267 SmallVector<const Expr *, 4> DiagnosticExprs;
4268
4269public:
4270 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4271
4272 bool hasUncoveredArg() const {
4273 return (FirstUncoveredArg >= 0);
4274 }
4275
4276 unsigned getUncoveredArg() const {
4277 assert(hasUncoveredArg() && "no uncovered argument");
4278 return FirstUncoveredArg;
4279 }
4280
4281 void setAllCovered() {
4282 // A string has been found with all arguments covered, so clear out
4283 // the diagnostics.
4284 DiagnosticExprs.clear();
4285 FirstUncoveredArg = AllCovered;
4286 }
4287
4288 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4289 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4290
4291 // Don't update if a previous string covers all arguments.
4292 if (FirstUncoveredArg == AllCovered)
4293 return;
4294
4295 // UncoveredArgHandler tracks the highest uncovered argument index
4296 // and with it all the strings that match this index.
4297 if (NewFirstUncoveredArg == FirstUncoveredArg)
4298 DiagnosticExprs.push_back(StrExpr);
4299 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4300 DiagnosticExprs.clear();
4301 DiagnosticExprs.push_back(StrExpr);
4302 FirstUncoveredArg = NewFirstUncoveredArg;
4303 }
4304 }
4305
4306 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4307};
4308
Richard Smithd7293d72013-08-05 18:49:43 +00004309enum StringLiteralCheckType {
4310 SLCT_NotALiteral,
4311 SLCT_UncheckedLiteral,
4312 SLCT_CheckedLiteral
4313};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004314} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004315
Stephen Hines648c3692016-09-16 01:07:04 +00004316static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4317 BinaryOperatorKind BinOpKind,
4318 bool AddendIsRight) {
4319 unsigned BitWidth = Offset.getBitWidth();
4320 unsigned AddendBitWidth = Addend.getBitWidth();
4321 // There might be negative interim results.
4322 if (Addend.isUnsigned()) {
4323 Addend = Addend.zext(++AddendBitWidth);
4324 Addend.setIsSigned(true);
4325 }
4326 // Adjust the bit width of the APSInts.
4327 if (AddendBitWidth > BitWidth) {
4328 Offset = Offset.sext(AddendBitWidth);
4329 BitWidth = AddendBitWidth;
4330 } else if (BitWidth > AddendBitWidth) {
4331 Addend = Addend.sext(BitWidth);
4332 }
4333
4334 bool Ov = false;
4335 llvm::APSInt ResOffset = Offset;
4336 if (BinOpKind == BO_Add)
4337 ResOffset = Offset.sadd_ov(Addend, Ov);
4338 else {
4339 assert(AddendIsRight && BinOpKind == BO_Sub &&
4340 "operator must be add or sub with addend on the right");
4341 ResOffset = Offset.ssub_ov(Addend, Ov);
4342 }
4343
4344 // We add an offset to a pointer here so we should support an offset as big as
4345 // possible.
4346 if (Ov) {
4347 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004348 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004349 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4350 return;
4351 }
4352
4353 Offset = ResOffset;
4354}
4355
4356namespace {
4357// This is a wrapper class around StringLiteral to support offsetted string
4358// literals as format strings. It takes the offset into account when returning
4359// the string and its length or the source locations to display notes correctly.
4360class FormatStringLiteral {
4361 const StringLiteral *FExpr;
4362 int64_t Offset;
4363
4364 public:
4365 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4366 : FExpr(fexpr), Offset(Offset) {}
4367
4368 StringRef getString() const {
4369 return FExpr->getString().drop_front(Offset);
4370 }
4371
4372 unsigned getByteLength() const {
4373 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4374 }
4375 unsigned getLength() const { return FExpr->getLength() - Offset; }
4376 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4377
4378 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4379
4380 QualType getType() const { return FExpr->getType(); }
4381
4382 bool isAscii() const { return FExpr->isAscii(); }
4383 bool isWide() const { return FExpr->isWide(); }
4384 bool isUTF8() const { return FExpr->isUTF8(); }
4385 bool isUTF16() const { return FExpr->isUTF16(); }
4386 bool isUTF32() const { return FExpr->isUTF32(); }
4387 bool isPascal() const { return FExpr->isPascal(); }
4388
4389 SourceLocation getLocationOfByte(
4390 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4391 const TargetInfo &Target, unsigned *StartToken = nullptr,
4392 unsigned *StartTokenByteOffset = nullptr) const {
4393 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4394 StartToken, StartTokenByteOffset);
4395 }
4396
4397 SourceLocation getLocStart() const LLVM_READONLY {
4398 return FExpr->getLocStart().getLocWithOffset(Offset);
4399 }
4400 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4401};
4402} // end anonymous namespace
4403
4404static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004405 const Expr *OrigFormatExpr,
4406 ArrayRef<const Expr *> Args,
4407 bool HasVAListArg, unsigned format_idx,
4408 unsigned firstDataArg,
4409 Sema::FormatStringType Type,
4410 bool inFunctionCall,
4411 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004412 llvm::SmallBitVector &CheckedVarArgs,
4413 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004414
Richard Smith55ce3522012-06-25 20:30:08 +00004415// Determine if an expression is a string literal or constant string.
4416// If this function returns false on the arguments to a function expecting a
4417// format string, we will usually need to emit a warning.
4418// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004419static StringLiteralCheckType
4420checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4421 bool HasVAListArg, unsigned format_idx,
4422 unsigned firstDataArg, Sema::FormatStringType Type,
4423 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004424 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004425 UncoveredArgHandler &UncoveredArg,
4426 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004427 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004428 assert(Offset.isSigned() && "invalid offset");
4429
Douglas Gregorc25f7662009-05-19 22:10:17 +00004430 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004431 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004432
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004433 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004434
Richard Smithd7293d72013-08-05 18:49:43 +00004435 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004436 // Technically -Wformat-nonliteral does not warn about this case.
4437 // The behavior of printf and friends in this case is implementation
4438 // dependent. Ideally if the format string cannot be null then
4439 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004440 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004441
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004442 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004443 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004444 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004445 // The expression is a literal if both sub-expressions were, and it was
4446 // completely checked only if both sub-expressions were checked.
4447 const AbstractConditionalOperator *C =
4448 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004449
4450 // Determine whether it is necessary to check both sub-expressions, for
4451 // example, because the condition expression is a constant that can be
4452 // evaluated at compile time.
4453 bool CheckLeft = true, CheckRight = true;
4454
4455 bool Cond;
4456 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4457 if (Cond)
4458 CheckRight = false;
4459 else
4460 CheckLeft = false;
4461 }
4462
Stephen Hines648c3692016-09-16 01:07:04 +00004463 // We need to maintain the offsets for the right and the left hand side
4464 // separately to check if every possible indexed expression is a valid
4465 // string literal. They might have different offsets for different string
4466 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004467 StringLiteralCheckType Left;
4468 if (!CheckLeft)
4469 Left = SLCT_UncheckedLiteral;
4470 else {
4471 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4472 HasVAListArg, format_idx, firstDataArg,
4473 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004474 CheckedVarArgs, UncoveredArg, Offset);
4475 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004476 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004477 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004478 }
4479
Richard Smith55ce3522012-06-25 20:30:08 +00004480 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004481 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004482 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004483 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004484 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004485
4486 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004487 }
4488
4489 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004490 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4491 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004492 }
4493
John McCallc07a0c72011-02-17 10:25:35 +00004494 case Stmt::OpaqueValueExprClass:
4495 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4496 E = src;
4497 goto tryAgain;
4498 }
Richard Smith55ce3522012-06-25 20:30:08 +00004499 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004500
Ted Kremeneka8890832011-02-24 23:03:04 +00004501 case Stmt::PredefinedExprClass:
4502 // While __func__, etc., are technically not string literals, they
4503 // cannot contain format specifiers and thus are not a security
4504 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004505 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004506
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004507 case Stmt::DeclRefExprClass: {
4508 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004509
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004510 // As an exception, do not flag errors for variables binding to
4511 // const string literals.
4512 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4513 bool isConstant = false;
4514 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004515
Richard Smithd7293d72013-08-05 18:49:43 +00004516 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4517 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004518 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004519 isConstant = T.isConstant(S.Context) &&
4520 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004521 } else if (T->isObjCObjectPointerType()) {
4522 // In ObjC, there is usually no "const ObjectPointer" type,
4523 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004524 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004527 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004528 if (const Expr *Init = VD->getAnyInitializer()) {
4529 // Look through initializers like const char c[] = { "foo" }
4530 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4531 if (InitList->isStringLiteralInit())
4532 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4533 }
Richard Smithd7293d72013-08-05 18:49:43 +00004534 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004535 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004536 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004537 /*InFunctionCall*/ false, CheckedVarArgs,
4538 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004539 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004540 }
Mike Stump11289f42009-09-09 15:08:12 +00004541
Anders Carlssonb012ca92009-06-28 19:55:58 +00004542 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4543 // special check to see if the format string is a function parameter
4544 // of the function calling the printf function. If the function
4545 // has an attribute indicating it is a printf-like function, then we
4546 // should suppress warnings concerning non-literals being used in a call
4547 // to a vprintf function. For example:
4548 //
4549 // void
4550 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4551 // va_list ap;
4552 // va_start(ap, fmt);
4553 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4554 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004555 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004556 if (HasVAListArg) {
4557 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4558 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4559 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004560 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004561 // adjust for implicit parameter
4562 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4563 if (MD->isInstance())
4564 ++PVIndex;
4565 // We also check if the formats are compatible.
4566 // We can't pass a 'scanf' string to a 'printf' function.
4567 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004568 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004569 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004570 }
4571 }
4572 }
4573 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004574 }
Mike Stump11289f42009-09-09 15:08:12 +00004575
Richard Smith55ce3522012-06-25 20:30:08 +00004576 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004577 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004578
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004579 case Stmt::CallExprClass:
4580 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004581 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004582 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4583 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4584 unsigned ArgIndex = FA->getFormatIdx();
4585 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4586 if (MD->isInstance())
4587 --ArgIndex;
4588 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004589
Richard Smithd7293d72013-08-05 18:49:43 +00004590 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004591 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004592 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004593 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004594 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4595 unsigned BuiltinID = FD->getBuiltinID();
4596 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4597 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4598 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004599 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004600 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004601 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004602 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004603 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004604 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004605 }
4606 }
Mike Stump11289f42009-09-09 15:08:12 +00004607
Richard Smith55ce3522012-06-25 20:30:08 +00004608 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004609 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004610 case Stmt::ObjCMessageExprClass: {
4611 const auto *ME = cast<ObjCMessageExpr>(E);
4612 if (const auto *ND = ME->getMethodDecl()) {
4613 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4614 unsigned ArgIndex = FA->getFormatIdx();
4615 const Expr *Arg = ME->getArg(ArgIndex - 1);
4616 return checkFormatStringExpr(
4617 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4618 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4619 }
4620 }
4621
4622 return SLCT_NotALiteral;
4623 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004624 case Stmt::ObjCStringLiteralClass:
4625 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004626 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004627
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004628 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004629 StrE = ObjCFExpr->getString();
4630 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004631 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004632
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004633 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004634 if (Offset.isNegative() || Offset > StrE->getLength()) {
4635 // TODO: It would be better to have an explicit warning for out of
4636 // bounds literals.
4637 return SLCT_NotALiteral;
4638 }
4639 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4640 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004641 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004642 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004643 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004644 }
Mike Stump11289f42009-09-09 15:08:12 +00004645
Richard Smith55ce3522012-06-25 20:30:08 +00004646 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004647 }
Stephen Hines648c3692016-09-16 01:07:04 +00004648 case Stmt::BinaryOperatorClass: {
4649 llvm::APSInt LResult;
4650 llvm::APSInt RResult;
4651
4652 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4653
4654 // A string literal + an int offset is still a string literal.
4655 if (BinOp->isAdditiveOp()) {
4656 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4657 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4658
4659 if (LIsInt != RIsInt) {
4660 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4661
4662 if (LIsInt) {
4663 if (BinOpKind == BO_Add) {
4664 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4665 E = BinOp->getRHS();
4666 goto tryAgain;
4667 }
4668 } else {
4669 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4670 E = BinOp->getLHS();
4671 goto tryAgain;
4672 }
4673 }
Stephen Hines648c3692016-09-16 01:07:04 +00004674 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004675
4676 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004677 }
4678 case Stmt::UnaryOperatorClass: {
4679 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4680 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4681 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4682 llvm::APSInt IndexResult;
4683 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4684 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4685 E = ASE->getBase();
4686 goto tryAgain;
4687 }
4688 }
4689
4690 return SLCT_NotALiteral;
4691 }
Mike Stump11289f42009-09-09 15:08:12 +00004692
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004693 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004694 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004695 }
4696}
4697
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004698Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004699 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004700 .Case("scanf", FST_Scanf)
4701 .Cases("printf", "printf0", FST_Printf)
4702 .Cases("NSString", "CFString", FST_NSString)
4703 .Case("strftime", FST_Strftime)
4704 .Case("strfmon", FST_Strfmon)
4705 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4706 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4707 .Case("os_trace", FST_OSLog)
4708 .Case("os_log", FST_OSLog)
4709 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004710}
4711
Jordan Rose3e0ec582012-07-19 18:10:23 +00004712/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004713/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004714/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004715bool Sema::CheckFormatArguments(const FormatAttr *Format,
4716 ArrayRef<const Expr *> Args,
4717 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004718 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004719 SourceLocation Loc, SourceRange Range,
4720 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004721 FormatStringInfo FSI;
4722 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004723 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004724 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004725 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004726 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004727}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004728
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004729bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004730 bool HasVAListArg, unsigned format_idx,
4731 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004732 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004733 SourceLocation Loc, SourceRange Range,
4734 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004735 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004736 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004737 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004738 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004741 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004742
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004743 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004744 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004745 // Dynamically generated format strings are difficult to
4746 // automatically vet at compile time. Requiring that format strings
4747 // are string literals: (1) permits the checking of format strings by
4748 // the compiler and thereby (2) can practically remove the source of
4749 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004750
Mike Stump11289f42009-09-09 15:08:12 +00004751 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004752 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004753 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004754 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004755 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004756 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004757 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4758 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004759 /*IsFunctionCall*/ true, CheckedVarArgs,
4760 UncoveredArg,
4761 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004762
4763 // Generate a diagnostic where an uncovered argument is detected.
4764 if (UncoveredArg.hasUncoveredArg()) {
4765 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4766 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4767 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4768 }
4769
Richard Smith55ce3522012-06-25 20:30:08 +00004770 if (CT != SLCT_NotALiteral)
4771 // Literal format string found, check done!
4772 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004773
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004774 // Strftime is particular as it always uses a single 'time' argument,
4775 // so it is safe to pass a non-literal string.
4776 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004777 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004778
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004779 // Do not emit diag when the string param is a macro expansion and the
4780 // format is either NSString or CFString. This is a hack to prevent
4781 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4782 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004783 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4784 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004785 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004786
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004787 // If there are no arguments specified, warn with -Wformat-security, otherwise
4788 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004789 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004790 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4791 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004792 switch (Type) {
4793 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004794 break;
4795 case FST_Kprintf:
4796 case FST_FreeBSDKPrintf:
4797 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004798 Diag(FormatLoc, diag::note_format_security_fixit)
4799 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004800 break;
4801 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004802 Diag(FormatLoc, diag::note_format_security_fixit)
4803 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004804 break;
4805 }
4806 } else {
4807 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004808 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004809 }
Richard Smith55ce3522012-06-25 20:30:08 +00004810 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004811}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004812
Ted Kremenekab278de2010-01-28 23:39:18 +00004813namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004814class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4815protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004816 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004817 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004818 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004819 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004820 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004821 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004822 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004823 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004824 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004825 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004826 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004827 bool usesPositionalArgs;
4828 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004829 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004830 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004831 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004832 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004833
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004834public:
Stephen Hines648c3692016-09-16 01:07:04 +00004835 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004836 const Expr *origFormatExpr,
4837 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004838 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004839 ArrayRef<const Expr *> Args, unsigned formatIdx,
4840 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004841 llvm::SmallBitVector &CheckedVarArgs,
4842 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004843 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4844 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4845 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4846 usesPositionalArgs(false), atFirstArg(true),
4847 inFunctionCall(inFunctionCall), CallType(callType),
4848 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004849 CoveredArgs.resize(numDataArgs);
4850 CoveredArgs.reset();
4851 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004852
Ted Kremenek019d2242010-01-29 01:50:07 +00004853 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004854
Ted Kremenek02087932010-07-16 02:11:22 +00004855 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004856 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004857
Jordan Rose92303592012-09-08 04:00:03 +00004858 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004859 const analyze_format_string::FormatSpecifier &FS,
4860 const analyze_format_string::ConversionSpecifier &CS,
4861 const char *startSpecifier, unsigned specifierLen,
4862 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004863
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004864 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004865 const analyze_format_string::FormatSpecifier &FS,
4866 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004867
4868 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004869 const analyze_format_string::ConversionSpecifier &CS,
4870 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004871
Craig Toppere14c0f82014-03-12 04:55:44 +00004872 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004873
Craig Toppere14c0f82014-03-12 04:55:44 +00004874 void HandleInvalidPosition(const char *startSpecifier,
4875 unsigned specifierLen,
4876 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004877
Craig Toppere14c0f82014-03-12 04:55:44 +00004878 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004879
Craig Toppere14c0f82014-03-12 04:55:44 +00004880 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004881
Richard Trieu03cf7b72011-10-28 00:41:25 +00004882 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004883 static void
4884 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4885 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4886 bool IsStringLocation, Range StringRange,
4887 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004888
Ted Kremenek02087932010-07-16 02:11:22 +00004889protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004890 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4891 const char *startSpec,
4892 unsigned specifierLen,
4893 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004894
4895 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4896 const char *startSpec,
4897 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004898
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004899 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004900 CharSourceRange getSpecifierRange(const char *startSpecifier,
4901 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004902 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004903
Ted Kremenek5739de72010-01-29 01:06:55 +00004904 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004905
4906 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4907 const analyze_format_string::ConversionSpecifier &CS,
4908 const char *startSpecifier, unsigned specifierLen,
4909 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004910
4911 template <typename Range>
4912 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4913 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004914 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004915};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004916} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004917
Ted Kremenek02087932010-07-16 02:11:22 +00004918SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004919 return OrigFormatExpr->getSourceRange();
4920}
4921
Ted Kremenek02087932010-07-16 02:11:22 +00004922CharSourceRange CheckFormatHandler::
4923getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004924 SourceLocation Start = getLocationOfByte(startSpecifier);
4925 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4926
4927 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004928 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004929
4930 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004931}
4932
Ted Kremenek02087932010-07-16 02:11:22 +00004933SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004934 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4935 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004936}
4937
Ted Kremenek02087932010-07-16 02:11:22 +00004938void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4939 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004940 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4941 getLocationOfByte(startSpecifier),
4942 /*IsStringLocation*/true,
4943 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004944}
4945
Jordan Rose92303592012-09-08 04:00:03 +00004946void CheckFormatHandler::HandleInvalidLengthModifier(
4947 const analyze_format_string::FormatSpecifier &FS,
4948 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004949 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004950 using namespace analyze_format_string;
4951
4952 const LengthModifier &LM = FS.getLengthModifier();
4953 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4954
4955 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004956 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004957 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004958 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004959 getLocationOfByte(LM.getStart()),
4960 /*IsStringLocation*/true,
4961 getSpecifierRange(startSpecifier, specifierLen));
4962
4963 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4964 << FixedLM->toString()
4965 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4966
4967 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004968 FixItHint Hint;
4969 if (DiagID == diag::warn_format_nonsensical_length)
4970 Hint = FixItHint::CreateRemoval(LMRange);
4971
4972 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004973 getLocationOfByte(LM.getStart()),
4974 /*IsStringLocation*/true,
4975 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004976 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004977 }
4978}
4979
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004980void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004981 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004982 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004983 using namespace analyze_format_string;
4984
4985 const LengthModifier &LM = FS.getLengthModifier();
4986 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4987
4988 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004989 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004990 if (FixedLM) {
4991 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4992 << LM.toString() << 0,
4993 getLocationOfByte(LM.getStart()),
4994 /*IsStringLocation*/true,
4995 getSpecifierRange(startSpecifier, specifierLen));
4996
4997 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4998 << FixedLM->toString()
4999 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5000
5001 } else {
5002 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5003 << LM.toString() << 0,
5004 getLocationOfByte(LM.getStart()),
5005 /*IsStringLocation*/true,
5006 getSpecifierRange(startSpecifier, specifierLen));
5007 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005008}
5009
5010void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5011 const analyze_format_string::ConversionSpecifier &CS,
5012 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005013 using namespace analyze_format_string;
5014
5015 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005016 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005017 if (FixedCS) {
5018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5019 << CS.toString() << /*conversion specifier*/1,
5020 getLocationOfByte(CS.getStart()),
5021 /*IsStringLocation*/true,
5022 getSpecifierRange(startSpecifier, specifierLen));
5023
5024 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5025 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5026 << FixedCS->toString()
5027 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5028 } else {
5029 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5030 << CS.toString() << /*conversion specifier*/1,
5031 getLocationOfByte(CS.getStart()),
5032 /*IsStringLocation*/true,
5033 getSpecifierRange(startSpecifier, specifierLen));
5034 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005035}
5036
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005037void CheckFormatHandler::HandlePosition(const char *startPos,
5038 unsigned posLen) {
5039 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5040 getLocationOfByte(startPos),
5041 /*IsStringLocation*/true,
5042 getSpecifierRange(startPos, posLen));
5043}
5044
Ted Kremenekd1668192010-02-27 01:41:03 +00005045void
Ted Kremenek02087932010-07-16 02:11:22 +00005046CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5047 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005048 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5049 << (unsigned) p,
5050 getLocationOfByte(startPos), /*IsStringLocation*/true,
5051 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005052}
5053
Ted Kremenek02087932010-07-16 02:11:22 +00005054void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005055 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005056 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5057 getLocationOfByte(startPos),
5058 /*IsStringLocation*/true,
5059 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005060}
5061
Ted Kremenek02087932010-07-16 02:11:22 +00005062void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005063 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005064 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005065 EmitFormatDiagnostic(
5066 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5067 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5068 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005069 }
Ted Kremenek02087932010-07-16 02:11:22 +00005070}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005071
Jordan Rose58bbe422012-07-19 18:10:08 +00005072// Note that this may return NULL if there was an error parsing or building
5073// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005074const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005075 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005076}
5077
5078void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005079 // Does the number of data arguments exceed the number of
5080 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005081 if (!HasVAListArg) {
5082 // Find any arguments that weren't covered.
5083 CoveredArgs.flip();
5084 signed notCoveredArg = CoveredArgs.find_first();
5085 if (notCoveredArg >= 0) {
5086 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005087 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5088 } else {
5089 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005090 }
5091 }
5092}
5093
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005094void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5095 const Expr *ArgExpr) {
5096 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5097 "Invalid state");
5098
5099 if (!ArgExpr)
5100 return;
5101
5102 SourceLocation Loc = ArgExpr->getLocStart();
5103
5104 if (S.getSourceManager().isInSystemMacro(Loc))
5105 return;
5106
5107 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5108 for (auto E : DiagnosticExprs)
5109 PDiag << E->getSourceRange();
5110
5111 CheckFormatHandler::EmitFormatDiagnostic(
5112 S, IsFunctionCall, DiagnosticExprs[0],
5113 PDiag, Loc, /*IsStringLocation*/false,
5114 DiagnosticExprs[0]->getSourceRange());
5115}
5116
Ted Kremenekce815422010-07-19 21:25:57 +00005117bool
5118CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5119 SourceLocation Loc,
5120 const char *startSpec,
5121 unsigned specifierLen,
5122 const char *csStart,
5123 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005124 bool keepGoing = true;
5125 if (argIndex < NumDataArgs) {
5126 // Consider the argument coverered, even though the specifier doesn't
5127 // make sense.
5128 CoveredArgs.set(argIndex);
5129 }
5130 else {
5131 // If argIndex exceeds the number of data arguments we
5132 // don't issue a warning because that is just a cascade of warnings (and
5133 // they may have intended '%%' anyway). We don't want to continue processing
5134 // the format string after this point, however, as we will like just get
5135 // gibberish when trying to match arguments.
5136 keepGoing = false;
5137 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005138
5139 StringRef Specifier(csStart, csLen);
5140
5141 // If the specifier in non-printable, it could be the first byte of a UTF-8
5142 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5143 // hex value.
5144 std::string CodePointStr;
5145 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005146 llvm::UTF32 CodePoint;
5147 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5148 const llvm::UTF8 *E =
5149 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5150 llvm::ConversionResult Result =
5151 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005152
Justin Lebar90910552016-09-30 00:38:45 +00005153 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005154 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005155 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005156 }
5157
5158 llvm::raw_string_ostream OS(CodePointStr);
5159 if (CodePoint < 256)
5160 OS << "\\x" << llvm::format("%02x", CodePoint);
5161 else if (CodePoint <= 0xFFFF)
5162 OS << "\\u" << llvm::format("%04x", CodePoint);
5163 else
5164 OS << "\\U" << llvm::format("%08x", CodePoint);
5165 OS.flush();
5166 Specifier = CodePointStr;
5167 }
5168
5169 EmitFormatDiagnostic(
5170 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5171 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5172
Ted Kremenekce815422010-07-19 21:25:57 +00005173 return keepGoing;
5174}
5175
Richard Trieu03cf7b72011-10-28 00:41:25 +00005176void
5177CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5178 const char *startSpec,
5179 unsigned specifierLen) {
5180 EmitFormatDiagnostic(
5181 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5182 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5183}
5184
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005185bool
5186CheckFormatHandler::CheckNumArgs(
5187 const analyze_format_string::FormatSpecifier &FS,
5188 const analyze_format_string::ConversionSpecifier &CS,
5189 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5190
5191 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005192 PartialDiagnostic PDiag = FS.usesPositionalArg()
5193 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5194 << (argIndex+1) << NumDataArgs)
5195 : S.PDiag(diag::warn_printf_insufficient_data_args);
5196 EmitFormatDiagnostic(
5197 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5198 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005199
5200 // Since more arguments than conversion tokens are given, by extension
5201 // all arguments are covered, so mark this as so.
5202 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005203 return false;
5204 }
5205 return true;
5206}
5207
Richard Trieu03cf7b72011-10-28 00:41:25 +00005208template<typename Range>
5209void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5210 SourceLocation Loc,
5211 bool IsStringLocation,
5212 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005213 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005214 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005215 Loc, IsStringLocation, StringRange, FixIt);
5216}
5217
5218/// \brief If the format string is not within the funcion call, emit a note
5219/// so that the function call and string are in diagnostic messages.
5220///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005221/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005222/// call and only one diagnostic message will be produced. Otherwise, an
5223/// extra note will be emitted pointing to location of the format string.
5224///
5225/// \param ArgumentExpr the expression that is passed as the format string
5226/// argument in the function call. Used for getting locations when two
5227/// diagnostics are emitted.
5228///
5229/// \param PDiag the callee should already have provided any strings for the
5230/// diagnostic message. This function only adds locations and fixits
5231/// to diagnostics.
5232///
5233/// \param Loc primary location for diagnostic. If two diagnostics are
5234/// required, one will be at Loc and a new SourceLocation will be created for
5235/// the other one.
5236///
5237/// \param IsStringLocation if true, Loc points to the format string should be
5238/// used for the note. Otherwise, Loc points to the argument list and will
5239/// be used with PDiag.
5240///
5241/// \param StringRange some or all of the string to highlight. This is
5242/// templated so it can accept either a CharSourceRange or a SourceRange.
5243///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005244/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005245template <typename Range>
5246void CheckFormatHandler::EmitFormatDiagnostic(
5247 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5248 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5249 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005250 if (InFunctionCall) {
5251 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5252 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005253 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005254 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005255 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5256 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005257
5258 const Sema::SemaDiagnosticBuilder &Note =
5259 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5260 diag::note_format_string_defined);
5261
5262 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005263 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005264 }
5265}
5266
Ted Kremenek02087932010-07-16 02:11:22 +00005267//===--- CHECK: Printf format string checking ------------------------------===//
5268
5269namespace {
5270class CheckPrintfHandler : public CheckFormatHandler {
5271public:
Stephen Hines648c3692016-09-16 01:07:04 +00005272 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005273 const Expr *origFormatExpr,
5274 const Sema::FormatStringType type, unsigned firstDataArg,
5275 unsigned numDataArgs, bool isObjC, const char *beg,
5276 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005277 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005278 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005279 llvm::SmallBitVector &CheckedVarArgs,
5280 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005281 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5282 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5283 inFunctionCall, CallType, CheckedVarArgs,
5284 UncoveredArg) {}
5285
5286 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5287
5288 /// Returns true if '%@' specifiers are allowed in the format string.
5289 bool allowsObjCArg() const {
5290 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5291 FSType == Sema::FST_OSTrace;
5292 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005293
Ted Kremenek02087932010-07-16 02:11:22 +00005294 bool HandleInvalidPrintfConversionSpecifier(
5295 const analyze_printf::PrintfSpecifier &FS,
5296 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005297 unsigned specifierLen) override;
5298
Ted Kremenek02087932010-07-16 02:11:22 +00005299 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5300 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005301 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005302 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5303 const char *StartSpecifier,
5304 unsigned SpecifierLen,
5305 const Expr *E);
5306
Ted Kremenek02087932010-07-16 02:11:22 +00005307 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5308 const char *startSpecifier, unsigned specifierLen);
5309 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5310 const analyze_printf::OptionalAmount &Amt,
5311 unsigned type,
5312 const char *startSpecifier, unsigned specifierLen);
5313 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5314 const analyze_printf::OptionalFlag &flag,
5315 const char *startSpecifier, unsigned specifierLen);
5316 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5317 const analyze_printf::OptionalFlag &ignoredFlag,
5318 const analyze_printf::OptionalFlag &flag,
5319 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005320 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005321 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005322
5323 void HandleEmptyObjCModifierFlag(const char *startFlag,
5324 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005325
Ted Kremenek2b417712015-07-02 05:39:16 +00005326 void HandleInvalidObjCModifierFlag(const char *startFlag,
5327 unsigned flagLen) override;
5328
5329 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5330 const char *flagsEnd,
5331 const char *conversionPosition)
5332 override;
5333};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005334} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005335
5336bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5337 const analyze_printf::PrintfSpecifier &FS,
5338 const char *startSpecifier,
5339 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005340 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005341 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005342
Ted Kremenekce815422010-07-19 21:25:57 +00005343 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5344 getLocationOfByte(CS.getStart()),
5345 startSpecifier, specifierLen,
5346 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005347}
5348
Ted Kremenek02087932010-07-16 02:11:22 +00005349bool CheckPrintfHandler::HandleAmount(
5350 const analyze_format_string::OptionalAmount &Amt,
5351 unsigned k, const char *startSpecifier,
5352 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005353 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005354 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005355 unsigned argIndex = Amt.getArgIndex();
5356 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5358 << k,
5359 getLocationOfByte(Amt.getStart()),
5360 /*IsStringLocation*/true,
5361 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005362 // Don't do any more checking. We will just emit
5363 // spurious errors.
5364 return false;
5365 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005366
Ted Kremenek5739de72010-01-29 01:06:55 +00005367 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005368 // Although not in conformance with C99, we also allow the argument to be
5369 // an 'unsigned int' as that is a reasonably safe case. GCC also
5370 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005371 CoveredArgs.set(argIndex);
5372 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005373 if (!Arg)
5374 return false;
5375
Ted Kremenek5739de72010-01-29 01:06:55 +00005376 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005377
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005378 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5379 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005380
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005381 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005382 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005383 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005384 << T << Arg->getSourceRange(),
5385 getLocationOfByte(Amt.getStart()),
5386 /*IsStringLocation*/true,
5387 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005388 // Don't do any more checking. We will just emit
5389 // spurious errors.
5390 return false;
5391 }
5392 }
5393 }
5394 return true;
5395}
Ted Kremenek5739de72010-01-29 01:06:55 +00005396
Tom Careb49ec692010-06-17 19:00:27 +00005397void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005398 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005399 const analyze_printf::OptionalAmount &Amt,
5400 unsigned type,
5401 const char *startSpecifier,
5402 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005403 const analyze_printf::PrintfConversionSpecifier &CS =
5404 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005405
Richard Trieu03cf7b72011-10-28 00:41:25 +00005406 FixItHint fixit =
5407 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5408 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5409 Amt.getConstantLength()))
5410 : FixItHint();
5411
5412 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5413 << type << CS.toString(),
5414 getLocationOfByte(Amt.getStart()),
5415 /*IsStringLocation*/true,
5416 getSpecifierRange(startSpecifier, specifierLen),
5417 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005418}
5419
Ted Kremenek02087932010-07-16 02:11:22 +00005420void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005421 const analyze_printf::OptionalFlag &flag,
5422 const char *startSpecifier,
5423 unsigned specifierLen) {
5424 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005425 const analyze_printf::PrintfConversionSpecifier &CS =
5426 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005427 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5428 << flag.toString() << CS.toString(),
5429 getLocationOfByte(flag.getPosition()),
5430 /*IsStringLocation*/true,
5431 getSpecifierRange(startSpecifier, specifierLen),
5432 FixItHint::CreateRemoval(
5433 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005434}
5435
5436void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005437 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005438 const analyze_printf::OptionalFlag &ignoredFlag,
5439 const analyze_printf::OptionalFlag &flag,
5440 const char *startSpecifier,
5441 unsigned specifierLen) {
5442 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005443 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5444 << ignoredFlag.toString() << flag.toString(),
5445 getLocationOfByte(ignoredFlag.getPosition()),
5446 /*IsStringLocation*/true,
5447 getSpecifierRange(startSpecifier, specifierLen),
5448 FixItHint::CreateRemoval(
5449 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005450}
5451
Ted Kremenek2b417712015-07-02 05:39:16 +00005452// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5453// bool IsStringLocation, Range StringRange,
5454// ArrayRef<FixItHint> Fixit = None);
5455
5456void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5457 unsigned flagLen) {
5458 // Warn about an empty flag.
5459 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5460 getLocationOfByte(startFlag),
5461 /*IsStringLocation*/true,
5462 getSpecifierRange(startFlag, flagLen));
5463}
5464
5465void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5466 unsigned flagLen) {
5467 // Warn about an invalid flag.
5468 auto Range = getSpecifierRange(startFlag, flagLen);
5469 StringRef flag(startFlag, flagLen);
5470 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5471 getLocationOfByte(startFlag),
5472 /*IsStringLocation*/true,
5473 Range, FixItHint::CreateRemoval(Range));
5474}
5475
5476void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5477 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5478 // Warn about using '[...]' without a '@' conversion.
5479 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5480 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5481 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5482 getLocationOfByte(conversionPosition),
5483 /*IsStringLocation*/true,
5484 Range, FixItHint::CreateRemoval(Range));
5485}
5486
Richard Smith55ce3522012-06-25 20:30:08 +00005487// Determines if the specified is a C++ class or struct containing
5488// a member with the specified name and kind (e.g. a CXXMethodDecl named
5489// "c_str()").
5490template<typename MemberKind>
5491static llvm::SmallPtrSet<MemberKind*, 1>
5492CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5493 const RecordType *RT = Ty->getAs<RecordType>();
5494 llvm::SmallPtrSet<MemberKind*, 1> Results;
5495
5496 if (!RT)
5497 return Results;
5498 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005499 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005500 return Results;
5501
Alp Tokerb6cc5922014-05-03 03:45:55 +00005502 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005503 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005504 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005505
5506 // We just need to include all members of the right kind turned up by the
5507 // filter, at this point.
5508 if (S.LookupQualifiedName(R, RT->getDecl()))
5509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5510 NamedDecl *decl = (*I)->getUnderlyingDecl();
5511 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5512 Results.insert(FK);
5513 }
5514 return Results;
5515}
5516
Richard Smith2868a732014-02-28 01:36:39 +00005517/// Check if we could call '.c_str()' on an object.
5518///
5519/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5520/// allow the call, or if it would be ambiguous).
5521bool Sema::hasCStrMethod(const Expr *E) {
5522 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5523 MethodSet Results =
5524 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5525 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5526 MI != ME; ++MI)
5527 if ((*MI)->getMinRequiredArguments() == 0)
5528 return true;
5529 return false;
5530}
5531
Richard Smith55ce3522012-06-25 20:30:08 +00005532// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005533// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005534// Returns true when a c_str() conversion method is found.
5535bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005536 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005537 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5538
5539 MethodSet Results =
5540 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5541
5542 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5543 MI != ME; ++MI) {
5544 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005545 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005546 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005547 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005548 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005549 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5550 << "c_str()"
5551 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5552 return true;
5553 }
5554 }
5555
5556 return false;
5557}
5558
Ted Kremenekab278de2010-01-28 23:39:18 +00005559bool
Ted Kremenek02087932010-07-16 02:11:22 +00005560CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005561 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005562 const char *startSpecifier,
5563 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005564 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005565 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005566 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005567
Ted Kremenek6cd69422010-07-19 22:01:06 +00005568 if (FS.consumesDataArgument()) {
5569 if (atFirstArg) {
5570 atFirstArg = false;
5571 usesPositionalArgs = FS.usesPositionalArg();
5572 }
5573 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005574 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5575 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005576 return false;
5577 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005578 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005579
Ted Kremenekd1668192010-02-27 01:41:03 +00005580 // First check if the field width, precision, and conversion specifier
5581 // have matching data arguments.
5582 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5583 startSpecifier, specifierLen)) {
5584 return false;
5585 }
5586
5587 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5588 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005589 return false;
5590 }
5591
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005592 if (!CS.consumesDataArgument()) {
5593 // FIXME: Technically specifying a precision or field width here
5594 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005595 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005596 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005597
Ted Kremenek4a49d982010-02-26 19:18:41 +00005598 // Consume the argument.
5599 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005600 if (argIndex < NumDataArgs) {
5601 // The check to see if the argIndex is valid will come later.
5602 // We set the bit here because we may exit early from this
5603 // function if we encounter some other error.
5604 CoveredArgs.set(argIndex);
5605 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005606
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005607 // FreeBSD kernel extensions.
5608 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5609 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5610 // We need at least two arguments.
5611 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5612 return false;
5613
5614 // Claim the second argument.
5615 CoveredArgs.set(argIndex + 1);
5616
5617 // Type check the first argument (int for %b, pointer for %D)
5618 const Expr *Ex = getDataArg(argIndex);
5619 const analyze_printf::ArgType &AT =
5620 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5621 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5622 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5623 EmitFormatDiagnostic(
5624 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5625 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5626 << false << Ex->getSourceRange(),
5627 Ex->getLocStart(), /*IsStringLocation*/false,
5628 getSpecifierRange(startSpecifier, specifierLen));
5629
5630 // Type check the second argument (char * for both %b and %D)
5631 Ex = getDataArg(argIndex + 1);
5632 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5633 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5634 EmitFormatDiagnostic(
5635 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5636 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5637 << false << Ex->getSourceRange(),
5638 Ex->getLocStart(), /*IsStringLocation*/false,
5639 getSpecifierRange(startSpecifier, specifierLen));
5640
5641 return true;
5642 }
5643
Ted Kremenek4a49d982010-02-26 19:18:41 +00005644 // Check for using an Objective-C specific conversion specifier
5645 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005646 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005647 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5648 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005649 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005650
Mehdi Amini06d367c2016-10-24 20:39:34 +00005651 // %P can only be used with os_log.
5652 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5653 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5654 specifierLen);
5655 }
5656
5657 // %n is not allowed with os_log.
5658 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5659 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5660 getLocationOfByte(CS.getStart()),
5661 /*IsStringLocation*/ false,
5662 getSpecifierRange(startSpecifier, specifierLen));
5663
5664 return true;
5665 }
5666
5667 // Only scalars are allowed for os_trace.
5668 if (FSType == Sema::FST_OSTrace &&
5669 (CS.getKind() == ConversionSpecifier::PArg ||
5670 CS.getKind() == ConversionSpecifier::sArg ||
5671 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5672 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5673 specifierLen);
5674 }
5675
5676 // Check for use of public/private annotation outside of os_log().
5677 if (FSType != Sema::FST_OSLog) {
5678 if (FS.isPublic().isSet()) {
5679 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5680 << "public",
5681 getLocationOfByte(FS.isPublic().getPosition()),
5682 /*IsStringLocation*/ false,
5683 getSpecifierRange(startSpecifier, specifierLen));
5684 }
5685 if (FS.isPrivate().isSet()) {
5686 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5687 << "private",
5688 getLocationOfByte(FS.isPrivate().getPosition()),
5689 /*IsStringLocation*/ false,
5690 getSpecifierRange(startSpecifier, specifierLen));
5691 }
5692 }
5693
Tom Careb49ec692010-06-17 19:00:27 +00005694 // Check for invalid use of field width
5695 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005696 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005697 startSpecifier, specifierLen);
5698 }
5699
5700 // Check for invalid use of precision
5701 if (!FS.hasValidPrecision()) {
5702 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5703 startSpecifier, specifierLen);
5704 }
5705
Mehdi Amini06d367c2016-10-24 20:39:34 +00005706 // Precision is mandatory for %P specifier.
5707 if (CS.getKind() == ConversionSpecifier::PArg &&
5708 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5709 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5710 getLocationOfByte(startSpecifier),
5711 /*IsStringLocation*/ false,
5712 getSpecifierRange(startSpecifier, specifierLen));
5713 }
5714
Tom Careb49ec692010-06-17 19:00:27 +00005715 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005716 if (!FS.hasValidThousandsGroupingPrefix())
5717 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005718 if (!FS.hasValidLeadingZeros())
5719 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5720 if (!FS.hasValidPlusPrefix())
5721 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005722 if (!FS.hasValidSpacePrefix())
5723 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005724 if (!FS.hasValidAlternativeForm())
5725 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5726 if (!FS.hasValidLeftJustified())
5727 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5728
5729 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005730 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5731 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5732 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005733 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5734 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5735 startSpecifier, specifierLen);
5736
5737 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005738 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005739 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5740 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005741 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005742 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005743 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005744 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5745 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005746
Jordan Rose92303592012-09-08 04:00:03 +00005747 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5748 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5749
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005750 // The remaining checks depend on the data arguments.
5751 if (HasVAListArg)
5752 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005753
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005754 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005755 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005756
Jordan Rose58bbe422012-07-19 18:10:08 +00005757 const Expr *Arg = getDataArg(argIndex);
5758 if (!Arg)
5759 return true;
5760
5761 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005762}
5763
Jordan Roseaee34382012-09-05 22:56:26 +00005764static bool requiresParensToAddCast(const Expr *E) {
5765 // FIXME: We should have a general way to reason about operator
5766 // precedence and whether parens are actually needed here.
5767 // Take care of a few common cases where they aren't.
5768 const Expr *Inside = E->IgnoreImpCasts();
5769 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5770 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5771
5772 switch (Inside->getStmtClass()) {
5773 case Stmt::ArraySubscriptExprClass:
5774 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005775 case Stmt::CharacterLiteralClass:
5776 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005777 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005778 case Stmt::FloatingLiteralClass:
5779 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005780 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005781 case Stmt::ObjCArrayLiteralClass:
5782 case Stmt::ObjCBoolLiteralExprClass:
5783 case Stmt::ObjCBoxedExprClass:
5784 case Stmt::ObjCDictionaryLiteralClass:
5785 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005786 case Stmt::ObjCIvarRefExprClass:
5787 case Stmt::ObjCMessageExprClass:
5788 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005789 case Stmt::ObjCStringLiteralClass:
5790 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005791 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005792 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005793 case Stmt::UnaryOperatorClass:
5794 return false;
5795 default:
5796 return true;
5797 }
5798}
5799
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005800static std::pair<QualType, StringRef>
5801shouldNotPrintDirectly(const ASTContext &Context,
5802 QualType IntendedTy,
5803 const Expr *E) {
5804 // Use a 'while' to peel off layers of typedefs.
5805 QualType TyTy = IntendedTy;
5806 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5807 StringRef Name = UserTy->getDecl()->getName();
5808 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5809 .Case("NSInteger", Context.LongTy)
5810 .Case("NSUInteger", Context.UnsignedLongTy)
5811 .Case("SInt32", Context.IntTy)
5812 .Case("UInt32", Context.UnsignedIntTy)
5813 .Default(QualType());
5814
5815 if (!CastTy.isNull())
5816 return std::make_pair(CastTy, Name);
5817
5818 TyTy = UserTy->desugar();
5819 }
5820
5821 // Strip parens if necessary.
5822 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5823 return shouldNotPrintDirectly(Context,
5824 PE->getSubExpr()->getType(),
5825 PE->getSubExpr());
5826
5827 // If this is a conditional expression, then its result type is constructed
5828 // via usual arithmetic conversions and thus there might be no necessary
5829 // typedef sugar there. Recurse to operands to check for NSInteger &
5830 // Co. usage condition.
5831 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5832 QualType TrueTy, FalseTy;
5833 StringRef TrueName, FalseName;
5834
5835 std::tie(TrueTy, TrueName) =
5836 shouldNotPrintDirectly(Context,
5837 CO->getTrueExpr()->getType(),
5838 CO->getTrueExpr());
5839 std::tie(FalseTy, FalseName) =
5840 shouldNotPrintDirectly(Context,
5841 CO->getFalseExpr()->getType(),
5842 CO->getFalseExpr());
5843
5844 if (TrueTy == FalseTy)
5845 return std::make_pair(TrueTy, TrueName);
5846 else if (TrueTy.isNull())
5847 return std::make_pair(FalseTy, FalseName);
5848 else if (FalseTy.isNull())
5849 return std::make_pair(TrueTy, TrueName);
5850 }
5851
5852 return std::make_pair(QualType(), StringRef());
5853}
5854
Richard Smith55ce3522012-06-25 20:30:08 +00005855bool
5856CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5857 const char *StartSpecifier,
5858 unsigned SpecifierLen,
5859 const Expr *E) {
5860 using namespace analyze_format_string;
5861 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005862 // Now type check the data expression that matches the
5863 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005864 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005865 if (!AT.isValid())
5866 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005867
Jordan Rose598ec092012-12-05 18:44:40 +00005868 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005869 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5870 ExprTy = TET->getUnderlyingExpr()->getType();
5871 }
5872
Seth Cantrellb4802962015-03-04 03:12:10 +00005873 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5874
5875 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005876 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005877 }
Jordan Rose98709982012-06-04 22:48:57 +00005878
Jordan Rose22b74712012-09-05 22:56:19 +00005879 // Look through argument promotions for our error message's reported type.
5880 // This includes the integral and floating promotions, but excludes array
5881 // and function pointer decay; seeing that an argument intended to be a
5882 // string has type 'char [6]' is probably more confusing than 'char *'.
5883 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5884 if (ICE->getCastKind() == CK_IntegralCast ||
5885 ICE->getCastKind() == CK_FloatingCast) {
5886 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005887 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005888
5889 // Check if we didn't match because of an implicit cast from a 'char'
5890 // or 'short' to an 'int'. This is done because printf is a varargs
5891 // function.
5892 if (ICE->getType() == S.Context.IntTy ||
5893 ICE->getType() == S.Context.UnsignedIntTy) {
5894 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005895 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005896 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005897 }
Jordan Rose98709982012-06-04 22:48:57 +00005898 }
Jordan Rose598ec092012-12-05 18:44:40 +00005899 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5900 // Special case for 'a', which has type 'int' in C.
5901 // Note, however, that we do /not/ want to treat multibyte constants like
5902 // 'MooV' as characters! This form is deprecated but still exists.
5903 if (ExprTy == S.Context.IntTy)
5904 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5905 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005906 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005907
Jordan Rosebc53ed12014-05-31 04:12:14 +00005908 // Look through enums to their underlying type.
5909 bool IsEnum = false;
5910 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5911 ExprTy = EnumTy->getDecl()->getIntegerType();
5912 IsEnum = true;
5913 }
5914
Jordan Rose0e5badd2012-12-05 18:44:49 +00005915 // %C in an Objective-C context prints a unichar, not a wchar_t.
5916 // If the argument is an integer of some kind, believe the %C and suggest
5917 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005918 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005919 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005920 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5921 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5922 !ExprTy->isCharType()) {
5923 // 'unichar' is defined as a typedef of unsigned short, but we should
5924 // prefer using the typedef if it is visible.
5925 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005926
5927 // While we are here, check if the value is an IntegerLiteral that happens
5928 // to be within the valid range.
5929 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5930 const llvm::APInt &V = IL->getValue();
5931 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5932 return true;
5933 }
5934
Jordan Rose0e5badd2012-12-05 18:44:49 +00005935 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5936 Sema::LookupOrdinaryName);
5937 if (S.LookupName(Result, S.getCurScope())) {
5938 NamedDecl *ND = Result.getFoundDecl();
5939 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5940 if (TD->getUnderlyingType() == IntendedTy)
5941 IntendedTy = S.Context.getTypedefType(TD);
5942 }
5943 }
5944 }
5945
5946 // Special-case some of Darwin's platform-independence types by suggesting
5947 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005948 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005949 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005950 QualType CastTy;
5951 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5952 if (!CastTy.isNull()) {
5953 IntendedTy = CastTy;
5954 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005955 }
5956 }
5957
Jordan Rose22b74712012-09-05 22:56:19 +00005958 // We may be able to offer a FixItHint if it is a supported type.
5959 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005960 bool success =
5961 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005962
Jordan Rose22b74712012-09-05 22:56:19 +00005963 if (success) {
5964 // Get the fix string from the fixed format specifier
5965 SmallString<16> buf;
5966 llvm::raw_svector_ostream os(buf);
5967 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005968
Jordan Roseaee34382012-09-05 22:56:26 +00005969 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5970
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005971 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005972 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5973 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5974 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5975 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005976 // In this case, the specifier is wrong and should be changed to match
5977 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005978 EmitFormatDiagnostic(S.PDiag(diag)
5979 << AT.getRepresentativeTypeName(S.Context)
5980 << IntendedTy << IsEnum << E->getSourceRange(),
5981 E->getLocStart(),
5982 /*IsStringLocation*/ false, SpecRange,
5983 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005984 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005985 // The canonical type for formatting this value is different from the
5986 // actual type of the expression. (This occurs, for example, with Darwin's
5987 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5988 // should be printed as 'long' for 64-bit compatibility.)
5989 // Rather than emitting a normal format/argument mismatch, we want to
5990 // add a cast to the recommended type (and correct the format string
5991 // if necessary).
5992 SmallString<16> CastBuf;
5993 llvm::raw_svector_ostream CastFix(CastBuf);
5994 CastFix << "(";
5995 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5996 CastFix << ")";
5997
5998 SmallVector<FixItHint,4> Hints;
5999 if (!AT.matchesType(S.Context, IntendedTy))
6000 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6001
6002 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6003 // If there's already a cast present, just replace it.
6004 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6005 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6006
6007 } else if (!requiresParensToAddCast(E)) {
6008 // If the expression has high enough precedence,
6009 // just write the C-style cast.
6010 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6011 CastFix.str()));
6012 } else {
6013 // Otherwise, add parens around the expression as well as the cast.
6014 CastFix << "(";
6015 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6016 CastFix.str()));
6017
Alp Tokerb6cc5922014-05-03 03:45:55 +00006018 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006019 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6020 }
6021
Jordan Rose0e5badd2012-12-05 18:44:49 +00006022 if (ShouldNotPrintDirectly) {
6023 // The expression has a type that should not be printed directly.
6024 // We extract the name from the typedef because we don't want to show
6025 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006026 StringRef Name;
6027 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6028 Name = TypedefTy->getDecl()->getName();
6029 else
6030 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006031 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006032 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006033 << E->getSourceRange(),
6034 E->getLocStart(), /*IsStringLocation=*/false,
6035 SpecRange, Hints);
6036 } else {
6037 // In this case, the expression could be printed using a different
6038 // specifier, but we've decided that the specifier is probably correct
6039 // and we should cast instead. Just use the normal warning message.
6040 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006041 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6042 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006043 << E->getSourceRange(),
6044 E->getLocStart(), /*IsStringLocation*/false,
6045 SpecRange, Hints);
6046 }
Jordan Roseaee34382012-09-05 22:56:26 +00006047 }
Jordan Rose22b74712012-09-05 22:56:19 +00006048 } else {
6049 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6050 SpecifierLen);
6051 // Since the warning for passing non-POD types to variadic functions
6052 // was deferred until now, we emit a warning for non-POD
6053 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006054 switch (S.isValidVarArgType(ExprTy)) {
6055 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006056 case Sema::VAK_ValidInCXX11: {
6057 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6058 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6059 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6060 }
Richard Smithd7293d72013-08-05 18:49:43 +00006061
Seth Cantrellb4802962015-03-04 03:12:10 +00006062 EmitFormatDiagnostic(
6063 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6064 << IsEnum << CSR << E->getSourceRange(),
6065 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6066 break;
6067 }
Richard Smithd7293d72013-08-05 18:49:43 +00006068 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006069 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006070 EmitFormatDiagnostic(
6071 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006072 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006073 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006074 << CallType
6075 << AT.getRepresentativeTypeName(S.Context)
6076 << CSR
6077 << E->getSourceRange(),
6078 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006079 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006080 break;
6081
6082 case Sema::VAK_Invalid:
6083 if (ExprTy->isObjCObjectType())
6084 EmitFormatDiagnostic(
6085 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6086 << S.getLangOpts().CPlusPlus11
6087 << ExprTy
6088 << CallType
6089 << AT.getRepresentativeTypeName(S.Context)
6090 << CSR
6091 << E->getSourceRange(),
6092 E->getLocStart(), /*IsStringLocation*/false, CSR);
6093 else
6094 // FIXME: If this is an initializer list, suggest removing the braces
6095 // or inserting a cast to the target type.
6096 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6097 << isa<InitListExpr>(E) << ExprTy << CallType
6098 << AT.getRepresentativeTypeName(S.Context)
6099 << E->getSourceRange();
6100 break;
6101 }
6102
6103 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6104 "format string specifier index out of range");
6105 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006106 }
6107
Ted Kremenekab278de2010-01-28 23:39:18 +00006108 return true;
6109}
6110
Ted Kremenek02087932010-07-16 02:11:22 +00006111//===--- CHECK: Scanf format string checking ------------------------------===//
6112
6113namespace {
6114class CheckScanfHandler : public CheckFormatHandler {
6115public:
Stephen Hines648c3692016-09-16 01:07:04 +00006116 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006117 const Expr *origFormatExpr, Sema::FormatStringType type,
6118 unsigned firstDataArg, unsigned numDataArgs,
6119 const char *beg, bool hasVAListArg,
6120 ArrayRef<const Expr *> Args, unsigned formatIdx,
6121 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006122 llvm::SmallBitVector &CheckedVarArgs,
6123 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006124 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6125 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6126 inFunctionCall, CallType, CheckedVarArgs,
6127 UncoveredArg) {}
6128
Ted Kremenek02087932010-07-16 02:11:22 +00006129 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6130 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006131 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006132
6133 bool HandleInvalidScanfConversionSpecifier(
6134 const analyze_scanf::ScanfSpecifier &FS,
6135 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006136 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006137
Craig Toppere14c0f82014-03-12 04:55:44 +00006138 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006139};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006140} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006141
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006142void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6143 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006144 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6145 getLocationOfByte(end), /*IsStringLocation*/true,
6146 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006147}
6148
Ted Kremenekce815422010-07-19 21:25:57 +00006149bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6150 const analyze_scanf::ScanfSpecifier &FS,
6151 const char *startSpecifier,
6152 unsigned specifierLen) {
6153
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006154 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006155 FS.getConversionSpecifier();
6156
6157 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6158 getLocationOfByte(CS.getStart()),
6159 startSpecifier, specifierLen,
6160 CS.getStart(), CS.getLength());
6161}
6162
Ted Kremenek02087932010-07-16 02:11:22 +00006163bool CheckScanfHandler::HandleScanfSpecifier(
6164 const analyze_scanf::ScanfSpecifier &FS,
6165 const char *startSpecifier,
6166 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006167 using namespace analyze_scanf;
6168 using namespace analyze_format_string;
6169
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006170 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006171
Ted Kremenek6cd69422010-07-19 22:01:06 +00006172 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6173 // be used to decide if we are using positional arguments consistently.
6174 if (FS.consumesDataArgument()) {
6175 if (atFirstArg) {
6176 atFirstArg = false;
6177 usesPositionalArgs = FS.usesPositionalArg();
6178 }
6179 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006180 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6181 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006182 return false;
6183 }
Ted Kremenek02087932010-07-16 02:11:22 +00006184 }
6185
6186 // Check if the field with is non-zero.
6187 const OptionalAmount &Amt = FS.getFieldWidth();
6188 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6189 if (Amt.getConstantAmount() == 0) {
6190 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6191 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006192 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6193 getLocationOfByte(Amt.getStart()),
6194 /*IsStringLocation*/true, R,
6195 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006196 }
6197 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006198
Ted Kremenek02087932010-07-16 02:11:22 +00006199 if (!FS.consumesDataArgument()) {
6200 // FIXME: Technically specifying a precision or field width here
6201 // makes no sense. Worth issuing a warning at some point.
6202 return true;
6203 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006204
Ted Kremenek02087932010-07-16 02:11:22 +00006205 // Consume the argument.
6206 unsigned argIndex = FS.getArgIndex();
6207 if (argIndex < NumDataArgs) {
6208 // The check to see if the argIndex is valid will come later.
6209 // We set the bit here because we may exit early from this
6210 // function if we encounter some other error.
6211 CoveredArgs.set(argIndex);
6212 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006213
Ted Kremenek4407ea42010-07-20 20:04:47 +00006214 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006215 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006216 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6217 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006218 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006219 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006220 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006221 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6222 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006223
Jordan Rose92303592012-09-08 04:00:03 +00006224 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6225 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6226
Ted Kremenek02087932010-07-16 02:11:22 +00006227 // The remaining checks depend on the data arguments.
6228 if (HasVAListArg)
6229 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006230
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006231 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006232 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006233
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006234 // Check that the argument type matches the format specifier.
6235 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006236 if (!Ex)
6237 return true;
6238
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006239 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006240
6241 if (!AT.isValid()) {
6242 return true;
6243 }
6244
Seth Cantrellb4802962015-03-04 03:12:10 +00006245 analyze_format_string::ArgType::MatchKind match =
6246 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006247 if (match == analyze_format_string::ArgType::Match) {
6248 return true;
6249 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006250
Seth Cantrell79340072015-03-04 05:58:08 +00006251 ScanfSpecifier fixedFS = FS;
6252 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6253 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006254
Seth Cantrell79340072015-03-04 05:58:08 +00006255 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6256 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6257 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6258 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006259
Seth Cantrell79340072015-03-04 05:58:08 +00006260 if (success) {
6261 // Get the fix string from the fixed format specifier.
6262 SmallString<128> buf;
6263 llvm::raw_svector_ostream os(buf);
6264 fixedFS.toString(os);
6265
6266 EmitFormatDiagnostic(
6267 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6268 << Ex->getType() << false << Ex->getSourceRange(),
6269 Ex->getLocStart(),
6270 /*IsStringLocation*/ false,
6271 getSpecifierRange(startSpecifier, specifierLen),
6272 FixItHint::CreateReplacement(
6273 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6274 } else {
6275 EmitFormatDiagnostic(S.PDiag(diag)
6276 << AT.getRepresentativeTypeName(S.Context)
6277 << Ex->getType() << false << Ex->getSourceRange(),
6278 Ex->getLocStart(),
6279 /*IsStringLocation*/ false,
6280 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006281 }
6282
Ted Kremenek02087932010-07-16 02:11:22 +00006283 return true;
6284}
6285
Stephen Hines648c3692016-09-16 01:07:04 +00006286static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006287 const Expr *OrigFormatExpr,
6288 ArrayRef<const Expr *> Args,
6289 bool HasVAListArg, unsigned format_idx,
6290 unsigned firstDataArg,
6291 Sema::FormatStringType Type,
6292 bool inFunctionCall,
6293 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006294 llvm::SmallBitVector &CheckedVarArgs,
6295 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006296 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006297 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006298 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006299 S, inFunctionCall, Args[format_idx],
6300 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006301 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006302 return;
6303 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006304
Ted Kremenekab278de2010-01-28 23:39:18 +00006305 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006306 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006307 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006308 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006309 const ConstantArrayType *T =
6310 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006311 assert(T && "String literal not of constant array type!");
6312 size_t TypeSize = T->getSize().getZExtValue();
6313 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006314 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006315
6316 // Emit a warning if the string literal is truncated and does not contain an
6317 // embedded null character.
6318 if (TypeSize <= StrRef.size() &&
6319 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6320 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006321 S, inFunctionCall, Args[format_idx],
6322 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006323 FExpr->getLocStart(),
6324 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6325 return;
6326 }
6327
Ted Kremenekab278de2010-01-28 23:39:18 +00006328 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006329 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006330 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006331 S, inFunctionCall, Args[format_idx],
6332 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006333 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006334 return;
6335 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006336
6337 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006338 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6339 Type == Sema::FST_OSTrace) {
6340 CheckPrintfHandler H(
6341 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6342 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6343 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6344 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006345
Hans Wennborg23926bd2011-12-15 10:25:47 +00006346 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006347 S.getLangOpts(),
6348 S.Context.getTargetInfo(),
6349 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006350 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006351 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006352 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6353 numDataArgs, Str, HasVAListArg, Args, format_idx,
6354 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006355
Hans Wennborg23926bd2011-12-15 10:25:47 +00006356 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006357 S.getLangOpts(),
6358 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006359 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006360 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006361}
6362
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006363bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6364 // Str - The format string. NOTE: this is NOT null-terminated!
6365 StringRef StrRef = FExpr->getString();
6366 const char *Str = StrRef.data();
6367 // Account for cases where the string literal is truncated in a declaration.
6368 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6369 assert(T && "String literal not of constant array type!");
6370 size_t TypeSize = T->getSize().getZExtValue();
6371 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6372 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6373 getLangOpts(),
6374 Context.getTargetInfo());
6375}
6376
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006377//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6378
6379// Returns the related absolute value function that is larger, of 0 if one
6380// does not exist.
6381static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6382 switch (AbsFunction) {
6383 default:
6384 return 0;
6385
6386 case Builtin::BI__builtin_abs:
6387 return Builtin::BI__builtin_labs;
6388 case Builtin::BI__builtin_labs:
6389 return Builtin::BI__builtin_llabs;
6390 case Builtin::BI__builtin_llabs:
6391 return 0;
6392
6393 case Builtin::BI__builtin_fabsf:
6394 return Builtin::BI__builtin_fabs;
6395 case Builtin::BI__builtin_fabs:
6396 return Builtin::BI__builtin_fabsl;
6397 case Builtin::BI__builtin_fabsl:
6398 return 0;
6399
6400 case Builtin::BI__builtin_cabsf:
6401 return Builtin::BI__builtin_cabs;
6402 case Builtin::BI__builtin_cabs:
6403 return Builtin::BI__builtin_cabsl;
6404 case Builtin::BI__builtin_cabsl:
6405 return 0;
6406
6407 case Builtin::BIabs:
6408 return Builtin::BIlabs;
6409 case Builtin::BIlabs:
6410 return Builtin::BIllabs;
6411 case Builtin::BIllabs:
6412 return 0;
6413
6414 case Builtin::BIfabsf:
6415 return Builtin::BIfabs;
6416 case Builtin::BIfabs:
6417 return Builtin::BIfabsl;
6418 case Builtin::BIfabsl:
6419 return 0;
6420
6421 case Builtin::BIcabsf:
6422 return Builtin::BIcabs;
6423 case Builtin::BIcabs:
6424 return Builtin::BIcabsl;
6425 case Builtin::BIcabsl:
6426 return 0;
6427 }
6428}
6429
6430// Returns the argument type of the absolute value function.
6431static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6432 unsigned AbsType) {
6433 if (AbsType == 0)
6434 return QualType();
6435
6436 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6437 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6438 if (Error != ASTContext::GE_None)
6439 return QualType();
6440
6441 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6442 if (!FT)
6443 return QualType();
6444
6445 if (FT->getNumParams() != 1)
6446 return QualType();
6447
6448 return FT->getParamType(0);
6449}
6450
6451// Returns the best absolute value function, or zero, based on type and
6452// current absolute value function.
6453static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6454 unsigned AbsFunctionKind) {
6455 unsigned BestKind = 0;
6456 uint64_t ArgSize = Context.getTypeSize(ArgType);
6457 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6458 Kind = getLargerAbsoluteValueFunction(Kind)) {
6459 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6460 if (Context.getTypeSize(ParamType) >= ArgSize) {
6461 if (BestKind == 0)
6462 BestKind = Kind;
6463 else if (Context.hasSameType(ParamType, ArgType)) {
6464 BestKind = Kind;
6465 break;
6466 }
6467 }
6468 }
6469 return BestKind;
6470}
6471
6472enum AbsoluteValueKind {
6473 AVK_Integer,
6474 AVK_Floating,
6475 AVK_Complex
6476};
6477
6478static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6479 if (T->isIntegralOrEnumerationType())
6480 return AVK_Integer;
6481 if (T->isRealFloatingType())
6482 return AVK_Floating;
6483 if (T->isAnyComplexType())
6484 return AVK_Complex;
6485
6486 llvm_unreachable("Type not integer, floating, or complex");
6487}
6488
6489// Changes the absolute value function to a different type. Preserves whether
6490// the function is a builtin.
6491static unsigned changeAbsFunction(unsigned AbsKind,
6492 AbsoluteValueKind ValueKind) {
6493 switch (ValueKind) {
6494 case AVK_Integer:
6495 switch (AbsKind) {
6496 default:
6497 return 0;
6498 case Builtin::BI__builtin_fabsf:
6499 case Builtin::BI__builtin_fabs:
6500 case Builtin::BI__builtin_fabsl:
6501 case Builtin::BI__builtin_cabsf:
6502 case Builtin::BI__builtin_cabs:
6503 case Builtin::BI__builtin_cabsl:
6504 return Builtin::BI__builtin_abs;
6505 case Builtin::BIfabsf:
6506 case Builtin::BIfabs:
6507 case Builtin::BIfabsl:
6508 case Builtin::BIcabsf:
6509 case Builtin::BIcabs:
6510 case Builtin::BIcabsl:
6511 return Builtin::BIabs;
6512 }
6513 case AVK_Floating:
6514 switch (AbsKind) {
6515 default:
6516 return 0;
6517 case Builtin::BI__builtin_abs:
6518 case Builtin::BI__builtin_labs:
6519 case Builtin::BI__builtin_llabs:
6520 case Builtin::BI__builtin_cabsf:
6521 case Builtin::BI__builtin_cabs:
6522 case Builtin::BI__builtin_cabsl:
6523 return Builtin::BI__builtin_fabsf;
6524 case Builtin::BIabs:
6525 case Builtin::BIlabs:
6526 case Builtin::BIllabs:
6527 case Builtin::BIcabsf:
6528 case Builtin::BIcabs:
6529 case Builtin::BIcabsl:
6530 return Builtin::BIfabsf;
6531 }
6532 case AVK_Complex:
6533 switch (AbsKind) {
6534 default:
6535 return 0;
6536 case Builtin::BI__builtin_abs:
6537 case Builtin::BI__builtin_labs:
6538 case Builtin::BI__builtin_llabs:
6539 case Builtin::BI__builtin_fabsf:
6540 case Builtin::BI__builtin_fabs:
6541 case Builtin::BI__builtin_fabsl:
6542 return Builtin::BI__builtin_cabsf;
6543 case Builtin::BIabs:
6544 case Builtin::BIlabs:
6545 case Builtin::BIllabs:
6546 case Builtin::BIfabsf:
6547 case Builtin::BIfabs:
6548 case Builtin::BIfabsl:
6549 return Builtin::BIcabsf;
6550 }
6551 }
6552 llvm_unreachable("Unable to convert function");
6553}
6554
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006555static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006556 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6557 if (!FnInfo)
6558 return 0;
6559
6560 switch (FDecl->getBuiltinID()) {
6561 default:
6562 return 0;
6563 case Builtin::BI__builtin_abs:
6564 case Builtin::BI__builtin_fabs:
6565 case Builtin::BI__builtin_fabsf:
6566 case Builtin::BI__builtin_fabsl:
6567 case Builtin::BI__builtin_labs:
6568 case Builtin::BI__builtin_llabs:
6569 case Builtin::BI__builtin_cabs:
6570 case Builtin::BI__builtin_cabsf:
6571 case Builtin::BI__builtin_cabsl:
6572 case Builtin::BIabs:
6573 case Builtin::BIlabs:
6574 case Builtin::BIllabs:
6575 case Builtin::BIfabs:
6576 case Builtin::BIfabsf:
6577 case Builtin::BIfabsl:
6578 case Builtin::BIcabs:
6579 case Builtin::BIcabsf:
6580 case Builtin::BIcabsl:
6581 return FDecl->getBuiltinID();
6582 }
6583 llvm_unreachable("Unknown Builtin type");
6584}
6585
6586// If the replacement is valid, emit a note with replacement function.
6587// Additionally, suggest including the proper header if not already included.
6588static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006589 unsigned AbsKind, QualType ArgType) {
6590 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006591 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006592 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006593 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6594 FunctionName = "std::abs";
6595 if (ArgType->isIntegralOrEnumerationType()) {
6596 HeaderName = "cstdlib";
6597 } else if (ArgType->isRealFloatingType()) {
6598 HeaderName = "cmath";
6599 } else {
6600 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006601 }
Richard Trieubeffb832014-04-15 23:47:53 +00006602
6603 // Lookup all std::abs
6604 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006605 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006606 R.suppressDiagnostics();
6607 S.LookupQualifiedName(R, Std);
6608
6609 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006610 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006611 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6612 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6613 } else {
6614 FDecl = dyn_cast<FunctionDecl>(I);
6615 }
6616 if (!FDecl)
6617 continue;
6618
6619 // Found std::abs(), check that they are the right ones.
6620 if (FDecl->getNumParams() != 1)
6621 continue;
6622
6623 // Check that the parameter type can handle the argument.
6624 QualType ParamType = FDecl->getParamDecl(0)->getType();
6625 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6626 S.Context.getTypeSize(ArgType) <=
6627 S.Context.getTypeSize(ParamType)) {
6628 // Found a function, don't need the header hint.
6629 EmitHeaderHint = false;
6630 break;
6631 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006632 }
Richard Trieubeffb832014-04-15 23:47:53 +00006633 }
6634 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006635 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006636 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6637
6638 if (HeaderName) {
6639 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6640 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6641 R.suppressDiagnostics();
6642 S.LookupName(R, S.getCurScope());
6643
6644 if (R.isSingleResult()) {
6645 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6646 if (FD && FD->getBuiltinID() == AbsKind) {
6647 EmitHeaderHint = false;
6648 } else {
6649 return;
6650 }
6651 } else if (!R.empty()) {
6652 return;
6653 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006654 }
6655 }
6656
6657 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006658 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006659
Richard Trieubeffb832014-04-15 23:47:53 +00006660 if (!HeaderName)
6661 return;
6662
6663 if (!EmitHeaderHint)
6664 return;
6665
Alp Toker5d96e0a2014-07-11 20:53:51 +00006666 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6667 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006668}
6669
Richard Trieua7f30b12016-12-06 01:42:28 +00006670template <std::size_t StrLen>
6671static bool IsStdFunction(const FunctionDecl *FDecl,
6672 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006673 if (!FDecl)
6674 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006675 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006676 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006677 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006678 return false;
6679
6680 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006681}
6682
6683// Warn when using the wrong abs() function.
6684void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006685 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006686 if (Call->getNumArgs() != 1)
6687 return;
6688
6689 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006690 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006691 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006692 return;
6693
6694 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6695 QualType ParamType = Call->getArg(0)->getType();
6696
Alp Toker5d96e0a2014-07-11 20:53:51 +00006697 // Unsigned types cannot be negative. Suggest removing the absolute value
6698 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006699 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006700 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006701 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006702 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6703 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006704 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006705 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6706 return;
6707 }
6708
David Majnemer7f77eb92015-11-15 03:04:34 +00006709 // Taking the absolute value of a pointer is very suspicious, they probably
6710 // wanted to index into an array, dereference a pointer, call a function, etc.
6711 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6712 unsigned DiagType = 0;
6713 if (ArgType->isFunctionType())
6714 DiagType = 1;
6715 else if (ArgType->isArrayType())
6716 DiagType = 2;
6717
6718 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6719 return;
6720 }
6721
Richard Trieubeffb832014-04-15 23:47:53 +00006722 // std::abs has overloads which prevent most of the absolute value problems
6723 // from occurring.
6724 if (IsStdAbs)
6725 return;
6726
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006727 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6728 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6729
6730 // The argument and parameter are the same kind. Check if they are the right
6731 // size.
6732 if (ArgValueKind == ParamValueKind) {
6733 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6734 return;
6735
6736 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6737 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6738 << FDecl << ArgType << ParamType;
6739
6740 if (NewAbsKind == 0)
6741 return;
6742
6743 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006744 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006745 return;
6746 }
6747
6748 // ArgValueKind != ParamValueKind
6749 // The wrong type of absolute value function was used. Attempt to find the
6750 // proper one.
6751 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6752 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6753 if (NewAbsKind == 0)
6754 return;
6755
6756 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6757 << FDecl << ParamValueKind << ArgValueKind;
6758
6759 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006760 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006761}
6762
Richard Trieu67c00712016-12-05 23:41:46 +00006763//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006764void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6765 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006766 if (!Call || !FDecl) return;
6767
6768 // Ignore template specializations and macros.
6769 if (!ActiveTemplateInstantiations.empty()) return;
6770 if (Call->getExprLoc().isMacroID()) return;
6771
6772 // Only care about the one template argument, two function parameter std::max
6773 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006774 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006775 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6776 if (!ArgList) return;
6777 if (ArgList->size() != 1) return;
6778
6779 // Check that template type argument is unsigned integer.
6780 const auto& TA = ArgList->get(0);
6781 if (TA.getKind() != TemplateArgument::Type) return;
6782 QualType ArgType = TA.getAsType();
6783 if (!ArgType->isUnsignedIntegerType()) return;
6784
6785 // See if either argument is a literal zero.
6786 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6787 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6788 if (!MTE) return false;
6789 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6790 if (!Num) return false;
6791 if (Num->getValue() != 0) return false;
6792 return true;
6793 };
6794
6795 const Expr *FirstArg = Call->getArg(0);
6796 const Expr *SecondArg = Call->getArg(1);
6797 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6798 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6799
6800 // Only warn when exactly one argument is zero.
6801 if (IsFirstArgZero == IsSecondArgZero) return;
6802
6803 SourceRange FirstRange = FirstArg->getSourceRange();
6804 SourceRange SecondRange = SecondArg->getSourceRange();
6805
6806 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6807
6808 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6809 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6810
6811 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6812 SourceRange RemovalRange;
6813 if (IsFirstArgZero) {
6814 RemovalRange = SourceRange(FirstRange.getBegin(),
6815 SecondRange.getBegin().getLocWithOffset(-1));
6816 } else {
6817 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6818 SecondRange.getEnd());
6819 }
6820
6821 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6822 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6823 << FixItHint::CreateRemoval(RemovalRange);
6824}
6825
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006826//===--- CHECK: Standard memory functions ---------------------------------===//
6827
Nico Weber0e6daef2013-12-26 23:38:39 +00006828/// \brief Takes the expression passed to the size_t parameter of functions
6829/// such as memcmp, strncat, etc and warns if it's a comparison.
6830///
6831/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6832static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6833 IdentifierInfo *FnName,
6834 SourceLocation FnLoc,
6835 SourceLocation RParenLoc) {
6836 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6837 if (!Size)
6838 return false;
6839
6840 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6841 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6842 return false;
6843
Nico Weber0e6daef2013-12-26 23:38:39 +00006844 SourceRange SizeRange = Size->getSourceRange();
6845 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6846 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006847 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006848 << FnName << FixItHint::CreateInsertion(
6849 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006850 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006851 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006852 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006853 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6854 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006855
6856 return true;
6857}
6858
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006859/// \brief Determine whether the given type is or contains a dynamic class type
6860/// (e.g., whether it has a vtable).
6861static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6862 bool &IsContained) {
6863 // Look through array types while ignoring qualifiers.
6864 const Type *Ty = T->getBaseElementTypeUnsafe();
6865 IsContained = false;
6866
6867 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6868 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006869 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006870 return nullptr;
6871
6872 if (RD->isDynamicClass())
6873 return RD;
6874
6875 // Check all the fields. If any bases were dynamic, the class is dynamic.
6876 // It's impossible for a class to transitively contain itself by value, so
6877 // infinite recursion is impossible.
6878 for (auto *FD : RD->fields()) {
6879 bool SubContained;
6880 if (const CXXRecordDecl *ContainedRD =
6881 getContainedDynamicClass(FD->getType(), SubContained)) {
6882 IsContained = true;
6883 return ContainedRD;
6884 }
6885 }
6886
6887 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006888}
6889
Chandler Carruth889ed862011-06-21 23:04:20 +00006890/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006891/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006892static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006893 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006894 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6895 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6896 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006897
Craig Topperc3ec1492014-05-26 06:22:03 +00006898 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006899}
6900
Chandler Carruth889ed862011-06-21 23:04:20 +00006901/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006902static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006903 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6904 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6905 if (SizeOf->getKind() == clang::UETT_SizeOf)
6906 return SizeOf->getTypeOfArgument();
6907
6908 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006909}
6910
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006911/// \brief Check for dangerous or invalid arguments to memset().
6912///
Chandler Carruthac687262011-06-03 06:23:57 +00006913/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006914/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6915/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006916///
6917/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006918void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006919 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006920 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006921 assert(BId != 0);
6922
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006923 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006924 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006925 unsigned ExpectedNumArgs =
6926 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006927 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006928 return;
6929
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006930 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006931 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006932 unsigned LenArg =
6933 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006934 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006935
Nico Weber0e6daef2013-12-26 23:38:39 +00006936 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6937 Call->getLocStart(), Call->getRParenLoc()))
6938 return;
6939
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006940 // We have special checking when the length is a sizeof expression.
6941 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6942 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6943 llvm::FoldingSetNodeID SizeOfArgID;
6944
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006945 // Although widely used, 'bzero' is not a standard function. Be more strict
6946 // with the argument types before allowing diagnostics and only allow the
6947 // form bzero(ptr, sizeof(...)).
6948 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6949 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6950 return;
6951
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006952 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6953 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006954 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006955
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006956 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006957 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006958 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006959 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006960
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006961 // Never warn about void type pointers. This can be used to suppress
6962 // false positives.
6963 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006964 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006965
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006966 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6967 // actually comparing the expressions for equality. Because computing the
6968 // expression IDs can be expensive, we only do this if the diagnostic is
6969 // enabled.
6970 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006971 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6972 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006973 // We only compute IDs for expressions if the warning is enabled, and
6974 // cache the sizeof arg's ID.
6975 if (SizeOfArgID == llvm::FoldingSetNodeID())
6976 SizeOfArg->Profile(SizeOfArgID, Context, true);
6977 llvm::FoldingSetNodeID DestID;
6978 Dest->Profile(DestID, Context, true);
6979 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006980 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6981 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006982 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006983 StringRef ReadableName = FnName->getName();
6984
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006985 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006986 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006987 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006988 if (!PointeeTy->isIncompleteType() &&
6989 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006990 ActionIdx = 2; // If the pointee's size is sizeof(char),
6991 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006992
6993 // If the function is defined as a builtin macro, do not show macro
6994 // expansion.
6995 SourceLocation SL = SizeOfArg->getExprLoc();
6996 SourceRange DSR = Dest->getSourceRange();
6997 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006998 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006999
7000 if (SM.isMacroArgExpansion(SL)) {
7001 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7002 SL = SM.getSpellingLoc(SL);
7003 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7004 SM.getSpellingLoc(DSR.getEnd()));
7005 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7006 SM.getSpellingLoc(SSR.getEnd()));
7007 }
7008
Anna Zaksd08d9152012-05-30 23:14:52 +00007009 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007010 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007011 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007012 << PointeeTy
7013 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007014 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007015 << SSR);
7016 DiagRuntimeBehavior(SL, SizeOfArg,
7017 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7018 << ActionIdx
7019 << SSR);
7020
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007021 break;
7022 }
7023 }
7024
7025 // Also check for cases where the sizeof argument is the exact same
7026 // type as the memory argument, and where it points to a user-defined
7027 // record type.
7028 if (SizeOfArgTy != QualType()) {
7029 if (PointeeTy->isRecordType() &&
7030 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7031 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7032 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7033 << FnName << SizeOfArgTy << ArgIdx
7034 << PointeeTy << Dest->getSourceRange()
7035 << LenExpr->getSourceRange());
7036 break;
7037 }
Nico Weberc5e73862011-06-14 16:14:58 +00007038 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007039 } else if (DestTy->isArrayType()) {
7040 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007041 }
Nico Weberc5e73862011-06-14 16:14:58 +00007042
Nico Weberc44b35e2015-03-21 17:37:46 +00007043 if (PointeeTy == QualType())
7044 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007045
Nico Weberc44b35e2015-03-21 17:37:46 +00007046 // Always complain about dynamic classes.
7047 bool IsContained;
7048 if (const CXXRecordDecl *ContainedRD =
7049 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007050
Nico Weberc44b35e2015-03-21 17:37:46 +00007051 unsigned OperationType = 0;
7052 // "overwritten" if we're warning about the destination for any call
7053 // but memcmp; otherwise a verb appropriate to the call.
7054 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7055 if (BId == Builtin::BImemcpy)
7056 OperationType = 1;
7057 else if(BId == Builtin::BImemmove)
7058 OperationType = 2;
7059 else if (BId == Builtin::BImemcmp)
7060 OperationType = 3;
7061 }
7062
John McCall31168b02011-06-15 23:02:42 +00007063 DiagRuntimeBehavior(
7064 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007065 PDiag(diag::warn_dyn_class_memaccess)
7066 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7067 << FnName << IsContained << ContainedRD << OperationType
7068 << Call->getCallee()->getSourceRange());
7069 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7070 BId != Builtin::BImemset)
7071 DiagRuntimeBehavior(
7072 Dest->getExprLoc(), Dest,
7073 PDiag(diag::warn_arc_object_memaccess)
7074 << ArgIdx << FnName << PointeeTy
7075 << Call->getCallee()->getSourceRange());
7076 else
7077 continue;
7078
7079 DiagRuntimeBehavior(
7080 Dest->getExprLoc(), Dest,
7081 PDiag(diag::note_bad_memaccess_silence)
7082 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7083 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007084 }
7085}
7086
Ted Kremenek6865f772011-08-18 20:55:45 +00007087// A little helper routine: ignore addition and subtraction of integer literals.
7088// This intentionally does not ignore all integer constant expressions because
7089// we don't want to remove sizeof().
7090static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7091 Ex = Ex->IgnoreParenCasts();
7092
7093 for (;;) {
7094 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7095 if (!BO || !BO->isAdditiveOp())
7096 break;
7097
7098 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7099 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7100
7101 if (isa<IntegerLiteral>(RHS))
7102 Ex = LHS;
7103 else if (isa<IntegerLiteral>(LHS))
7104 Ex = RHS;
7105 else
7106 break;
7107 }
7108
7109 return Ex;
7110}
7111
Anna Zaks13b08572012-08-08 21:42:23 +00007112static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7113 ASTContext &Context) {
7114 // Only handle constant-sized or VLAs, but not flexible members.
7115 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7116 // Only issue the FIXIT for arrays of size > 1.
7117 if (CAT->getSize().getSExtValue() <= 1)
7118 return false;
7119 } else if (!Ty->isVariableArrayType()) {
7120 return false;
7121 }
7122 return true;
7123}
7124
Ted Kremenek6865f772011-08-18 20:55:45 +00007125// Warn if the user has made the 'size' argument to strlcpy or strlcat
7126// be the size of the source, instead of the destination.
7127void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7128 IdentifierInfo *FnName) {
7129
7130 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007131 unsigned NumArgs = Call->getNumArgs();
7132 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007133 return;
7134
7135 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7136 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007137 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007138
7139 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7140 Call->getLocStart(), Call->getRParenLoc()))
7141 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007142
7143 // Look for 'strlcpy(dst, x, sizeof(x))'
7144 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7145 CompareWithSrc = Ex;
7146 else {
7147 // Look for 'strlcpy(dst, x, strlen(x))'
7148 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007149 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7150 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007151 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7152 }
7153 }
7154
7155 if (!CompareWithSrc)
7156 return;
7157
7158 // Determine if the argument to sizeof/strlen is equal to the source
7159 // argument. In principle there's all kinds of things you could do
7160 // here, for instance creating an == expression and evaluating it with
7161 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7162 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7163 if (!SrcArgDRE)
7164 return;
7165
7166 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7167 if (!CompareWithSrcDRE ||
7168 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7169 return;
7170
7171 const Expr *OriginalSizeArg = Call->getArg(2);
7172 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7173 << OriginalSizeArg->getSourceRange() << FnName;
7174
7175 // Output a FIXIT hint if the destination is an array (rather than a
7176 // pointer to an array). This could be enhanced to handle some
7177 // pointers if we know the actual size, like if DstArg is 'array+2'
7178 // we could say 'sizeof(array)-2'.
7179 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007180 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007181 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007182
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007183 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007184 llvm::raw_svector_ostream OS(sizeString);
7185 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007186 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007187 OS << ")";
7188
7189 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7190 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7191 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007192}
7193
Anna Zaks314cd092012-02-01 19:08:57 +00007194/// Check if two expressions refer to the same declaration.
7195static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7196 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7197 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7198 return D1->getDecl() == D2->getDecl();
7199 return false;
7200}
7201
7202static const Expr *getStrlenExprArg(const Expr *E) {
7203 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7204 const FunctionDecl *FD = CE->getDirectCallee();
7205 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007206 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007207 return CE->getArg(0)->IgnoreParenCasts();
7208 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007209 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007210}
7211
7212// Warn on anti-patterns as the 'size' argument to strncat.
7213// The correct size argument should look like following:
7214// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7215void Sema::CheckStrncatArguments(const CallExpr *CE,
7216 IdentifierInfo *FnName) {
7217 // Don't crash if the user has the wrong number of arguments.
7218 if (CE->getNumArgs() < 3)
7219 return;
7220 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7221 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7222 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7223
Nico Weber0e6daef2013-12-26 23:38:39 +00007224 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7225 CE->getRParenLoc()))
7226 return;
7227
Anna Zaks314cd092012-02-01 19:08:57 +00007228 // Identify common expressions, which are wrongly used as the size argument
7229 // to strncat and may lead to buffer overflows.
7230 unsigned PatternType = 0;
7231 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7232 // - sizeof(dst)
7233 if (referToTheSameDecl(SizeOfArg, DstArg))
7234 PatternType = 1;
7235 // - sizeof(src)
7236 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7237 PatternType = 2;
7238 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7239 if (BE->getOpcode() == BO_Sub) {
7240 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7241 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7242 // - sizeof(dst) - strlen(dst)
7243 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7244 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7245 PatternType = 1;
7246 // - sizeof(src) - (anything)
7247 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7248 PatternType = 2;
7249 }
7250 }
7251
7252 if (PatternType == 0)
7253 return;
7254
Anna Zaks5069aa32012-02-03 01:27:37 +00007255 // Generate the diagnostic.
7256 SourceLocation SL = LenArg->getLocStart();
7257 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007258 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007259
7260 // If the function is defined as a builtin macro, do not show macro expansion.
7261 if (SM.isMacroArgExpansion(SL)) {
7262 SL = SM.getSpellingLoc(SL);
7263 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7264 SM.getSpellingLoc(SR.getEnd()));
7265 }
7266
Anna Zaks13b08572012-08-08 21:42:23 +00007267 // Check if the destination is an array (rather than a pointer to an array).
7268 QualType DstTy = DstArg->getType();
7269 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7270 Context);
7271 if (!isKnownSizeArray) {
7272 if (PatternType == 1)
7273 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7274 else
7275 Diag(SL, diag::warn_strncat_src_size) << SR;
7276 return;
7277 }
7278
Anna Zaks314cd092012-02-01 19:08:57 +00007279 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007280 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007281 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007282 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007283
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007284 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007285 llvm::raw_svector_ostream OS(sizeString);
7286 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007287 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007288 OS << ") - ";
7289 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007290 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007291 OS << ") - 1";
7292
Anna Zaks5069aa32012-02-03 01:27:37 +00007293 Diag(SL, diag::note_strncat_wrong_size)
7294 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007295}
7296
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007297//===--- CHECK: Return Address of Stack Variable --------------------------===//
7298
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007299static const Expr *EvalVal(const Expr *E,
7300 SmallVectorImpl<const DeclRefExpr *> &refVars,
7301 const Decl *ParentDecl);
7302static const Expr *EvalAddr(const Expr *E,
7303 SmallVectorImpl<const DeclRefExpr *> &refVars,
7304 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007305
7306/// CheckReturnStackAddr - Check if a return statement returns the address
7307/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007308static void
7309CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7310 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007311
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007312 const Expr *stackE = nullptr;
7313 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007314
7315 // Perform checking for returned stack addresses, local blocks,
7316 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007317 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007318 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007319 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007320 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007321 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007322 }
7323
Craig Topperc3ec1492014-05-26 06:22:03 +00007324 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007325 return; // Nothing suspicious was found.
7326
Richard Trieu81b6c562016-08-05 23:24:47 +00007327 // Parameters are initalized in the calling scope, so taking the address
7328 // of a parameter reference doesn't need a warning.
7329 for (auto *DRE : refVars)
7330 if (isa<ParmVarDecl>(DRE->getDecl()))
7331 return;
7332
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007333 SourceLocation diagLoc;
7334 SourceRange diagRange;
7335 if (refVars.empty()) {
7336 diagLoc = stackE->getLocStart();
7337 diagRange = stackE->getSourceRange();
7338 } else {
7339 // We followed through a reference variable. 'stackE' contains the
7340 // problematic expression but we will warn at the return statement pointing
7341 // at the reference variable. We will later display the "trail" of
7342 // reference variables using notes.
7343 diagLoc = refVars[0]->getLocStart();
7344 diagRange = refVars[0]->getSourceRange();
7345 }
7346
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007347 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7348 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007349 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007350 << DR->getDecl()->getDeclName() << diagRange;
7351 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007352 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007353 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007354 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007355 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007356 // If there is an LValue->RValue conversion, then the value of the
7357 // reference type is used, not the reference.
7358 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7359 if (ICE->getCastKind() == CK_LValueToRValue) {
7360 return;
7361 }
7362 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007363 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7364 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007365 }
7366
7367 // Display the "trail" of reference variables that we followed until we
7368 // found the problematic expression using notes.
7369 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007370 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007371 // If this var binds to another reference var, show the range of the next
7372 // var, otherwise the var binds to the problematic expression, in which case
7373 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007374 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7375 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007376 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7377 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007378 }
7379}
7380
7381/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7382/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007383/// to a location on the stack, a local block, an address of a label, or a
7384/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007385/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007386/// encounter a subexpression that (1) clearly does not lead to one of the
7387/// above problematic expressions (2) is something we cannot determine leads to
7388/// a problematic expression based on such local checking.
7389///
7390/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7391/// the expression that they point to. Such variables are added to the
7392/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007393///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007394/// EvalAddr processes expressions that are pointers that are used as
7395/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007396/// At the base case of the recursion is a check for the above problematic
7397/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007398///
7399/// This implementation handles:
7400///
7401/// * pointer-to-pointer casts
7402/// * implicit conversions from array references to pointers
7403/// * taking the address of fields
7404/// * arbitrary interplay between "&" and "*" operators
7405/// * pointer arithmetic from an address of a stack variable
7406/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007407static const Expr *EvalAddr(const Expr *E,
7408 SmallVectorImpl<const DeclRefExpr *> &refVars,
7409 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007410 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007411 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007412
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007413 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007414 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007415 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007416 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007417 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007418
Peter Collingbourne91147592011-04-15 00:35:48 +00007419 E = E->IgnoreParens();
7420
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007421 // Our "symbolic interpreter" is just a dispatch off the currently
7422 // viewed AST node. We then recursively traverse the AST by calling
7423 // EvalAddr and EvalVal appropriately.
7424 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007425 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007426 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007427
Richard Smith40f08eb2014-01-30 22:05:38 +00007428 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007429 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007430 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007431
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007432 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007433 // If this is a reference variable, follow through to the expression that
7434 // it points to.
7435 if (V->hasLocalStorage() &&
7436 V->getType()->isReferenceType() && V->hasInit()) {
7437 // Add the reference variable to the "trail".
7438 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007439 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007440 }
7441
Craig Topperc3ec1492014-05-26 06:22:03 +00007442 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007443 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007444
Chris Lattner934edb22007-12-28 05:31:15 +00007445 case Stmt::UnaryOperatorClass: {
7446 // The only unary operator that make sense to handle here
7447 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007448 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007449
John McCalle3027922010-08-25 11:45:40 +00007450 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007451 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007452 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007453 }
Mike Stump11289f42009-09-09 15:08:12 +00007454
Chris Lattner934edb22007-12-28 05:31:15 +00007455 case Stmt::BinaryOperatorClass: {
7456 // Handle pointer arithmetic. All other binary operators are not valid
7457 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007458 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007459 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007460
John McCalle3027922010-08-25 11:45:40 +00007461 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007462 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007463
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007464 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007465
7466 // Determine which argument is the real pointer base. It could be
7467 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007468 if (!Base->getType()->isPointerType())
7469 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007470
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007471 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007472 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007473 }
Steve Naroff2752a172008-09-10 19:17:48 +00007474
Chris Lattner934edb22007-12-28 05:31:15 +00007475 // For conditional operators we need to see if either the LHS or RHS are
7476 // valid DeclRefExpr*s. If one of them is valid, we return it.
7477 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007478 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007479
Chris Lattner934edb22007-12-28 05:31:15 +00007480 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007481 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007482 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007483 // In C++, we can have a throw-expression, which has 'void' type.
7484 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007485 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007486 return LHS;
7487 }
Chris Lattner934edb22007-12-28 05:31:15 +00007488
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007489 // In C++, we can have a throw-expression, which has 'void' type.
7490 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007491 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007492
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007493 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007494 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007495
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007496 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007497 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007498 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007499 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007500
7501 case Stmt::AddrLabelExprClass:
7502 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007503
John McCall28fc7092011-11-10 05:35:25 +00007504 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007505 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7506 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007507
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007508 // For casts, we need to handle conversions from arrays to
7509 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007510 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007511 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007512 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007513 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007514 case Stmt::CXXStaticCastExprClass:
7515 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007516 case Stmt::CXXConstCastExprClass:
7517 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007518 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007519 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007520 case CK_LValueToRValue:
7521 case CK_NoOp:
7522 case CK_BaseToDerived:
7523 case CK_DerivedToBase:
7524 case CK_UncheckedDerivedToBase:
7525 case CK_Dynamic:
7526 case CK_CPointerToObjCPointerCast:
7527 case CK_BlockPointerToObjCPointerCast:
7528 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007529 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007530
7531 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007532 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007533
Richard Trieudadefde2014-07-02 04:39:38 +00007534 case CK_BitCast:
7535 if (SubExpr->getType()->isAnyPointerType() ||
7536 SubExpr->getType()->isBlockPointerType() ||
7537 SubExpr->getType()->isObjCQualifiedIdType())
7538 return EvalAddr(SubExpr, refVars, ParentDecl);
7539 else
7540 return nullptr;
7541
Eli Friedman8195ad72012-02-23 23:04:32 +00007542 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007543 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007544 }
Chris Lattner934edb22007-12-28 05:31:15 +00007545 }
Mike Stump11289f42009-09-09 15:08:12 +00007546
Douglas Gregorfe314812011-06-21 17:03:29 +00007547 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007548 if (const Expr *Result =
7549 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7550 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007551 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007552 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007553
Chris Lattner934edb22007-12-28 05:31:15 +00007554 // Everything else: we simply don't reason about them.
7555 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007556 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007557 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007558}
Mike Stump11289f42009-09-09 15:08:12 +00007559
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007560/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7561/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007562static const Expr *EvalVal(const Expr *E,
7563 SmallVectorImpl<const DeclRefExpr *> &refVars,
7564 const Decl *ParentDecl) {
7565 do {
7566 // We should only be called for evaluating non-pointer expressions, or
7567 // expressions with a pointer type that are not used as references but
7568 // instead
7569 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007570
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007571 // Our "symbolic interpreter" is just a dispatch off the currently
7572 // viewed AST node. We then recursively traverse the AST by calling
7573 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007574
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007575 E = E->IgnoreParens();
7576 switch (E->getStmtClass()) {
7577 case Stmt::ImplicitCastExprClass: {
7578 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7579 if (IE->getValueKind() == VK_LValue) {
7580 E = IE->getSubExpr();
7581 continue;
7582 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007583 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007584 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007585
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007586 case Stmt::ExprWithCleanupsClass:
7587 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7588 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007589
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007590 case Stmt::DeclRefExprClass: {
7591 // When we hit a DeclRefExpr we are looking at code that refers to a
7592 // variable's name. If it's not a reference variable we check if it has
7593 // local storage within the function, and if so, return the expression.
7594 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7595
7596 // If we leave the immediate function, the lifetime isn't about to end.
7597 if (DR->refersToEnclosingVariableOrCapture())
7598 return nullptr;
7599
7600 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7601 // Check if it refers to itself, e.g. "int& i = i;".
7602 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007603 return DR;
7604
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007605 if (V->hasLocalStorage()) {
7606 if (!V->getType()->isReferenceType())
7607 return DR;
7608
7609 // Reference variable, follow through to the expression that
7610 // it points to.
7611 if (V->hasInit()) {
7612 // Add the reference variable to the "trail".
7613 refVars.push_back(DR);
7614 return EvalVal(V->getInit(), refVars, V);
7615 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007616 }
7617 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007618
7619 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007620 }
Mike Stump11289f42009-09-09 15:08:12 +00007621
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007622 case Stmt::UnaryOperatorClass: {
7623 // The only unary operator that make sense to handle here
7624 // is Deref. All others don't resolve to a "name." This includes
7625 // handling all sorts of rvalues passed to a unary operator.
7626 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007627
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007628 if (U->getOpcode() == UO_Deref)
7629 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007630
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007631 return nullptr;
7632 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007633
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007634 case Stmt::ArraySubscriptExprClass: {
7635 // Array subscripts are potential references to data on the stack. We
7636 // retrieve the DeclRefExpr* for the array variable if it indeed
7637 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007638 const auto *ASE = cast<ArraySubscriptExpr>(E);
7639 if (ASE->isTypeDependent())
7640 return nullptr;
7641 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007642 }
Mike Stump11289f42009-09-09 15:08:12 +00007643
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007644 case Stmt::OMPArraySectionExprClass: {
7645 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7646 ParentDecl);
7647 }
Mike Stump11289f42009-09-09 15:08:12 +00007648
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007649 case Stmt::ConditionalOperatorClass: {
7650 // For conditional operators we need to see if either the LHS or RHS are
7651 // non-NULL Expr's. If one is non-NULL, we return it.
7652 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007653
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007654 // Handle the GNU extension for missing LHS.
7655 if (const Expr *LHSExpr = C->getLHS()) {
7656 // In C++, we can have a throw-expression, which has 'void' type.
7657 if (!LHSExpr->getType()->isVoidType())
7658 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7659 return LHS;
7660 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007661
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007662 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007663 if (C->getRHS()->getType()->isVoidType())
7664 return nullptr;
7665
7666 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007667 }
7668
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007669 // Accesses to members are potential references to data on the stack.
7670 case Stmt::MemberExprClass: {
7671 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007672
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007673 // Check for indirect access. We only want direct field accesses.
7674 if (M->isArrow())
7675 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007676
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007677 // Check whether the member type is itself a reference, in which case
7678 // we're not going to refer to the member, but to what the member refers
7679 // to.
7680 if (M->getMemberDecl()->getType()->isReferenceType())
7681 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007682
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007683 return EvalVal(M->getBase(), refVars, ParentDecl);
7684 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007685
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007686 case Stmt::MaterializeTemporaryExprClass:
7687 if (const Expr *Result =
7688 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7689 refVars, ParentDecl))
7690 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007691 return E;
7692
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007693 default:
7694 // Check that we don't return or take the address of a reference to a
7695 // temporary. This is only useful in C++.
7696 if (!E->isTypeDependent() && E->isRValue())
7697 return E;
7698
7699 // Everything else: we simply don't reason about them.
7700 return nullptr;
7701 }
7702 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007703}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007704
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007705void
7706Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7707 SourceLocation ReturnLoc,
7708 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007709 const AttrVec *Attrs,
7710 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007711 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7712
7713 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007714 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7715 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007716 CheckNonNullExpr(*this, RetValExp))
7717 Diag(ReturnLoc, diag::warn_null_ret)
7718 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007719
7720 // C++11 [basic.stc.dynamic.allocation]p4:
7721 // If an allocation function declared with a non-throwing
7722 // exception-specification fails to allocate storage, it shall return
7723 // a null pointer. Any other allocation function that fails to allocate
7724 // storage shall indicate failure only by throwing an exception [...]
7725 if (FD) {
7726 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7727 if (Op == OO_New || Op == OO_Array_New) {
7728 const FunctionProtoType *Proto
7729 = FD->getType()->castAs<FunctionProtoType>();
7730 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7731 CheckNonNullExpr(*this, RetValExp))
7732 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7733 << FD << getLangOpts().CPlusPlus11;
7734 }
7735 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007736}
7737
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007738//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7739
7740/// Check for comparisons of floating point operands using != and ==.
7741/// Issue a warning if these are no self-comparisons, as they are not likely
7742/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007743void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007744 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7745 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007746
7747 // Special case: check for x == x (which is OK).
7748 // Do not emit warnings for such cases.
7749 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7750 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7751 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007752 return;
Mike Stump11289f42009-09-09 15:08:12 +00007753
Ted Kremenekeda40e22007-11-29 00:59:04 +00007754 // Special case: check for comparisons against literals that can be exactly
7755 // represented by APFloat. In such cases, do not emit a warning. This
7756 // is a heuristic: often comparison against such literals are used to
7757 // detect if a value in a variable has not changed. This clearly can
7758 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007759 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7760 if (FLL->isExact())
7761 return;
7762 } else
7763 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7764 if (FLR->isExact())
7765 return;
Mike Stump11289f42009-09-09 15:08:12 +00007766
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007767 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007768 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007769 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007770 return;
Mike Stump11289f42009-09-09 15:08:12 +00007771
David Blaikie1f4ff152012-07-16 20:47:22 +00007772 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007773 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007774 return;
Mike Stump11289f42009-09-09 15:08:12 +00007775
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007776 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007777 Diag(Loc, diag::warn_floatingpoint_eq)
7778 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007779}
John McCallca01b222010-01-04 23:21:16 +00007780
John McCall70aa5392010-01-06 05:24:50 +00007781//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7782//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007783
John McCall70aa5392010-01-06 05:24:50 +00007784namespace {
John McCallca01b222010-01-04 23:21:16 +00007785
John McCall70aa5392010-01-06 05:24:50 +00007786/// Structure recording the 'active' range of an integer-valued
7787/// expression.
7788struct IntRange {
7789 /// The number of bits active in the int.
7790 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007791
John McCall70aa5392010-01-06 05:24:50 +00007792 /// True if the int is known not to have negative values.
7793 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007794
John McCall70aa5392010-01-06 05:24:50 +00007795 IntRange(unsigned Width, bool NonNegative)
7796 : Width(Width), NonNegative(NonNegative)
7797 {}
John McCallca01b222010-01-04 23:21:16 +00007798
John McCall817d4af2010-11-10 23:38:19 +00007799 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007800 static IntRange forBoolType() {
7801 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007802 }
7803
John McCall817d4af2010-11-10 23:38:19 +00007804 /// Returns the range of an opaque value of the given integral type.
7805 static IntRange forValueOfType(ASTContext &C, QualType T) {
7806 return forValueOfCanonicalType(C,
7807 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007808 }
7809
John McCall817d4af2010-11-10 23:38:19 +00007810 /// Returns the range of an opaque value of a canonical integral type.
7811 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007812 assert(T->isCanonicalUnqualified());
7813
7814 if (const VectorType *VT = dyn_cast<VectorType>(T))
7815 T = VT->getElementType().getTypePtr();
7816 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7817 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007818 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7819 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007820
David Majnemer6a426652013-06-07 22:07:20 +00007821 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007822 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007823 EnumDecl *Enum = ET->getDecl();
7824 if (!Enum->isCompleteDefinition())
7825 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007826
David Majnemer6a426652013-06-07 22:07:20 +00007827 unsigned NumPositive = Enum->getNumPositiveBits();
7828 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007829
David Majnemer6a426652013-06-07 22:07:20 +00007830 if (NumNegative == 0)
7831 return IntRange(NumPositive, true/*NonNegative*/);
7832 else
7833 return IntRange(std::max(NumPositive + 1, NumNegative),
7834 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007835 }
John McCall70aa5392010-01-06 05:24:50 +00007836
7837 const BuiltinType *BT = cast<BuiltinType>(T);
7838 assert(BT->isInteger());
7839
7840 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7841 }
7842
John McCall817d4af2010-11-10 23:38:19 +00007843 /// Returns the "target" range of a canonical integral type, i.e.
7844 /// the range of values expressible in the type.
7845 ///
7846 /// This matches forValueOfCanonicalType except that enums have the
7847 /// full range of their type, not the range of their enumerators.
7848 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7849 assert(T->isCanonicalUnqualified());
7850
7851 if (const VectorType *VT = dyn_cast<VectorType>(T))
7852 T = VT->getElementType().getTypePtr();
7853 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7854 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007855 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7856 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007857 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007858 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007859
7860 const BuiltinType *BT = cast<BuiltinType>(T);
7861 assert(BT->isInteger());
7862
7863 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7864 }
7865
7866 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007867 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007868 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007869 L.NonNegative && R.NonNegative);
7870 }
7871
John McCall817d4af2010-11-10 23:38:19 +00007872 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007873 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007874 return IntRange(std::min(L.Width, R.Width),
7875 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007876 }
7877};
7878
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007879IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007880 if (value.isSigned() && value.isNegative())
7881 return IntRange(value.getMinSignedBits(), false);
7882
7883 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007884 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007885
7886 // isNonNegative() just checks the sign bit without considering
7887 // signedness.
7888 return IntRange(value.getActiveBits(), true);
7889}
7890
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007891IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7892 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007893 if (result.isInt())
7894 return GetValueRange(C, result.getInt(), MaxWidth);
7895
7896 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007897 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7898 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7899 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7900 R = IntRange::join(R, El);
7901 }
John McCall70aa5392010-01-06 05:24:50 +00007902 return R;
7903 }
7904
7905 if (result.isComplexInt()) {
7906 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7907 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7908 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007909 }
7910
7911 // This can happen with lossless casts to intptr_t of "based" lvalues.
7912 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007913 // FIXME: The only reason we need to pass the type in here is to get
7914 // the sign right on this one case. It would be nice if APValue
7915 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007916 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007917 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007918}
John McCall70aa5392010-01-06 05:24:50 +00007919
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007920QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007921 QualType Ty = E->getType();
7922 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7923 Ty = AtomicRHS->getValueType();
7924 return Ty;
7925}
7926
John McCall70aa5392010-01-06 05:24:50 +00007927/// Pseudo-evaluate the given integer expression, estimating the
7928/// range of values it might take.
7929///
7930/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007931IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007932 E = E->IgnoreParens();
7933
7934 // Try a full evaluation first.
7935 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007936 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007937 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007938
7939 // I think we only want to look through implicit casts here; if the
7940 // user has an explicit widening cast, we should treat the value as
7941 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007942 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007943 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007944 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7945
Eli Friedmane6d33952013-07-08 20:20:06 +00007946 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007947
George Burgess IVdf1ed002016-01-13 01:52:39 +00007948 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7949 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007950
John McCall70aa5392010-01-06 05:24:50 +00007951 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007952 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007953 return OutputTypeRange;
7954
7955 IntRange SubRange
7956 = GetExprRange(C, CE->getSubExpr(),
7957 std::min(MaxWidth, OutputTypeRange.Width));
7958
7959 // Bail out if the subexpr's range is as wide as the cast type.
7960 if (SubRange.Width >= OutputTypeRange.Width)
7961 return OutputTypeRange;
7962
7963 // Otherwise, we take the smaller width, and we're non-negative if
7964 // either the output type or the subexpr is.
7965 return IntRange(SubRange.Width,
7966 SubRange.NonNegative || OutputTypeRange.NonNegative);
7967 }
7968
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007969 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007970 // If we can fold the condition, just take that operand.
7971 bool CondResult;
7972 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7973 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7974 : CO->getFalseExpr(),
7975 MaxWidth);
7976
7977 // Otherwise, conservatively merge.
7978 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7979 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7980 return IntRange::join(L, R);
7981 }
7982
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007983 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007984 switch (BO->getOpcode()) {
7985
7986 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007987 case BO_LAnd:
7988 case BO_LOr:
7989 case BO_LT:
7990 case BO_GT:
7991 case BO_LE:
7992 case BO_GE:
7993 case BO_EQ:
7994 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007995 return IntRange::forBoolType();
7996
John McCallc3688382011-07-13 06:35:24 +00007997 // The type of the assignments is the type of the LHS, so the RHS
7998 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007999 case BO_MulAssign:
8000 case BO_DivAssign:
8001 case BO_RemAssign:
8002 case BO_AddAssign:
8003 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008004 case BO_XorAssign:
8005 case BO_OrAssign:
8006 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008007 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008008
John McCallc3688382011-07-13 06:35:24 +00008009 // Simple assignments just pass through the RHS, which will have
8010 // been coerced to the LHS type.
8011 case BO_Assign:
8012 // TODO: bitfields?
8013 return GetExprRange(C, BO->getRHS(), MaxWidth);
8014
John McCall70aa5392010-01-06 05:24:50 +00008015 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008016 case BO_PtrMemD:
8017 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008018 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008019
John McCall2ce81ad2010-01-06 22:07:33 +00008020 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008021 case BO_And:
8022 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008023 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8024 GetExprRange(C, BO->getRHS(), MaxWidth));
8025
John McCall70aa5392010-01-06 05:24:50 +00008026 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008027 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008028 // ...except that we want to treat '1 << (blah)' as logically
8029 // positive. It's an important idiom.
8030 if (IntegerLiteral *I
8031 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8032 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008033 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008034 return IntRange(R.Width, /*NonNegative*/ true);
8035 }
8036 }
8037 // fallthrough
8038
John McCalle3027922010-08-25 11:45:40 +00008039 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008040 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008041
John McCall2ce81ad2010-01-06 22:07:33 +00008042 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008043 case BO_Shr:
8044 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008045 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8046
8047 // If the shift amount is a positive constant, drop the width by
8048 // that much.
8049 llvm::APSInt shift;
8050 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8051 shift.isNonNegative()) {
8052 unsigned zext = shift.getZExtValue();
8053 if (zext >= L.Width)
8054 L.Width = (L.NonNegative ? 0 : 1);
8055 else
8056 L.Width -= zext;
8057 }
8058
8059 return L;
8060 }
8061
8062 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008063 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008064 return GetExprRange(C, BO->getRHS(), MaxWidth);
8065
John McCall2ce81ad2010-01-06 22:07:33 +00008066 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008067 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008068 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008069 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008070 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008071
John McCall51431812011-07-14 22:39:48 +00008072 // The width of a division result is mostly determined by the size
8073 // of the LHS.
8074 case BO_Div: {
8075 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008076 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008077 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8078
8079 // If the divisor is constant, use that.
8080 llvm::APSInt divisor;
8081 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8082 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8083 if (log2 >= L.Width)
8084 L.Width = (L.NonNegative ? 0 : 1);
8085 else
8086 L.Width = std::min(L.Width - log2, MaxWidth);
8087 return L;
8088 }
8089
8090 // Otherwise, just use the LHS's width.
8091 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8092 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8093 }
8094
8095 // The result of a remainder can't be larger than the result of
8096 // either side.
8097 case BO_Rem: {
8098 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008099 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008100 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8101 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8102
8103 IntRange meet = IntRange::meet(L, R);
8104 meet.Width = std::min(meet.Width, MaxWidth);
8105 return meet;
8106 }
8107
8108 // The default behavior is okay for these.
8109 case BO_Mul:
8110 case BO_Add:
8111 case BO_Xor:
8112 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008113 break;
8114 }
8115
John McCall51431812011-07-14 22:39:48 +00008116 // The default case is to treat the operation as if it were closed
8117 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008118 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8119 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8120 return IntRange::join(L, R);
8121 }
8122
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008123 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008124 switch (UO->getOpcode()) {
8125 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008126 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008127 return IntRange::forBoolType();
8128
8129 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008130 case UO_Deref:
8131 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008132 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008133
8134 default:
8135 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8136 }
8137 }
8138
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008140 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8141
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008142 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008143 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008144 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008145
Eli Friedmane6d33952013-07-08 20:20:06 +00008146 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008147}
John McCall263a48b2010-01-04 23:31:57 +00008148
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008149IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008150 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008151}
8152
John McCall263a48b2010-01-04 23:31:57 +00008153/// Checks whether the given value, which currently has the given
8154/// source semantics, has the same value when coerced through the
8155/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008156bool IsSameFloatAfterCast(const llvm::APFloat &value,
8157 const llvm::fltSemantics &Src,
8158 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008159 llvm::APFloat truncated = value;
8160
8161 bool ignored;
8162 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8163 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8164
8165 return truncated.bitwiseIsEqual(value);
8166}
8167
8168/// Checks whether the given value, which currently has the given
8169/// source semantics, has the same value when coerced through the
8170/// target semantics.
8171///
8172/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008173bool IsSameFloatAfterCast(const APValue &value,
8174 const llvm::fltSemantics &Src,
8175 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008176 if (value.isFloat())
8177 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8178
8179 if (value.isVector()) {
8180 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8181 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8182 return false;
8183 return true;
8184 }
8185
8186 assert(value.isComplexFloat());
8187 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8188 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8189}
8190
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008191void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008192
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008193bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008194 // Suppress cases where we are comparing against an enum constant.
8195 if (const DeclRefExpr *DR =
8196 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8197 if (isa<EnumConstantDecl>(DR->getDecl()))
8198 return false;
8199
8200 // Suppress cases where the '0' value is expanded from a macro.
8201 if (E->getLocStart().isMacroID())
8202 return false;
8203
John McCallcc7e5bf2010-05-06 08:58:33 +00008204 llvm::APSInt Value;
8205 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8206}
8207
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008208bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008209 // Strip off implicit integral promotions.
8210 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008211 if (ICE->getCastKind() != CK_IntegralCast &&
8212 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008213 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008214 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008215 }
8216
8217 return E->getType()->isEnumeralType();
8218}
8219
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008220void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008221 // Disable warning in template instantiations.
8222 if (!S.ActiveTemplateInstantiations.empty())
8223 return;
8224
John McCalle3027922010-08-25 11:45:40 +00008225 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008226 if (E->isValueDependent())
8227 return;
8228
John McCalle3027922010-08-25 11:45:40 +00008229 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008230 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008231 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008232 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008233 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008234 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008235 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008236 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008237 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008238 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008239 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008240 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008241 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008242 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008243 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008244 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8245 }
8246}
8247
Benjamin Kramer7320b992016-06-15 14:20:56 +00008248void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8249 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008250 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008251 // Disable warning in template instantiations.
8252 if (!S.ActiveTemplateInstantiations.empty())
8253 return;
8254
Richard Trieu0f097742014-04-04 04:13:47 +00008255 // TODO: Investigate using GetExprRange() to get tighter bounds
8256 // on the bit ranges.
8257 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008258 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008259 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008260 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8261 unsigned OtherWidth = OtherRange.Width;
8262
8263 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8264
Richard Trieu560910c2012-11-14 22:50:24 +00008265 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008266 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008267 return;
8268
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008269 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008270 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008271
Richard Trieu0f097742014-04-04 04:13:47 +00008272 // Used for diagnostic printout.
8273 enum {
8274 LiteralConstant = 0,
8275 CXXBoolLiteralTrue,
8276 CXXBoolLiteralFalse
8277 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008278
Richard Trieu0f097742014-04-04 04:13:47 +00008279 if (!OtherIsBooleanType) {
8280 QualType ConstantT = Constant->getType();
8281 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008282
Richard Trieu0f097742014-04-04 04:13:47 +00008283 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8284 return;
8285 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8286 "comparison with non-integer type");
8287
8288 bool ConstantSigned = ConstantT->isSignedIntegerType();
8289 bool CommonSigned = CommonT->isSignedIntegerType();
8290
8291 bool EqualityOnly = false;
8292
8293 if (CommonSigned) {
8294 // The common type is signed, therefore no signed to unsigned conversion.
8295 if (!OtherRange.NonNegative) {
8296 // Check that the constant is representable in type OtherT.
8297 if (ConstantSigned) {
8298 if (OtherWidth >= Value.getMinSignedBits())
8299 return;
8300 } else { // !ConstantSigned
8301 if (OtherWidth >= Value.getActiveBits() + 1)
8302 return;
8303 }
8304 } else { // !OtherSigned
8305 // Check that the constant is representable in type OtherT.
8306 // Negative values are out of range.
8307 if (ConstantSigned) {
8308 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8309 return;
8310 } else { // !ConstantSigned
8311 if (OtherWidth >= Value.getActiveBits())
8312 return;
8313 }
Richard Trieu560910c2012-11-14 22:50:24 +00008314 }
Richard Trieu0f097742014-04-04 04:13:47 +00008315 } else { // !CommonSigned
8316 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008317 if (OtherWidth >= Value.getActiveBits())
8318 return;
Craig Toppercf360162014-06-18 05:13:11 +00008319 } else { // OtherSigned
8320 assert(!ConstantSigned &&
8321 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008322 // Check to see if the constant is representable in OtherT.
8323 if (OtherWidth > Value.getActiveBits())
8324 return;
8325 // Check to see if the constant is equivalent to a negative value
8326 // cast to CommonT.
8327 if (S.Context.getIntWidth(ConstantT) ==
8328 S.Context.getIntWidth(CommonT) &&
8329 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8330 return;
8331 // The constant value rests between values that OtherT can represent
8332 // after conversion. Relational comparison still works, but equality
8333 // comparisons will be tautological.
8334 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008335 }
8336 }
Richard Trieu0f097742014-04-04 04:13:47 +00008337
8338 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8339
8340 if (op == BO_EQ || op == BO_NE) {
8341 IsTrue = op == BO_NE;
8342 } else if (EqualityOnly) {
8343 return;
8344 } else if (RhsConstant) {
8345 if (op == BO_GT || op == BO_GE)
8346 IsTrue = !PositiveConstant;
8347 else // op == BO_LT || op == BO_LE
8348 IsTrue = PositiveConstant;
8349 } else {
8350 if (op == BO_LT || op == BO_LE)
8351 IsTrue = !PositiveConstant;
8352 else // op == BO_GT || op == BO_GE
8353 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008354 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008355 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008356 // Other isKnownToHaveBooleanValue
8357 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8358 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8359 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8360
8361 static const struct LinkedConditions {
8362 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8363 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8364 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8365 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8366 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8367 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8368
8369 } TruthTable = {
8370 // Constant on LHS. | Constant on RHS. |
8371 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8372 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8373 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8374 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8375 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8376 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8377 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8378 };
8379
8380 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8381
8382 enum ConstantValue ConstVal = Zero;
8383 if (Value.isUnsigned() || Value.isNonNegative()) {
8384 if (Value == 0) {
8385 LiteralOrBoolConstant =
8386 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8387 ConstVal = Zero;
8388 } else if (Value == 1) {
8389 LiteralOrBoolConstant =
8390 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8391 ConstVal = One;
8392 } else {
8393 LiteralOrBoolConstant = LiteralConstant;
8394 ConstVal = GT_One;
8395 }
8396 } else {
8397 ConstVal = LT_Zero;
8398 }
8399
8400 CompareBoolWithConstantResult CmpRes;
8401
8402 switch (op) {
8403 case BO_LT:
8404 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8405 break;
8406 case BO_GT:
8407 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8408 break;
8409 case BO_LE:
8410 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8411 break;
8412 case BO_GE:
8413 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8414 break;
8415 case BO_EQ:
8416 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8417 break;
8418 case BO_NE:
8419 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8420 break;
8421 default:
8422 CmpRes = Unkwn;
8423 break;
8424 }
8425
8426 if (CmpRes == AFals) {
8427 IsTrue = false;
8428 } else if (CmpRes == ATrue) {
8429 IsTrue = true;
8430 } else {
8431 return;
8432 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008433 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008434
8435 // If this is a comparison to an enum constant, include that
8436 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008437 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008438 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8439 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8440
8441 SmallString<64> PrettySourceValue;
8442 llvm::raw_svector_ostream OS(PrettySourceValue);
8443 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008444 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008445 else
8446 OS << Value;
8447
Richard Trieu0f097742014-04-04 04:13:47 +00008448 S.DiagRuntimeBehavior(
8449 E->getOperatorLoc(), E,
8450 S.PDiag(diag::warn_out_of_range_compare)
8451 << OS.str() << LiteralOrBoolConstant
8452 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8453 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008454}
8455
John McCallcc7e5bf2010-05-06 08:58:33 +00008456/// Analyze the operands of the given comparison. Implements the
8457/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008458void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008459 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8460 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008461}
John McCall263a48b2010-01-04 23:31:57 +00008462
John McCallca01b222010-01-04 23:21:16 +00008463/// \brief Implements -Wsign-compare.
8464///
Richard Trieu82402a02011-09-15 21:56:47 +00008465/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008466void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008467 // The type the comparison is being performed in.
8468 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008469
8470 // Only analyze comparison operators where both sides have been converted to
8471 // the same type.
8472 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8473 return AnalyzeImpConvsInComparison(S, E);
8474
8475 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008476 if (E->isValueDependent())
8477 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008478
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008479 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8480 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008481
8482 bool IsComparisonConstant = false;
8483
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008484 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008485 // of 'true' or 'false'.
8486 if (T->isIntegralType(S.Context)) {
8487 llvm::APSInt RHSValue;
8488 bool IsRHSIntegralLiteral =
8489 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8490 llvm::APSInt LHSValue;
8491 bool IsLHSIntegralLiteral =
8492 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8493 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8494 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8495 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8496 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8497 else
8498 IsComparisonConstant =
8499 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008500 } else if (!T->hasUnsignedIntegerRepresentation())
8501 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008502
John McCallcc7e5bf2010-05-06 08:58:33 +00008503 // We don't do anything special if this isn't an unsigned integral
8504 // comparison: we're only interested in integral comparisons, and
8505 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008506 //
8507 // We also don't care about value-dependent expressions or expressions
8508 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008509 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008510 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008511
John McCallcc7e5bf2010-05-06 08:58:33 +00008512 // Check to see if one of the (unmodified) operands is of different
8513 // signedness.
8514 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008515 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8516 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008517 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008518 signedOperand = LHS;
8519 unsignedOperand = RHS;
8520 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8521 signedOperand = RHS;
8522 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008523 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008524 CheckTrivialUnsignedComparison(S, E);
8525 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008526 }
8527
John McCallcc7e5bf2010-05-06 08:58:33 +00008528 // Otherwise, calculate the effective range of the signed operand.
8529 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008530
John McCallcc7e5bf2010-05-06 08:58:33 +00008531 // Go ahead and analyze implicit conversions in the operands. Note
8532 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008533 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8534 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008535
John McCallcc7e5bf2010-05-06 08:58:33 +00008536 // If the signed range is non-negative, -Wsign-compare won't fire,
8537 // but we should still check for comparisons which are always true
8538 // or false.
8539 if (signedRange.NonNegative)
8540 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008541
8542 // For (in)equality comparisons, if the unsigned operand is a
8543 // constant which cannot collide with a overflowed signed operand,
8544 // then reinterpreting the signed operand as unsigned will not
8545 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008546 if (E->isEqualityOp()) {
8547 unsigned comparisonWidth = S.Context.getIntWidth(T);
8548 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008549
John McCallcc7e5bf2010-05-06 08:58:33 +00008550 // We should never be unable to prove that the unsigned operand is
8551 // non-negative.
8552 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8553
8554 if (unsignedRange.Width < comparisonWidth)
8555 return;
8556 }
8557
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008558 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8559 S.PDiag(diag::warn_mixed_sign_comparison)
8560 << LHS->getType() << RHS->getType()
8561 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008562}
8563
John McCall1f425642010-11-11 03:21:53 +00008564/// Analyzes an attempt to assign the given value to a bitfield.
8565///
8566/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008567bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8568 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008569 assert(Bitfield->isBitField());
8570 if (Bitfield->isInvalidDecl())
8571 return false;
8572
John McCalldeebbcf2010-11-11 05:33:51 +00008573 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008574 QualType BitfieldType = Bitfield->getType();
8575 if (BitfieldType->isBooleanType())
8576 return false;
8577
8578 if (BitfieldType->isEnumeralType()) {
8579 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8580 // If the underlying enum type was not explicitly specified as an unsigned
8581 // type and the enum contain only positive values, MSVC++ will cause an
8582 // inconsistency by storing this as a signed type.
8583 if (S.getLangOpts().CPlusPlus11 &&
8584 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8585 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8586 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8587 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8588 << BitfieldEnumDecl->getNameAsString();
8589 }
8590 }
8591
John McCalldeebbcf2010-11-11 05:33:51 +00008592 if (Bitfield->getType()->isBooleanType())
8593 return false;
8594
Douglas Gregor789adec2011-02-04 13:09:01 +00008595 // Ignore value- or type-dependent expressions.
8596 if (Bitfield->getBitWidth()->isValueDependent() ||
8597 Bitfield->getBitWidth()->isTypeDependent() ||
8598 Init->isValueDependent() ||
8599 Init->isTypeDependent())
8600 return false;
8601
John McCall1f425642010-11-11 03:21:53 +00008602 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8603
Richard Smith5fab0c92011-12-28 19:48:30 +00008604 llvm::APSInt Value;
8605 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008606 return false;
8607
John McCall1f425642010-11-11 03:21:53 +00008608 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008609 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008610
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008611 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008612 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008613 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8614 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008615
John McCall1f425642010-11-11 03:21:53 +00008616 if (OriginalWidth <= FieldWidth)
8617 return false;
8618
Eli Friedmanc267a322012-01-26 23:11:39 +00008619 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008620 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008621 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008622
Eli Friedmanc267a322012-01-26 23:11:39 +00008623 // Check whether the stored value is equal to the original value.
8624 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008625 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008626 return false;
8627
Eli Friedmanc267a322012-01-26 23:11:39 +00008628 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008629 // therefore don't strictly fit into a signed bitfield of width 1.
8630 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008631 return false;
8632
John McCall1f425642010-11-11 03:21:53 +00008633 std::string PrettyValue = Value.toString(10);
8634 std::string PrettyTrunc = TruncatedValue.toString(10);
8635
8636 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8637 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8638 << Init->getSourceRange();
8639
8640 return true;
8641}
8642
John McCalld2a53122010-11-09 23:24:47 +00008643/// Analyze the given simple or compound assignment for warning-worthy
8644/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008645void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008646 // Just recurse on the LHS.
8647 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8648
8649 // We want to recurse on the RHS as normal unless we're assigning to
8650 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008651 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008652 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008653 E->getOperatorLoc())) {
8654 // Recurse, ignoring any implicit conversions on the RHS.
8655 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8656 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008657 }
8658 }
8659
8660 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8661}
8662
John McCall263a48b2010-01-04 23:31:57 +00008663/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008664void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8665 SourceLocation CContext, unsigned diag,
8666 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008667 if (pruneControlFlow) {
8668 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8669 S.PDiag(diag)
8670 << SourceType << T << E->getSourceRange()
8671 << SourceRange(CContext));
8672 return;
8673 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008674 S.Diag(E->getExprLoc(), diag)
8675 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8676}
8677
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008678/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008679void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8680 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008681 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008682}
8683
Richard Trieube234c32016-04-21 21:04:55 +00008684
8685/// Diagnose an implicit cast from a floating point value to an integer value.
8686void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8687
8688 SourceLocation CContext) {
8689 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8690 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8691
8692 Expr *InnerE = E->IgnoreParenImpCasts();
8693 // We also want to warn on, e.g., "int i = -1.234"
8694 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8695 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8696 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8697
8698 const bool IsLiteral =
8699 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8700
8701 llvm::APFloat Value(0.0);
8702 bool IsConstant =
8703 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8704 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008705 return DiagnoseImpCast(S, E, T, CContext,
8706 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008707 }
8708
Chandler Carruth016ef402011-04-10 08:36:24 +00008709 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008710
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008711 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8712 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008713 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8714 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008715 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008716 if (IsLiteral) return;
8717 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8718 PruneWarnings);
8719 }
8720
8721 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008722 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008723 // Warn on floating point literal to integer.
8724 DiagID = diag::warn_impcast_literal_float_to_integer;
8725 } else if (IntegerValue == 0) {
8726 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8727 return DiagnoseImpCast(S, E, T, CContext,
8728 diag::warn_impcast_float_integer, PruneWarnings);
8729 }
8730 // Warn on non-zero to zero conversion.
8731 DiagID = diag::warn_impcast_float_to_integer_zero;
8732 } else {
8733 if (IntegerValue.isUnsigned()) {
8734 if (!IntegerValue.isMaxValue()) {
8735 return DiagnoseImpCast(S, E, T, CContext,
8736 diag::warn_impcast_float_integer, PruneWarnings);
8737 }
8738 } else { // IntegerValue.isSigned()
8739 if (!IntegerValue.isMaxSignedValue() &&
8740 !IntegerValue.isMinSignedValue()) {
8741 return DiagnoseImpCast(S, E, T, CContext,
8742 diag::warn_impcast_float_integer, PruneWarnings);
8743 }
8744 }
8745 // Warn on evaluatable floating point expression to integer conversion.
8746 DiagID = diag::warn_impcast_float_to_integer;
8747 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008748
Eli Friedman07185912013-08-29 23:44:43 +00008749 // FIXME: Force the precision of the source value down so we don't print
8750 // digits which are usually useless (we don't really care here if we
8751 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8752 // would automatically print the shortest representation, but it's a bit
8753 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008754 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008755 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8756 precision = (precision * 59 + 195) / 196;
8757 Value.toString(PrettySourceValue, precision);
8758
David Blaikie9b88cc02012-05-15 17:18:27 +00008759 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008760 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008761 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008762 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008763 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008764
Richard Trieube234c32016-04-21 21:04:55 +00008765 if (PruneWarnings) {
8766 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8767 S.PDiag(DiagID)
8768 << E->getType() << T.getUnqualifiedType()
8769 << PrettySourceValue << PrettyTargetValue
8770 << E->getSourceRange() << SourceRange(CContext));
8771 } else {
8772 S.Diag(E->getExprLoc(), DiagID)
8773 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8774 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8775 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008776}
8777
John McCall18a2c2c2010-11-09 22:22:12 +00008778std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8779 if (!Range.Width) return "0";
8780
8781 llvm::APSInt ValueInRange = Value;
8782 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008783 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008784 return ValueInRange.toString(10);
8785}
8786
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008787bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008788 if (!isa<ImplicitCastExpr>(Ex))
8789 return false;
8790
8791 Expr *InnerE = Ex->IgnoreParenImpCasts();
8792 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8793 const Type *Source =
8794 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8795 if (Target->isDependentType())
8796 return false;
8797
8798 const BuiltinType *FloatCandidateBT =
8799 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8800 const Type *BoolCandidateType = ToBool ? Target : Source;
8801
8802 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8803 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8804}
8805
8806void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8807 SourceLocation CC) {
8808 unsigned NumArgs = TheCall->getNumArgs();
8809 for (unsigned i = 0; i < NumArgs; ++i) {
8810 Expr *CurrA = TheCall->getArg(i);
8811 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8812 continue;
8813
8814 bool IsSwapped = ((i > 0) &&
8815 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8816 IsSwapped |= ((i < (NumArgs - 1)) &&
8817 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8818 if (IsSwapped) {
8819 // Warn on this floating-point to bool conversion.
8820 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8821 CurrA->getType(), CC,
8822 diag::warn_impcast_floating_point_to_bool);
8823 }
8824 }
8825}
8826
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008827void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008828 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8829 E->getExprLoc()))
8830 return;
8831
Richard Trieu09d6b802016-01-08 23:35:06 +00008832 // Don't warn on functions which have return type nullptr_t.
8833 if (isa<CallExpr>(E))
8834 return;
8835
Richard Trieu5b993502014-10-15 03:42:06 +00008836 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8837 const Expr::NullPointerConstantKind NullKind =
8838 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8839 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8840 return;
8841
8842 // Return if target type is a safe conversion.
8843 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8844 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8845 return;
8846
8847 SourceLocation Loc = E->getSourceRange().getBegin();
8848
Richard Trieu0a5e1662016-02-13 00:58:53 +00008849 // Venture through the macro stacks to get to the source of macro arguments.
8850 // The new location is a better location than the complete location that was
8851 // passed in.
8852 while (S.SourceMgr.isMacroArgExpansion(Loc))
8853 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8854
8855 while (S.SourceMgr.isMacroArgExpansion(CC))
8856 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8857
Richard Trieu5b993502014-10-15 03:42:06 +00008858 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008859 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8860 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8861 Loc, S.SourceMgr, S.getLangOpts());
8862 if (MacroName == "NULL")
8863 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008864 }
8865
8866 // Only warn if the null and context location are in the same macro expansion.
8867 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8868 return;
8869
8870 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8871 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8872 << FixItHint::CreateReplacement(Loc,
8873 S.getFixItZeroLiteralForType(T, Loc));
8874}
8875
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008876void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8877 ObjCArrayLiteral *ArrayLiteral);
8878void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8879 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008880
8881/// Check a single element within a collection literal against the
8882/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008883void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8884 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008885 // Skip a bitcast to 'id' or qualified 'id'.
8886 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8887 if (ICE->getCastKind() == CK_BitCast &&
8888 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8889 Element = ICE->getSubExpr();
8890 }
8891
8892 QualType ElementType = Element->getType();
8893 ExprResult ElementResult(Element);
8894 if (ElementType->getAs<ObjCObjectPointerType>() &&
8895 S.CheckSingleAssignmentConstraints(TargetElementType,
8896 ElementResult,
8897 false, false)
8898 != Sema::Compatible) {
8899 S.Diag(Element->getLocStart(),
8900 diag::warn_objc_collection_literal_element)
8901 << ElementType << ElementKind << TargetElementType
8902 << Element->getSourceRange();
8903 }
8904
8905 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8906 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8907 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8908 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8909}
8910
8911/// Check an Objective-C array literal being converted to the given
8912/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008913void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8914 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008915 if (!S.NSArrayDecl)
8916 return;
8917
8918 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8919 if (!TargetObjCPtr)
8920 return;
8921
8922 if (TargetObjCPtr->isUnspecialized() ||
8923 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8924 != S.NSArrayDecl->getCanonicalDecl())
8925 return;
8926
8927 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8928 if (TypeArgs.size() != 1)
8929 return;
8930
8931 QualType TargetElementType = TypeArgs[0];
8932 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8933 checkObjCCollectionLiteralElement(S, TargetElementType,
8934 ArrayLiteral->getElement(I),
8935 0);
8936 }
8937}
8938
8939/// Check an Objective-C dictionary literal being converted to the given
8940/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008941void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8942 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008943 if (!S.NSDictionaryDecl)
8944 return;
8945
8946 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8947 if (!TargetObjCPtr)
8948 return;
8949
8950 if (TargetObjCPtr->isUnspecialized() ||
8951 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8952 != S.NSDictionaryDecl->getCanonicalDecl())
8953 return;
8954
8955 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8956 if (TypeArgs.size() != 2)
8957 return;
8958
8959 QualType TargetKeyType = TypeArgs[0];
8960 QualType TargetObjectType = TypeArgs[1];
8961 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8962 auto Element = DictionaryLiteral->getKeyValueElement(I);
8963 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8964 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8965 }
8966}
8967
Richard Trieufc404c72016-02-05 23:02:38 +00008968// Helper function to filter out cases for constant width constant conversion.
8969// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008970bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8971 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008972 // If initializing from a constant, and the constant starts with '0',
8973 // then it is a binary, octal, or hexadecimal. Allow these constants
8974 // to fill all the bits, even if there is a sign change.
8975 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8976 const char FirstLiteralCharacter =
8977 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8978 if (FirstLiteralCharacter == '0')
8979 return false;
8980 }
8981
8982 // If the CC location points to a '{', and the type is char, then assume
8983 // assume it is an array initialization.
8984 if (CC.isValid() && T->isCharType()) {
8985 const char FirstContextCharacter =
8986 S.getSourceManager().getCharacterData(CC)[0];
8987 if (FirstContextCharacter == '{')
8988 return false;
8989 }
8990
8991 return true;
8992}
8993
John McCallcc7e5bf2010-05-06 08:58:33 +00008994void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008995 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008996 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008997
John McCallcc7e5bf2010-05-06 08:58:33 +00008998 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8999 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9000 if (Source == Target) return;
9001 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009002
Chandler Carruthc22845a2011-07-26 05:40:03 +00009003 // If the conversion context location is invalid don't complain. We also
9004 // don't want to emit a warning if the issue occurs from the expansion of
9005 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9006 // delay this check as long as possible. Once we detect we are in that
9007 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009008 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009009 return;
9010
Richard Trieu021baa32011-09-23 20:10:00 +00009011 // Diagnose implicit casts to bool.
9012 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9013 if (isa<StringLiteral>(E))
9014 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009015 // and expressions, for instance, assert(0 && "error here"), are
9016 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009017 return DiagnoseImpCast(S, E, T, CC,
9018 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009019 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9020 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9021 // This covers the literal expressions that evaluate to Objective-C
9022 // objects.
9023 return DiagnoseImpCast(S, E, T, CC,
9024 diag::warn_impcast_objective_c_literal_to_bool);
9025 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009026 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9027 // Warn on pointer to bool conversion that is always true.
9028 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9029 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009030 }
Richard Trieu021baa32011-09-23 20:10:00 +00009031 }
John McCall263a48b2010-01-04 23:31:57 +00009032
Douglas Gregor5054cb02015-07-07 03:58:22 +00009033 // Check implicit casts from Objective-C collection literals to specialized
9034 // collection types, e.g., NSArray<NSString *> *.
9035 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9036 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9037 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9038 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9039
John McCall263a48b2010-01-04 23:31:57 +00009040 // Strip vector types.
9041 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009042 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009043 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009044 return;
John McCallacf0ee52010-10-08 02:01:28 +00009045 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009046 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009047
9048 // If the vector cast is cast between two vectors of the same size, it is
9049 // a bitcast, not a conversion.
9050 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9051 return;
John McCall263a48b2010-01-04 23:31:57 +00009052
9053 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9054 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9055 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009056 if (auto VecTy = dyn_cast<VectorType>(Target))
9057 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009058
9059 // Strip complex types.
9060 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009061 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009062 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009063 return;
9064
John McCallacf0ee52010-10-08 02:01:28 +00009065 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009066 }
John McCall263a48b2010-01-04 23:31:57 +00009067
9068 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9069 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9070 }
9071
9072 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9073 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9074
9075 // If the source is floating point...
9076 if (SourceBT && SourceBT->isFloatingPoint()) {
9077 // ...and the target is floating point...
9078 if (TargetBT && TargetBT->isFloatingPoint()) {
9079 // ...then warn if we're dropping FP rank.
9080
9081 // Builtin FP kinds are ordered by increasing FP rank.
9082 if (SourceBT->getKind() > TargetBT->getKind()) {
9083 // Don't warn about float constants that are precisely
9084 // representable in the target type.
9085 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009086 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009087 // Value might be a float, a float vector, or a float complex.
9088 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009089 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9090 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009091 return;
9092 }
9093
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009094 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009095 return;
9096
John McCallacf0ee52010-10-08 02:01:28 +00009097 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009098 }
9099 // ... or possibly if we're increasing rank, too
9100 else if (TargetBT->getKind() > SourceBT->getKind()) {
9101 if (S.SourceMgr.isInSystemMacro(CC))
9102 return;
9103
9104 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009105 }
9106 return;
9107 }
9108
Richard Trieube234c32016-04-21 21:04:55 +00009109 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009110 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009111 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009112 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009113
Richard Trieube234c32016-04-21 21:04:55 +00009114 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009115 }
John McCall263a48b2010-01-04 23:31:57 +00009116
Richard Smith54894fd2015-12-30 01:06:52 +00009117 // Detect the case where a call result is converted from floating-point to
9118 // to bool, and the final argument to the call is converted from bool, to
9119 // discover this typo:
9120 //
9121 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9122 //
9123 // FIXME: This is an incredibly special case; is there some more general
9124 // way to detect this class of misplaced-parentheses bug?
9125 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009126 // Check last argument of function call to see if it is an
9127 // implicit cast from a type matching the type the result
9128 // is being cast to.
9129 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009130 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009131 Expr *LastA = CEx->getArg(NumArgs - 1);
9132 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009133 if (isa<ImplicitCastExpr>(LastA) &&
9134 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009135 // Warn on this floating-point to bool conversion
9136 DiagnoseImpCast(S, E, T, CC,
9137 diag::warn_impcast_floating_point_to_bool);
9138 }
9139 }
9140 }
John McCall263a48b2010-01-04 23:31:57 +00009141 return;
9142 }
9143
Richard Trieu5b993502014-10-15 03:42:06 +00009144 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009145
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009146 S.DiscardMisalignedMemberAddress(Target, E);
9147
David Blaikie9366d2b2012-06-19 21:19:06 +00009148 if (!Source->isIntegerType() || !Target->isIntegerType())
9149 return;
9150
David Blaikie7555b6a2012-05-15 16:56:36 +00009151 // TODO: remove this early return once the false positives for constant->bool
9152 // in templates, macros, etc, are reduced or removed.
9153 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9154 return;
9155
John McCallcc7e5bf2010-05-06 08:58:33 +00009156 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009157 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009158
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009159 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009160 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009161 // TODO: this should happen for bitfield stores, too.
9162 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009163 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009164 if (S.SourceMgr.isInSystemMacro(CC))
9165 return;
9166
John McCall18a2c2c2010-11-09 22:22:12 +00009167 std::string PrettySourceValue = Value.toString(10);
9168 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009169
Ted Kremenek33ba9952011-10-22 02:37:33 +00009170 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9171 S.PDiag(diag::warn_impcast_integer_precision_constant)
9172 << PrettySourceValue << PrettyTargetValue
9173 << E->getType() << T << E->getSourceRange()
9174 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009175 return;
9176 }
9177
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009178 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9179 if (S.SourceMgr.isInSystemMacro(CC))
9180 return;
9181
David Blaikie9455da02012-04-12 22:40:54 +00009182 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009183 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9184 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009185 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009186 }
9187
Richard Trieudcb55572016-01-29 23:51:16 +00009188 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9189 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9190 // Warn when doing a signed to signed conversion, warn if the positive
9191 // source value is exactly the width of the target type, which will
9192 // cause a negative value to be stored.
9193
9194 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009195 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9196 !S.SourceMgr.isInSystemMacro(CC)) {
9197 if (isSameWidthConstantConversion(S, E, T, CC)) {
9198 std::string PrettySourceValue = Value.toString(10);
9199 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009200
Richard Trieufc404c72016-02-05 23:02:38 +00009201 S.DiagRuntimeBehavior(
9202 E->getExprLoc(), E,
9203 S.PDiag(diag::warn_impcast_integer_precision_constant)
9204 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9205 << E->getSourceRange() << clang::SourceRange(CC));
9206 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009207 }
9208 }
Richard Trieufc404c72016-02-05 23:02:38 +00009209
Richard Trieudcb55572016-01-29 23:51:16 +00009210 // Fall through for non-constants to give a sign conversion warning.
9211 }
9212
John McCallcc7e5bf2010-05-06 08:58:33 +00009213 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9214 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9215 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009216 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009217 return;
9218
John McCallcc7e5bf2010-05-06 08:58:33 +00009219 unsigned DiagID = diag::warn_impcast_integer_sign;
9220
9221 // Traditionally, gcc has warned about this under -Wsign-compare.
9222 // We also want to warn about it in -Wconversion.
9223 // So if -Wconversion is off, use a completely identical diagnostic
9224 // in the sign-compare group.
9225 // The conditional-checking code will
9226 if (ICContext) {
9227 DiagID = diag::warn_impcast_integer_sign_conditional;
9228 *ICContext = true;
9229 }
9230
John McCallacf0ee52010-10-08 02:01:28 +00009231 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009232 }
9233
Douglas Gregora78f1932011-02-22 02:45:07 +00009234 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009235 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9236 // type, to give us better diagnostics.
9237 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009238 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009239 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9240 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9241 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9242 SourceType = S.Context.getTypeDeclType(Enum);
9243 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9244 }
9245 }
9246
Douglas Gregora78f1932011-02-22 02:45:07 +00009247 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9248 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009249 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9250 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009251 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009252 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009253 return;
9254
Douglas Gregor364f7db2011-03-12 00:14:31 +00009255 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009256 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009257 }
John McCall263a48b2010-01-04 23:31:57 +00009258}
9259
David Blaikie18e9ac72012-05-15 21:57:38 +00009260void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9261 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009262
9263void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009264 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009265 E = E->IgnoreParenImpCasts();
9266
9267 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009268 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009269
John McCallacf0ee52010-10-08 02:01:28 +00009270 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009271 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009272 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009273}
9274
David Blaikie18e9ac72012-05-15 21:57:38 +00009275void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9276 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009277 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009278
9279 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009280 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9281 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009282
9283 // If -Wconversion would have warned about either of the candidates
9284 // for a signedness conversion to the context type...
9285 if (!Suspicious) return;
9286
9287 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009288 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009289 return;
9290
John McCallcc7e5bf2010-05-06 08:58:33 +00009291 // ...then check whether it would have warned about either of the
9292 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009293 if (E->getType() == T) return;
9294
9295 Suspicious = false;
9296 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9297 E->getType(), CC, &Suspicious);
9298 if (!Suspicious)
9299 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009300 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009301}
9302
Richard Trieu65724892014-11-15 06:37:39 +00009303/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9304/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009305void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009306 if (S.getLangOpts().Bool)
9307 return;
9308 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9309}
9310
John McCallcc7e5bf2010-05-06 08:58:33 +00009311/// AnalyzeImplicitConversions - Find and report any interesting
9312/// implicit conversions in the given expression. There are a couple
9313/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009314void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009315 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009316 Expr *E = OrigE->IgnoreParenImpCasts();
9317
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009318 if (E->isTypeDependent() || E->isValueDependent())
9319 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009320
John McCallcc7e5bf2010-05-06 08:58:33 +00009321 // For conditional operators, we analyze the arguments as if they
9322 // were being fed directly into the output.
9323 if (isa<ConditionalOperator>(E)) {
9324 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009325 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009326 return;
9327 }
9328
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009329 // Check implicit argument conversions for function calls.
9330 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9331 CheckImplicitArgumentConversions(S, Call, CC);
9332
John McCallcc7e5bf2010-05-06 08:58:33 +00009333 // Go ahead and check any implicit conversions we might have skipped.
9334 // The non-canonical typecheck is just an optimization;
9335 // CheckImplicitConversion will filter out dead implicit conversions.
9336 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009337 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009338
9339 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009340
9341 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9342 // The bound subexpressions in a PseudoObjectExpr are not reachable
9343 // as transitive children.
9344 // FIXME: Use a more uniform representation for this.
9345 for (auto *SE : POE->semantics())
9346 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9347 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009348 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009349
John McCallcc7e5bf2010-05-06 08:58:33 +00009350 // Skip past explicit casts.
9351 if (isa<ExplicitCastExpr>(E)) {
9352 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009353 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009354 }
9355
John McCalld2a53122010-11-09 23:24:47 +00009356 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9357 // Do a somewhat different check with comparison operators.
9358 if (BO->isComparisonOp())
9359 return AnalyzeComparison(S, BO);
9360
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009361 // And with simple assignments.
9362 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009363 return AnalyzeAssignment(S, BO);
9364 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009365
9366 // These break the otherwise-useful invariant below. Fortunately,
9367 // we don't really need to recurse into them, because any internal
9368 // expressions should have been analyzed already when they were
9369 // built into statements.
9370 if (isa<StmtExpr>(E)) return;
9371
9372 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009373 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009374
9375 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009376 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009377 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009378 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009379 for (Stmt *SubStmt : E->children()) {
9380 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009381 if (!ChildExpr)
9382 continue;
9383
Richard Trieu955231d2014-01-25 01:10:35 +00009384 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009385 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009386 // Ignore checking string literals that are in logical and operators.
9387 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009388 continue;
9389 AnalyzeImplicitConversions(S, ChildExpr, CC);
9390 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009391
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009392 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009393 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9394 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009395 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009396
9397 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9398 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009399 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009400 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009401
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009402 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9403 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009404 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009405}
9406
9407} // end anonymous namespace
9408
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009409/// Diagnose integer type and any valid implicit convertion to it.
9410static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9411 // Taking into account implicit conversions,
9412 // allow any integer.
9413 if (!E->getType()->isIntegerType()) {
9414 S.Diag(E->getLocStart(),
9415 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9416 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009417 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009418 // Potentially emit standard warnings for implicit conversions if enabled
9419 // using -Wconversion.
9420 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9421 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009422}
9423
Richard Trieuc1888e02014-06-28 23:25:37 +00009424// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9425// Returns true when emitting a warning about taking the address of a reference.
9426static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009427 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009428 E = E->IgnoreParenImpCasts();
9429
9430 const FunctionDecl *FD = nullptr;
9431
9432 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9433 if (!DRE->getDecl()->getType()->isReferenceType())
9434 return false;
9435 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9436 if (!M->getMemberDecl()->getType()->isReferenceType())
9437 return false;
9438 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009439 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009440 return false;
9441 FD = Call->getDirectCallee();
9442 } else {
9443 return false;
9444 }
9445
9446 SemaRef.Diag(E->getExprLoc(), PD);
9447
9448 // If possible, point to location of function.
9449 if (FD) {
9450 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9451 }
9452
9453 return true;
9454}
9455
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009456// Returns true if the SourceLocation is expanded from any macro body.
9457// Returns false if the SourceLocation is invalid, is from not in a macro
9458// expansion, or is from expanded from a top-level macro argument.
9459static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9460 if (Loc.isInvalid())
9461 return false;
9462
9463 while (Loc.isMacroID()) {
9464 if (SM.isMacroBodyExpansion(Loc))
9465 return true;
9466 Loc = SM.getImmediateMacroCallerLoc(Loc);
9467 }
9468
9469 return false;
9470}
9471
Richard Trieu3bb8b562014-02-26 02:36:06 +00009472/// \brief Diagnose pointers that are always non-null.
9473/// \param E the expression containing the pointer
9474/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9475/// compared to a null pointer
9476/// \param IsEqual True when the comparison is equal to a null pointer
9477/// \param Range Extra SourceRange to highlight in the diagnostic
9478void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9479 Expr::NullPointerConstantKind NullKind,
9480 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009481 if (!E)
9482 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009483
9484 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009485 if (E->getExprLoc().isMacroID()) {
9486 const SourceManager &SM = getSourceManager();
9487 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9488 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009489 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009490 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009491 E = E->IgnoreImpCasts();
9492
9493 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9494
Richard Trieuf7432752014-06-06 21:39:26 +00009495 if (isa<CXXThisExpr>(E)) {
9496 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9497 : diag::warn_this_bool_conversion;
9498 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9499 return;
9500 }
9501
Richard Trieu3bb8b562014-02-26 02:36:06 +00009502 bool IsAddressOf = false;
9503
9504 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9505 if (UO->getOpcode() != UO_AddrOf)
9506 return;
9507 IsAddressOf = true;
9508 E = UO->getSubExpr();
9509 }
9510
Richard Trieuc1888e02014-06-28 23:25:37 +00009511 if (IsAddressOf) {
9512 unsigned DiagID = IsCompare
9513 ? diag::warn_address_of_reference_null_compare
9514 : diag::warn_address_of_reference_bool_conversion;
9515 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9516 << IsEqual;
9517 if (CheckForReference(*this, E, PD)) {
9518 return;
9519 }
9520 }
9521
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009522 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9523 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009524 std::string Str;
9525 llvm::raw_string_ostream S(Str);
9526 E->printPretty(S, nullptr, getPrintingPolicy());
9527 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9528 : diag::warn_cast_nonnull_to_bool;
9529 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9530 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009531 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009532 };
9533
9534 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9535 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9536 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009537 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9538 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009539 return;
9540 }
9541 }
9542 }
9543
Richard Trieu3bb8b562014-02-26 02:36:06 +00009544 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009545 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009546 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9547 D = R->getDecl();
9548 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9549 D = M->getMemberDecl();
9550 }
9551
9552 // Weak Decls can be null.
9553 if (!D || D->isWeak())
9554 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009555
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009556 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009557 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9558 if (getCurFunction() &&
9559 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009560 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9561 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009562 return;
9563 }
9564
9565 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009566 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009567 assert(ParamIter != FD->param_end());
9568 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9569
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009570 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9571 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009572 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009573 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009574 }
George Burgess IV850269a2015-12-08 22:02:00 +00009575
9576 for (unsigned ArgNo : NonNull->args()) {
9577 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009578 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009579 return;
9580 }
George Burgess IV850269a2015-12-08 22:02:00 +00009581 }
9582 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009583 }
9584 }
George Burgess IV850269a2015-12-08 22:02:00 +00009585 }
9586
Richard Trieu3bb8b562014-02-26 02:36:06 +00009587 QualType T = D->getType();
9588 const bool IsArray = T->isArrayType();
9589 const bool IsFunction = T->isFunctionType();
9590
Richard Trieuc1888e02014-06-28 23:25:37 +00009591 // Address of function is used to silence the function warning.
9592 if (IsAddressOf && IsFunction) {
9593 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009594 }
9595
9596 // Found nothing.
9597 if (!IsAddressOf && !IsFunction && !IsArray)
9598 return;
9599
9600 // Pretty print the expression for the diagnostic.
9601 std::string Str;
9602 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009603 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009604
9605 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9606 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009607 enum {
9608 AddressOf,
9609 FunctionPointer,
9610 ArrayPointer
9611 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009612 if (IsAddressOf)
9613 DiagType = AddressOf;
9614 else if (IsFunction)
9615 DiagType = FunctionPointer;
9616 else if (IsArray)
9617 DiagType = ArrayPointer;
9618 else
9619 llvm_unreachable("Could not determine diagnostic.");
9620 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9621 << Range << IsEqual;
9622
9623 if (!IsFunction)
9624 return;
9625
9626 // Suggest '&' to silence the function warning.
9627 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9628 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9629
9630 // Check to see if '()' fixit should be emitted.
9631 QualType ReturnType;
9632 UnresolvedSet<4> NonTemplateOverloads;
9633 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9634 if (ReturnType.isNull())
9635 return;
9636
9637 if (IsCompare) {
9638 // There are two cases here. If there is null constant, the only suggest
9639 // for a pointer return type. If the null is 0, then suggest if the return
9640 // type is a pointer or an integer type.
9641 if (!ReturnType->isPointerType()) {
9642 if (NullKind == Expr::NPCK_ZeroExpression ||
9643 NullKind == Expr::NPCK_ZeroLiteral) {
9644 if (!ReturnType->isIntegerType())
9645 return;
9646 } else {
9647 return;
9648 }
9649 }
9650 } else { // !IsCompare
9651 // For function to bool, only suggest if the function pointer has bool
9652 // return type.
9653 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9654 return;
9655 }
9656 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009657 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009658}
9659
John McCallcc7e5bf2010-05-06 08:58:33 +00009660/// Diagnoses "dangerous" implicit conversions within the given
9661/// expression (which is a full expression). Implements -Wconversion
9662/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009663///
9664/// \param CC the "context" location of the implicit conversion, i.e.
9665/// the most location of the syntactic entity requiring the implicit
9666/// conversion
9667void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009668 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009669 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009670 return;
9671
9672 // Don't diagnose for value- or type-dependent expressions.
9673 if (E->isTypeDependent() || E->isValueDependent())
9674 return;
9675
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009676 // Check for array bounds violations in cases where the check isn't triggered
9677 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9678 // ArraySubscriptExpr is on the RHS of a variable initialization.
9679 CheckArrayAccess(E);
9680
John McCallacf0ee52010-10-08 02:01:28 +00009681 // This is not the right CC for (e.g.) a variable initialization.
9682 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009683}
9684
Richard Trieu65724892014-11-15 06:37:39 +00009685/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9686/// Input argument E is a logical expression.
9687void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9688 ::CheckBoolLikeConversion(*this, E, CC);
9689}
9690
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009691/// Diagnose when expression is an integer constant expression and its evaluation
9692/// results in integer overflow
9693void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009694 // Use a work list to deal with nested struct initializers.
9695 SmallVector<Expr *, 2> Exprs(1, E);
9696
9697 do {
9698 Expr *E = Exprs.pop_back_val();
9699
9700 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9701 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9702 continue;
9703 }
9704
9705 if (auto InitList = dyn_cast<InitListExpr>(E))
9706 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9707 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009708}
9709
Richard Smithc406cb72013-01-17 01:17:56 +00009710namespace {
9711/// \brief Visitor for expressions which looks for unsequenced operations on the
9712/// same object.
9713class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009714 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9715
Richard Smithc406cb72013-01-17 01:17:56 +00009716 /// \brief A tree of sequenced regions within an expression. Two regions are
9717 /// unsequenced if one is an ancestor or a descendent of the other. When we
9718 /// finish processing an expression with sequencing, such as a comma
9719 /// expression, we fold its tree nodes into its parent, since they are
9720 /// unsequenced with respect to nodes we will visit later.
9721 class SequenceTree {
9722 struct Value {
9723 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9724 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009725 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009726 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009727 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009728
9729 public:
9730 /// \brief A region within an expression which may be sequenced with respect
9731 /// to some other region.
9732 class Seq {
9733 explicit Seq(unsigned N) : Index(N) {}
9734 unsigned Index;
9735 friend class SequenceTree;
9736 public:
9737 Seq() : Index(0) {}
9738 };
9739
9740 SequenceTree() { Values.push_back(Value(0)); }
9741 Seq root() const { return Seq(0); }
9742
9743 /// \brief Create a new sequence of operations, which is an unsequenced
9744 /// subset of \p Parent. This sequence of operations is sequenced with
9745 /// respect to other children of \p Parent.
9746 Seq allocate(Seq Parent) {
9747 Values.push_back(Value(Parent.Index));
9748 return Seq(Values.size() - 1);
9749 }
9750
9751 /// \brief Merge a sequence of operations into its parent.
9752 void merge(Seq S) {
9753 Values[S.Index].Merged = true;
9754 }
9755
9756 /// \brief Determine whether two operations are unsequenced. This operation
9757 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9758 /// should have been merged into its parent as appropriate.
9759 bool isUnsequenced(Seq Cur, Seq Old) {
9760 unsigned C = representative(Cur.Index);
9761 unsigned Target = representative(Old.Index);
9762 while (C >= Target) {
9763 if (C == Target)
9764 return true;
9765 C = Values[C].Parent;
9766 }
9767 return false;
9768 }
9769
9770 private:
9771 /// \brief Pick a representative for a sequence.
9772 unsigned representative(unsigned K) {
9773 if (Values[K].Merged)
9774 // Perform path compression as we go.
9775 return Values[K].Parent = representative(Values[K].Parent);
9776 return K;
9777 }
9778 };
9779
9780 /// An object for which we can track unsequenced uses.
9781 typedef NamedDecl *Object;
9782
9783 /// Different flavors of object usage which we track. We only track the
9784 /// least-sequenced usage of each kind.
9785 enum UsageKind {
9786 /// A read of an object. Multiple unsequenced reads are OK.
9787 UK_Use,
9788 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009789 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009790 UK_ModAsValue,
9791 /// A modification of an object which is not sequenced before the value
9792 /// computation of the expression, such as n++.
9793 UK_ModAsSideEffect,
9794
9795 UK_Count = UK_ModAsSideEffect + 1
9796 };
9797
9798 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009799 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009800 Expr *Use;
9801 SequenceTree::Seq Seq;
9802 };
9803
9804 struct UsageInfo {
9805 UsageInfo() : Diagnosed(false) {}
9806 Usage Uses[UK_Count];
9807 /// Have we issued a diagnostic for this variable already?
9808 bool Diagnosed;
9809 };
9810 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9811
9812 Sema &SemaRef;
9813 /// Sequenced regions within the expression.
9814 SequenceTree Tree;
9815 /// Declaration modifications and references which we have seen.
9816 UsageInfoMap UsageMap;
9817 /// The region we are currently within.
9818 SequenceTree::Seq Region;
9819 /// Filled in with declarations which were modified as a side-effect
9820 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009821 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009822 /// Expressions to check later. We defer checking these to reduce
9823 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009824 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009825
9826 /// RAII object wrapping the visitation of a sequenced subexpression of an
9827 /// expression. At the end of this process, the side-effects of the evaluation
9828 /// become sequenced with respect to the value computation of the result, so
9829 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9830 /// UK_ModAsValue.
9831 struct SequencedSubexpression {
9832 SequencedSubexpression(SequenceChecker &Self)
9833 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9834 Self.ModAsSideEffect = &ModAsSideEffect;
9835 }
9836 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009837 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9838 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009839 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009840 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9841 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009842 }
9843 Self.ModAsSideEffect = OldModAsSideEffect;
9844 }
9845
9846 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009847 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9848 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009849 };
9850
Richard Smith40238f02013-06-20 22:21:56 +00009851 /// RAII object wrapping the visitation of a subexpression which we might
9852 /// choose to evaluate as a constant. If any subexpression is evaluated and
9853 /// found to be non-constant, this allows us to suppress the evaluation of
9854 /// the outer expression.
9855 class EvaluationTracker {
9856 public:
9857 EvaluationTracker(SequenceChecker &Self)
9858 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9859 Self.EvalTracker = this;
9860 }
9861 ~EvaluationTracker() {
9862 Self.EvalTracker = Prev;
9863 if (Prev)
9864 Prev->EvalOK &= EvalOK;
9865 }
9866
9867 bool evaluate(const Expr *E, bool &Result) {
9868 if (!EvalOK || E->isValueDependent())
9869 return false;
9870 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9871 return EvalOK;
9872 }
9873
9874 private:
9875 SequenceChecker &Self;
9876 EvaluationTracker *Prev;
9877 bool EvalOK;
9878 } *EvalTracker;
9879
Richard Smithc406cb72013-01-17 01:17:56 +00009880 /// \brief Find the object which is produced by the specified expression,
9881 /// if any.
9882 Object getObject(Expr *E, bool Mod) const {
9883 E = E->IgnoreParenCasts();
9884 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9885 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9886 return getObject(UO->getSubExpr(), Mod);
9887 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9888 if (BO->getOpcode() == BO_Comma)
9889 return getObject(BO->getRHS(), Mod);
9890 if (Mod && BO->isAssignmentOp())
9891 return getObject(BO->getLHS(), Mod);
9892 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9893 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9894 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9895 return ME->getMemberDecl();
9896 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9897 // FIXME: If this is a reference, map through to its value.
9898 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009899 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009900 }
9901
9902 /// \brief Note that an object was modified or used by an expression.
9903 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9904 Usage &U = UI.Uses[UK];
9905 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9906 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9907 ModAsSideEffect->push_back(std::make_pair(O, U));
9908 U.Use = Ref;
9909 U.Seq = Region;
9910 }
9911 }
9912 /// \brief Check whether a modification or use conflicts with a prior usage.
9913 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9914 bool IsModMod) {
9915 if (UI.Diagnosed)
9916 return;
9917
9918 const Usage &U = UI.Uses[OtherKind];
9919 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9920 return;
9921
9922 Expr *Mod = U.Use;
9923 Expr *ModOrUse = Ref;
9924 if (OtherKind == UK_Use)
9925 std::swap(Mod, ModOrUse);
9926
9927 SemaRef.Diag(Mod->getExprLoc(),
9928 IsModMod ? diag::warn_unsequenced_mod_mod
9929 : diag::warn_unsequenced_mod_use)
9930 << O << SourceRange(ModOrUse->getExprLoc());
9931 UI.Diagnosed = true;
9932 }
9933
9934 void notePreUse(Object O, Expr *Use) {
9935 UsageInfo &U = UsageMap[O];
9936 // Uses conflict with other modifications.
9937 checkUsage(O, U, Use, UK_ModAsValue, false);
9938 }
9939 void notePostUse(Object O, Expr *Use) {
9940 UsageInfo &U = UsageMap[O];
9941 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9942 addUsage(U, O, Use, UK_Use);
9943 }
9944
9945 void notePreMod(Object O, Expr *Mod) {
9946 UsageInfo &U = UsageMap[O];
9947 // Modifications conflict with other modifications and with uses.
9948 checkUsage(O, U, Mod, UK_ModAsValue, true);
9949 checkUsage(O, U, Mod, UK_Use, false);
9950 }
9951 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9952 UsageInfo &U = UsageMap[O];
9953 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9954 addUsage(U, O, Use, UK);
9955 }
9956
9957public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009958 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009959 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9960 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009961 Visit(E);
9962 }
9963
9964 void VisitStmt(Stmt *S) {
9965 // Skip all statements which aren't expressions for now.
9966 }
9967
9968 void VisitExpr(Expr *E) {
9969 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009970 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009971 }
9972
9973 void VisitCastExpr(CastExpr *E) {
9974 Object O = Object();
9975 if (E->getCastKind() == CK_LValueToRValue)
9976 O = getObject(E->getSubExpr(), false);
9977
9978 if (O)
9979 notePreUse(O, E);
9980 VisitExpr(E);
9981 if (O)
9982 notePostUse(O, E);
9983 }
9984
9985 void VisitBinComma(BinaryOperator *BO) {
9986 // C++11 [expr.comma]p1:
9987 // Every value computation and side effect associated with the left
9988 // expression is sequenced before every value computation and side
9989 // effect associated with the right expression.
9990 SequenceTree::Seq LHS = Tree.allocate(Region);
9991 SequenceTree::Seq RHS = Tree.allocate(Region);
9992 SequenceTree::Seq OldRegion = Region;
9993
9994 {
9995 SequencedSubexpression SeqLHS(*this);
9996 Region = LHS;
9997 Visit(BO->getLHS());
9998 }
9999
10000 Region = RHS;
10001 Visit(BO->getRHS());
10002
10003 Region = OldRegion;
10004
10005 // Forget that LHS and RHS are sequenced. They are both unsequenced
10006 // with respect to other stuff.
10007 Tree.merge(LHS);
10008 Tree.merge(RHS);
10009 }
10010
10011 void VisitBinAssign(BinaryOperator *BO) {
10012 // The modification is sequenced after the value computation of the LHS
10013 // and RHS, so check it before inspecting the operands and update the
10014 // map afterwards.
10015 Object O = getObject(BO->getLHS(), true);
10016 if (!O)
10017 return VisitExpr(BO);
10018
10019 notePreMod(O, BO);
10020
10021 // C++11 [expr.ass]p7:
10022 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10023 // only once.
10024 //
10025 // Therefore, for a compound assignment operator, O is considered used
10026 // everywhere except within the evaluation of E1 itself.
10027 if (isa<CompoundAssignOperator>(BO))
10028 notePreUse(O, BO);
10029
10030 Visit(BO->getLHS());
10031
10032 if (isa<CompoundAssignOperator>(BO))
10033 notePostUse(O, BO);
10034
10035 Visit(BO->getRHS());
10036
Richard Smith83e37bee2013-06-26 23:16:51 +000010037 // C++11 [expr.ass]p1:
10038 // the assignment is sequenced [...] before the value computation of the
10039 // assignment expression.
10040 // C11 6.5.16/3 has no such rule.
10041 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10042 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010043 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010044
Richard Smithc406cb72013-01-17 01:17:56 +000010045 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10046 VisitBinAssign(CAO);
10047 }
10048
10049 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10050 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10051 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10052 Object O = getObject(UO->getSubExpr(), true);
10053 if (!O)
10054 return VisitExpr(UO);
10055
10056 notePreMod(O, UO);
10057 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010058 // C++11 [expr.pre.incr]p1:
10059 // the expression ++x is equivalent to x+=1
10060 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10061 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010062 }
10063
10064 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10065 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10066 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10067 Object O = getObject(UO->getSubExpr(), true);
10068 if (!O)
10069 return VisitExpr(UO);
10070
10071 notePreMod(O, UO);
10072 Visit(UO->getSubExpr());
10073 notePostMod(O, UO, UK_ModAsSideEffect);
10074 }
10075
10076 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10077 void VisitBinLOr(BinaryOperator *BO) {
10078 // The side-effects of the LHS of an '&&' are sequenced before the
10079 // value computation of the RHS, and hence before the value computation
10080 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10081 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010082 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010083 {
10084 SequencedSubexpression Sequenced(*this);
10085 Visit(BO->getLHS());
10086 }
10087
10088 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010089 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010090 if (!Result)
10091 Visit(BO->getRHS());
10092 } else {
10093 // Check for unsequenced operations in the RHS, treating it as an
10094 // entirely separate evaluation.
10095 //
10096 // FIXME: If there are operations in the RHS which are unsequenced
10097 // with respect to operations outside the RHS, and those operations
10098 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010099 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010100 }
Richard Smithc406cb72013-01-17 01:17:56 +000010101 }
10102 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010103 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010104 {
10105 SequencedSubexpression Sequenced(*this);
10106 Visit(BO->getLHS());
10107 }
10108
10109 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010110 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010111 if (Result)
10112 Visit(BO->getRHS());
10113 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010114 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010115 }
Richard Smithc406cb72013-01-17 01:17:56 +000010116 }
10117
10118 // Only visit the condition, unless we can be sure which subexpression will
10119 // be chosen.
10120 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010121 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010122 {
10123 SequencedSubexpression Sequenced(*this);
10124 Visit(CO->getCond());
10125 }
Richard Smithc406cb72013-01-17 01:17:56 +000010126
10127 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010128 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010129 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010130 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010131 WorkList.push_back(CO->getTrueExpr());
10132 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010133 }
Richard Smithc406cb72013-01-17 01:17:56 +000010134 }
10135
Richard Smithe3dbfe02013-06-30 10:40:20 +000010136 void VisitCallExpr(CallExpr *CE) {
10137 // C++11 [intro.execution]p15:
10138 // When calling a function [...], every value computation and side effect
10139 // associated with any argument expression, or with the postfix expression
10140 // designating the called function, is sequenced before execution of every
10141 // expression or statement in the body of the function [and thus before
10142 // the value computation of its result].
10143 SequencedSubexpression Sequenced(*this);
10144 Base::VisitCallExpr(CE);
10145
10146 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10147 }
10148
Richard Smithc406cb72013-01-17 01:17:56 +000010149 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010150 // This is a call, so all subexpressions are sequenced before the result.
10151 SequencedSubexpression Sequenced(*this);
10152
Richard Smithc406cb72013-01-17 01:17:56 +000010153 if (!CCE->isListInitialization())
10154 return VisitExpr(CCE);
10155
10156 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010157 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010158 SequenceTree::Seq Parent = Region;
10159 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10160 E = CCE->arg_end();
10161 I != E; ++I) {
10162 Region = Tree.allocate(Parent);
10163 Elts.push_back(Region);
10164 Visit(*I);
10165 }
10166
10167 // Forget that the initializers are sequenced.
10168 Region = Parent;
10169 for (unsigned I = 0; I < Elts.size(); ++I)
10170 Tree.merge(Elts[I]);
10171 }
10172
10173 void VisitInitListExpr(InitListExpr *ILE) {
10174 if (!SemaRef.getLangOpts().CPlusPlus11)
10175 return VisitExpr(ILE);
10176
10177 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010178 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010179 SequenceTree::Seq Parent = Region;
10180 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10181 Expr *E = ILE->getInit(I);
10182 if (!E) continue;
10183 Region = Tree.allocate(Parent);
10184 Elts.push_back(Region);
10185 Visit(E);
10186 }
10187
10188 // Forget that the initializers are sequenced.
10189 Region = Parent;
10190 for (unsigned I = 0; I < Elts.size(); ++I)
10191 Tree.merge(Elts[I]);
10192 }
10193};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010194} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010195
10196void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010197 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010198 WorkList.push_back(E);
10199 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010200 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010201 SequenceChecker(*this, Item, WorkList);
10202 }
Richard Smithc406cb72013-01-17 01:17:56 +000010203}
10204
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010205void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10206 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010207 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010208 if (!E->isInstantiationDependent())
10209 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010210 if (!IsConstexpr && !E->isValueDependent())
10211 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010212 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010213}
10214
John McCall1f425642010-11-11 03:21:53 +000010215void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10216 FieldDecl *BitField,
10217 Expr *Init) {
10218 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10219}
10220
David Majnemer61a5bbf2015-04-07 22:08:51 +000010221static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10222 SourceLocation Loc) {
10223 if (!PType->isVariablyModifiedType())
10224 return;
10225 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10226 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10227 return;
10228 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010229 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10230 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10231 return;
10232 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010233 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10234 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10235 return;
10236 }
10237
10238 const ArrayType *AT = S.Context.getAsArrayType(PType);
10239 if (!AT)
10240 return;
10241
10242 if (AT->getSizeModifier() != ArrayType::Star) {
10243 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10244 return;
10245 }
10246
10247 S.Diag(Loc, diag::err_array_star_in_function_definition);
10248}
10249
Mike Stump0c2ec772010-01-21 03:59:47 +000010250/// CheckParmsForFunctionDef - Check that the parameters of the given
10251/// function are appropriate for the definition of a function. This
10252/// takes care of any checks that cannot be performed on the
10253/// declaration itself, e.g., that the types of each of the function
10254/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010255bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010256 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010257 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010258 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010259 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10260 // function declarator that is part of a function definition of
10261 // that function shall not have incomplete type.
10262 //
10263 // This is also C++ [dcl.fct]p6.
10264 if (!Param->isInvalidDecl() &&
10265 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010266 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010267 Param->setInvalidDecl();
10268 HasInvalidParm = true;
10269 }
10270
10271 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10272 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010273 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010274 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010275 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010276 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010277 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010278
10279 // C99 6.7.5.3p12:
10280 // If the function declarator is not part of a definition of that
10281 // function, parameters may have incomplete type and may use the [*]
10282 // notation in their sequences of declarator specifiers to specify
10283 // variable length array types.
10284 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010285 // FIXME: This diagnostic should point the '[*]' if source-location
10286 // information is added for it.
10287 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010288
10289 // MSVC destroys objects passed by value in the callee. Therefore a
10290 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010291 // object's destructor. However, we don't perform any direct access check
10292 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010293 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10294 .getCXXABI()
10295 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010296 if (!Param->isInvalidDecl()) {
10297 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10298 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10299 if (!ClassDecl->isInvalidDecl() &&
10300 !ClassDecl->hasIrrelevantDestructor() &&
10301 !ClassDecl->isDependentContext()) {
10302 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10303 MarkFunctionReferenced(Param->getLocation(), Destructor);
10304 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10305 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010306 }
10307 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010308 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010309
10310 // Parameters with the pass_object_size attribute only need to be marked
10311 // constant at function definitions. Because we lack information about
10312 // whether we're on a declaration or definition when we're instantiating the
10313 // attribute, we need to check for constness here.
10314 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10315 if (!Param->getType().isConstQualified())
10316 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10317 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010318 }
10319
10320 return HasInvalidParm;
10321}
John McCall2b5c1b22010-08-12 21:44:57 +000010322
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010323/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10324/// or MemberExpr.
10325static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10326 ASTContext &Context) {
10327 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10328 return Context.getDeclAlign(DRE->getDecl());
10329
10330 if (const auto *ME = dyn_cast<MemberExpr>(E))
10331 return Context.getDeclAlign(ME->getMemberDecl());
10332
10333 return TypeAlign;
10334}
10335
John McCall2b5c1b22010-08-12 21:44:57 +000010336/// CheckCastAlign - Implements -Wcast-align, which warns when a
10337/// pointer cast increases the alignment requirements.
10338void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10339 // This is actually a lot of work to potentially be doing on every
10340 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010341 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010342 return;
10343
10344 // Ignore dependent types.
10345 if (T->isDependentType() || Op->getType()->isDependentType())
10346 return;
10347
10348 // Require that the destination be a pointer type.
10349 const PointerType *DestPtr = T->getAs<PointerType>();
10350 if (!DestPtr) return;
10351
10352 // If the destination has alignment 1, we're done.
10353 QualType DestPointee = DestPtr->getPointeeType();
10354 if (DestPointee->isIncompleteType()) return;
10355 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10356 if (DestAlign.isOne()) return;
10357
10358 // Require that the source be a pointer type.
10359 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10360 if (!SrcPtr) return;
10361 QualType SrcPointee = SrcPtr->getPointeeType();
10362
10363 // Whitelist casts from cv void*. We already implicitly
10364 // whitelisted casts to cv void*, since they have alignment 1.
10365 // Also whitelist casts involving incomplete types, which implicitly
10366 // includes 'void'.
10367 if (SrcPointee->isIncompleteType()) return;
10368
10369 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010370
10371 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10372 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10373 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10374 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10375 if (UO->getOpcode() == UO_AddrOf)
10376 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10377 }
10378
John McCall2b5c1b22010-08-12 21:44:57 +000010379 if (SrcAlign >= DestAlign) return;
10380
10381 Diag(TRange.getBegin(), diag::warn_cast_align)
10382 << Op->getType() << T
10383 << static_cast<unsigned>(SrcAlign.getQuantity())
10384 << static_cast<unsigned>(DestAlign.getQuantity())
10385 << TRange << Op->getSourceRange();
10386}
10387
Chandler Carruth28389f02011-08-05 09:10:50 +000010388/// \brief Check whether this array fits the idiom of a size-one tail padded
10389/// array member of a struct.
10390///
10391/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10392/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010393static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010394 const NamedDecl *ND) {
10395 if (Size != 1 || !ND) return false;
10396
10397 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10398 if (!FD) return false;
10399
10400 // Don't consider sizes resulting from macro expansions or template argument
10401 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010402
10403 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010404 while (TInfo) {
10405 TypeLoc TL = TInfo->getTypeLoc();
10406 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010407 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10408 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010409 TInfo = TDL->getTypeSourceInfo();
10410 continue;
10411 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010412 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10413 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010414 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10415 return false;
10416 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010417 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010418 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010419
10420 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010421 if (!RD) return false;
10422 if (RD->isUnion()) return false;
10423 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10424 if (!CRD->isStandardLayout()) return false;
10425 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010426
Benjamin Kramer8c543672011-08-06 03:04:42 +000010427 // See if this is the last field decl in the record.
10428 const Decl *D = FD;
10429 while ((D = D->getNextDeclInContext()))
10430 if (isa<FieldDecl>(D))
10431 return false;
10432 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010433}
10434
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010435void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010436 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010437 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010438 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010439 if (IndexExpr->isValueDependent())
10440 return;
10441
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010442 const Type *EffectiveType =
10443 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010444 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010445 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010446 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010447 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010448 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010449
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010450 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010451 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010452 return;
Richard Smith13f67182011-12-16 19:31:14 +000010453 if (IndexNegated)
10454 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010455
Craig Topperc3ec1492014-05-26 06:22:03 +000010456 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010457 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10458 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010459 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010460 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010461
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010462 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010463 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010464 if (!size.isStrictlyPositive())
10465 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010466
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010467 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010468 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010469 // Make sure we're comparing apples to apples when comparing index to size
10470 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10471 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010472 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010473 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010474 if (ptrarith_typesize != array_typesize) {
10475 // There's a cast to a different size type involved
10476 uint64_t ratio = array_typesize / ptrarith_typesize;
10477 // TODO: Be smarter about handling cases where array_typesize is not a
10478 // multiple of ptrarith_typesize
10479 if (ptrarith_typesize * ratio == array_typesize)
10480 size *= llvm::APInt(size.getBitWidth(), ratio);
10481 }
10482 }
10483
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010484 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010485 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010486 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010487 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010488
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010489 // For array subscripting the index must be less than size, but for pointer
10490 // arithmetic also allow the index (offset) to be equal to size since
10491 // computing the next address after the end of the array is legal and
10492 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010493 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010494 return;
10495
10496 // Also don't warn for arrays of size 1 which are members of some
10497 // structure. These are often used to approximate flexible arrays in C89
10498 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010499 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010500 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010501
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010502 // Suppress the warning if the subscript expression (as identified by the
10503 // ']' location) and the index expression are both from macro expansions
10504 // within a system header.
10505 if (ASE) {
10506 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10507 ASE->getRBracketLoc());
10508 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10509 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10510 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010511 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010512 return;
10513 }
10514 }
10515
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010516 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010517 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010518 DiagID = diag::warn_array_index_exceeds_bounds;
10519
10520 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10521 PDiag(DiagID) << index.toString(10, true)
10522 << size.toString(10, true)
10523 << (unsigned)size.getLimitedValue(~0U)
10524 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010525 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010526 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010527 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010528 DiagID = diag::warn_ptr_arith_precedes_bounds;
10529 if (index.isNegative()) index = -index;
10530 }
10531
10532 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10533 PDiag(DiagID) << index.toString(10, true)
10534 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010535 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010536
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010537 if (!ND) {
10538 // Try harder to find a NamedDecl to point at in the note.
10539 while (const ArraySubscriptExpr *ASE =
10540 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10541 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10542 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10543 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10544 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10545 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10546 }
10547
Chandler Carruth1af88f12011-02-17 21:10:52 +000010548 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010549 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10550 PDiag(diag::note_array_index_out_of_bounds)
10551 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010552}
10553
Ted Kremenekdf26df72011-03-01 18:41:00 +000010554void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010555 int AllowOnePastEnd = 0;
10556 while (expr) {
10557 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010558 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010559 case Stmt::ArraySubscriptExprClass: {
10560 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010561 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010562 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010563 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010564 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010565 case Stmt::OMPArraySectionExprClass: {
10566 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10567 if (ASE->getLowerBound())
10568 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10569 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10570 return;
10571 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010572 case Stmt::UnaryOperatorClass: {
10573 // Only unwrap the * and & unary operators
10574 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10575 expr = UO->getSubExpr();
10576 switch (UO->getOpcode()) {
10577 case UO_AddrOf:
10578 AllowOnePastEnd++;
10579 break;
10580 case UO_Deref:
10581 AllowOnePastEnd--;
10582 break;
10583 default:
10584 return;
10585 }
10586 break;
10587 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010588 case Stmt::ConditionalOperatorClass: {
10589 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10590 if (const Expr *lhs = cond->getLHS())
10591 CheckArrayAccess(lhs);
10592 if (const Expr *rhs = cond->getRHS())
10593 CheckArrayAccess(rhs);
10594 return;
10595 }
10596 default:
10597 return;
10598 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010599 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010600}
John McCall31168b02011-06-15 23:02:42 +000010601
10602//===--- CHECK: Objective-C retain cycles ----------------------------------//
10603
10604namespace {
10605 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010606 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010607 VarDecl *Variable;
10608 SourceRange Range;
10609 SourceLocation Loc;
10610 bool Indirect;
10611
10612 void setLocsFrom(Expr *e) {
10613 Loc = e->getExprLoc();
10614 Range = e->getSourceRange();
10615 }
10616 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010617} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010618
10619/// Consider whether capturing the given variable can possibly lead to
10620/// a retain cycle.
10621static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010622 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010623 // lifetime. In MRR, it's captured strongly if the variable is
10624 // __block and has an appropriate type.
10625 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10626 return false;
10627
10628 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010629 if (ref)
10630 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010631 return true;
10632}
10633
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010634static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010635 while (true) {
10636 e = e->IgnoreParens();
10637 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10638 switch (cast->getCastKind()) {
10639 case CK_BitCast:
10640 case CK_LValueBitCast:
10641 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010642 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010643 e = cast->getSubExpr();
10644 continue;
10645
John McCall31168b02011-06-15 23:02:42 +000010646 default:
10647 return false;
10648 }
10649 }
10650
10651 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10652 ObjCIvarDecl *ivar = ref->getDecl();
10653 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10654 return false;
10655
10656 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010657 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010658 return false;
10659
10660 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10661 owner.Indirect = true;
10662 return true;
10663 }
10664
10665 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10666 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10667 if (!var) return false;
10668 return considerVariable(var, ref, owner);
10669 }
10670
John McCall31168b02011-06-15 23:02:42 +000010671 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10672 if (member->isArrow()) return false;
10673
10674 // Don't count this as an indirect ownership.
10675 e = member->getBase();
10676 continue;
10677 }
10678
John McCallfe96e0b2011-11-06 09:01:30 +000010679 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10680 // Only pay attention to pseudo-objects on property references.
10681 ObjCPropertyRefExpr *pre
10682 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10683 ->IgnoreParens());
10684 if (!pre) return false;
10685 if (pre->isImplicitProperty()) return false;
10686 ObjCPropertyDecl *property = pre->getExplicitProperty();
10687 if (!property->isRetaining() &&
10688 !(property->getPropertyIvarDecl() &&
10689 property->getPropertyIvarDecl()->getType()
10690 .getObjCLifetime() == Qualifiers::OCL_Strong))
10691 return false;
10692
10693 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010694 if (pre->isSuperReceiver()) {
10695 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10696 if (!owner.Variable)
10697 return false;
10698 owner.Loc = pre->getLocation();
10699 owner.Range = pre->getSourceRange();
10700 return true;
10701 }
John McCallfe96e0b2011-11-06 09:01:30 +000010702 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10703 ->getSourceExpr());
10704 continue;
10705 }
10706
John McCall31168b02011-06-15 23:02:42 +000010707 // Array ivars?
10708
10709 return false;
10710 }
10711}
10712
10713namespace {
10714 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10715 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10716 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010717 Context(Context), Variable(variable), Capturer(nullptr),
10718 VarWillBeReased(false) {}
10719 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010720 VarDecl *Variable;
10721 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010722 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010723
10724 void VisitDeclRefExpr(DeclRefExpr *ref) {
10725 if (ref->getDecl() == Variable && !Capturer)
10726 Capturer = ref;
10727 }
10728
John McCall31168b02011-06-15 23:02:42 +000010729 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10730 if (Capturer) return;
10731 Visit(ref->getBase());
10732 if (Capturer && ref->isFreeIvar())
10733 Capturer = ref;
10734 }
10735
10736 void VisitBlockExpr(BlockExpr *block) {
10737 // Look inside nested blocks
10738 if (block->getBlockDecl()->capturesVariable(Variable))
10739 Visit(block->getBlockDecl()->getBody());
10740 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010741
10742 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10743 if (Capturer) return;
10744 if (OVE->getSourceExpr())
10745 Visit(OVE->getSourceExpr());
10746 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010747 void VisitBinaryOperator(BinaryOperator *BinOp) {
10748 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10749 return;
10750 Expr *LHS = BinOp->getLHS();
10751 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10752 if (DRE->getDecl() != Variable)
10753 return;
10754 if (Expr *RHS = BinOp->getRHS()) {
10755 RHS = RHS->IgnoreParenCasts();
10756 llvm::APSInt Value;
10757 VarWillBeReased =
10758 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10759 }
10760 }
10761 }
John McCall31168b02011-06-15 23:02:42 +000010762 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010763} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010764
10765/// Check whether the given argument is a block which captures a
10766/// variable.
10767static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10768 assert(owner.Variable && owner.Loc.isValid());
10769
10770 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010771
10772 // Look through [^{...} copy] and Block_copy(^{...}).
10773 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10774 Selector Cmd = ME->getSelector();
10775 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10776 e = ME->getInstanceReceiver();
10777 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010778 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010779 e = e->IgnoreParenCasts();
10780 }
10781 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10782 if (CE->getNumArgs() == 1) {
10783 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010784 if (Fn) {
10785 const IdentifierInfo *FnI = Fn->getIdentifier();
10786 if (FnI && FnI->isStr("_Block_copy")) {
10787 e = CE->getArg(0)->IgnoreParenCasts();
10788 }
10789 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010790 }
10791 }
10792
John McCall31168b02011-06-15 23:02:42 +000010793 BlockExpr *block = dyn_cast<BlockExpr>(e);
10794 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010795 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010796
10797 FindCaptureVisitor visitor(S.Context, owner.Variable);
10798 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010799 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010800}
10801
10802static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10803 RetainCycleOwner &owner) {
10804 assert(capturer);
10805 assert(owner.Variable && owner.Loc.isValid());
10806
10807 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10808 << owner.Variable << capturer->getSourceRange();
10809 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10810 << owner.Indirect << owner.Range;
10811}
10812
10813/// Check for a keyword selector that starts with the word 'add' or
10814/// 'set'.
10815static bool isSetterLikeSelector(Selector sel) {
10816 if (sel.isUnarySelector()) return false;
10817
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010818 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010819 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010820 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010821 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010822 else if (str.startswith("add")) {
10823 // Specially whitelist 'addOperationWithBlock:'.
10824 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10825 return false;
10826 str = str.substr(3);
10827 }
John McCall31168b02011-06-15 23:02:42 +000010828 else
10829 return false;
10830
10831 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010832 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010833}
10834
Benjamin Kramer3a743452015-03-09 15:03:32 +000010835static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10836 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010837 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10838 Message->getReceiverInterface(),
10839 NSAPI::ClassId_NSMutableArray);
10840 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010841 return None;
10842 }
10843
10844 Selector Sel = Message->getSelector();
10845
10846 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10847 S.NSAPIObj->getNSArrayMethodKind(Sel);
10848 if (!MKOpt) {
10849 return None;
10850 }
10851
10852 NSAPI::NSArrayMethodKind MK = *MKOpt;
10853
10854 switch (MK) {
10855 case NSAPI::NSMutableArr_addObject:
10856 case NSAPI::NSMutableArr_insertObjectAtIndex:
10857 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10858 return 0;
10859 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10860 return 1;
10861
10862 default:
10863 return None;
10864 }
10865
10866 return None;
10867}
10868
10869static
10870Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10871 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010872 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10873 Message->getReceiverInterface(),
10874 NSAPI::ClassId_NSMutableDictionary);
10875 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010876 return None;
10877 }
10878
10879 Selector Sel = Message->getSelector();
10880
10881 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10882 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10883 if (!MKOpt) {
10884 return None;
10885 }
10886
10887 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10888
10889 switch (MK) {
10890 case NSAPI::NSMutableDict_setObjectForKey:
10891 case NSAPI::NSMutableDict_setValueForKey:
10892 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10893 return 0;
10894
10895 default:
10896 return None;
10897 }
10898
10899 return None;
10900}
10901
10902static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010903 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10904 Message->getReceiverInterface(),
10905 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010906
Alex Denisov5dfac812015-08-06 04:51:14 +000010907 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10908 Message->getReceiverInterface(),
10909 NSAPI::ClassId_NSMutableOrderedSet);
10910 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010911 return None;
10912 }
10913
10914 Selector Sel = Message->getSelector();
10915
10916 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10917 if (!MKOpt) {
10918 return None;
10919 }
10920
10921 NSAPI::NSSetMethodKind MK = *MKOpt;
10922
10923 switch (MK) {
10924 case NSAPI::NSMutableSet_addObject:
10925 case NSAPI::NSOrderedSet_setObjectAtIndex:
10926 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10927 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10928 return 0;
10929 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10930 return 1;
10931 }
10932
10933 return None;
10934}
10935
10936void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10937 if (!Message->isInstanceMessage()) {
10938 return;
10939 }
10940
10941 Optional<int> ArgOpt;
10942
10943 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10944 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10945 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10946 return;
10947 }
10948
10949 int ArgIndex = *ArgOpt;
10950
Alex Denisove1d882c2015-03-04 17:55:52 +000010951 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10952 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10953 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10954 }
10955
Alex Denisov5dfac812015-08-06 04:51:14 +000010956 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010957 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010958 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010959 Diag(Message->getSourceRange().getBegin(),
10960 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010961 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010962 }
10963 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010964 } else {
10965 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10966
10967 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10968 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10969 }
10970
10971 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10972 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10973 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10974 ValueDecl *Decl = ReceiverRE->getDecl();
10975 Diag(Message->getSourceRange().getBegin(),
10976 diag::warn_objc_circular_container)
10977 << Decl->getName() << Decl->getName();
10978 if (!ArgRE->isObjCSelfExpr()) {
10979 Diag(Decl->getLocation(),
10980 diag::note_objc_circular_container_declared_here)
10981 << Decl->getName();
10982 }
10983 }
10984 }
10985 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10986 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10987 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10988 ObjCIvarDecl *Decl = IvarRE->getDecl();
10989 Diag(Message->getSourceRange().getBegin(),
10990 diag::warn_objc_circular_container)
10991 << Decl->getName() << Decl->getName();
10992 Diag(Decl->getLocation(),
10993 diag::note_objc_circular_container_declared_here)
10994 << Decl->getName();
10995 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010996 }
10997 }
10998 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010999}
11000
John McCall31168b02011-06-15 23:02:42 +000011001/// Check a message send to see if it's likely to cause a retain cycle.
11002void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11003 // Only check instance methods whose selector looks like a setter.
11004 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11005 return;
11006
11007 // Try to find a variable that the receiver is strongly owned by.
11008 RetainCycleOwner owner;
11009 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011010 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011011 return;
11012 } else {
11013 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11014 owner.Variable = getCurMethodDecl()->getSelfDecl();
11015 owner.Loc = msg->getSuperLoc();
11016 owner.Range = msg->getSuperLoc();
11017 }
11018
11019 // Check whether the receiver is captured by any of the arguments.
11020 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11021 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11022 return diagnoseRetainCycle(*this, capturer, owner);
11023}
11024
11025/// Check a property assign to see if it's likely to cause a retain cycle.
11026void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11027 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011028 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011029 return;
11030
11031 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11032 diagnoseRetainCycle(*this, capturer, owner);
11033}
11034
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011035void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11036 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011037 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011038 return;
11039
11040 // Because we don't have an expression for the variable, we have to set the
11041 // location explicitly here.
11042 Owner.Loc = Var->getLocation();
11043 Owner.Range = Var->getSourceRange();
11044
11045 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11046 diagnoseRetainCycle(*this, Capturer, Owner);
11047}
11048
Ted Kremenek9304da92012-12-21 08:04:28 +000011049static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11050 Expr *RHS, bool isProperty) {
11051 // Check if RHS is an Objective-C object literal, which also can get
11052 // immediately zapped in a weak reference. Note that we explicitly
11053 // allow ObjCStringLiterals, since those are designed to never really die.
11054 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011055
Ted Kremenek64873352012-12-21 22:46:35 +000011056 // This enum needs to match with the 'select' in
11057 // warn_objc_arc_literal_assign (off-by-1).
11058 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11059 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11060 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011061
11062 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011063 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011064 << (isProperty ? 0 : 1)
11065 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011066
11067 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011068}
11069
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011070static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11071 Qualifiers::ObjCLifetime LT,
11072 Expr *RHS, bool isProperty) {
11073 // Strip off any implicit cast added to get to the one ARC-specific.
11074 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11075 if (cast->getCastKind() == CK_ARCConsumeObject) {
11076 S.Diag(Loc, diag::warn_arc_retained_assign)
11077 << (LT == Qualifiers::OCL_ExplicitNone)
11078 << (isProperty ? 0 : 1)
11079 << RHS->getSourceRange();
11080 return true;
11081 }
11082 RHS = cast->getSubExpr();
11083 }
11084
11085 if (LT == Qualifiers::OCL_Weak &&
11086 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11087 return true;
11088
11089 return false;
11090}
11091
Ted Kremenekb36234d2012-12-21 08:04:20 +000011092bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11093 QualType LHS, Expr *RHS) {
11094 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11095
11096 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11097 return false;
11098
11099 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11100 return true;
11101
11102 return false;
11103}
11104
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011105void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11106 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011107 QualType LHSType;
11108 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011109 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011110 ObjCPropertyRefExpr *PRE
11111 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11112 if (PRE && !PRE->isImplicitProperty()) {
11113 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11114 if (PD)
11115 LHSType = PD->getType();
11116 }
11117
11118 if (LHSType.isNull())
11119 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011120
11121 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11122
11123 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011124 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011125 getCurFunction()->markSafeWeakUse(LHS);
11126 }
11127
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011128 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11129 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011130
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011131 // FIXME. Check for other life times.
11132 if (LT != Qualifiers::OCL_None)
11133 return;
11134
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011135 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011136 if (PRE->isImplicitProperty())
11137 return;
11138 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11139 if (!PD)
11140 return;
11141
Bill Wendling44426052012-12-20 19:22:21 +000011142 unsigned Attributes = PD->getPropertyAttributes();
11143 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011144 // when 'assign' attribute was not explicitly specified
11145 // by user, ignore it and rely on property type itself
11146 // for lifetime info.
11147 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11148 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11149 LHSType->isObjCRetainableType())
11150 return;
11151
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011152 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011153 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011154 Diag(Loc, diag::warn_arc_retained_property_assign)
11155 << RHS->getSourceRange();
11156 return;
11157 }
11158 RHS = cast->getSubExpr();
11159 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011160 }
Bill Wendling44426052012-12-20 19:22:21 +000011161 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011162 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11163 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011164 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011165 }
11166}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011167
11168//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11169
11170namespace {
11171bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11172 SourceLocation StmtLoc,
11173 const NullStmt *Body) {
11174 // Do not warn if the body is a macro that expands to nothing, e.g:
11175 //
11176 // #define CALL(x)
11177 // if (condition)
11178 // CALL(0);
11179 //
11180 if (Body->hasLeadingEmptyMacro())
11181 return false;
11182
11183 // Get line numbers of statement and body.
11184 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011185 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011186 &StmtLineInvalid);
11187 if (StmtLineInvalid)
11188 return false;
11189
11190 bool BodyLineInvalid;
11191 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11192 &BodyLineInvalid);
11193 if (BodyLineInvalid)
11194 return false;
11195
11196 // Warn if null statement and body are on the same line.
11197 if (StmtLine != BodyLine)
11198 return false;
11199
11200 return true;
11201}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011202} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011203
11204void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11205 const Stmt *Body,
11206 unsigned DiagID) {
11207 // Since this is a syntactic check, don't emit diagnostic for template
11208 // instantiations, this just adds noise.
11209 if (CurrentInstantiationScope)
11210 return;
11211
11212 // The body should be a null statement.
11213 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11214 if (!NBody)
11215 return;
11216
11217 // Do the usual checks.
11218 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11219 return;
11220
11221 Diag(NBody->getSemiLoc(), DiagID);
11222 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11223}
11224
11225void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11226 const Stmt *PossibleBody) {
11227 assert(!CurrentInstantiationScope); // Ensured by caller
11228
11229 SourceLocation StmtLoc;
11230 const Stmt *Body;
11231 unsigned DiagID;
11232 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11233 StmtLoc = FS->getRParenLoc();
11234 Body = FS->getBody();
11235 DiagID = diag::warn_empty_for_body;
11236 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11237 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11238 Body = WS->getBody();
11239 DiagID = diag::warn_empty_while_body;
11240 } else
11241 return; // Neither `for' nor `while'.
11242
11243 // The body should be a null statement.
11244 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11245 if (!NBody)
11246 return;
11247
11248 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011249 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011250 return;
11251
11252 // Do the usual checks.
11253 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11254 return;
11255
11256 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11257 // noise level low, emit diagnostics only if for/while is followed by a
11258 // CompoundStmt, e.g.:
11259 // for (int i = 0; i < n; i++);
11260 // {
11261 // a(i);
11262 // }
11263 // or if for/while is followed by a statement with more indentation
11264 // than for/while itself:
11265 // for (int i = 0; i < n; i++);
11266 // a(i);
11267 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11268 if (!ProbableTypo) {
11269 bool BodyColInvalid;
11270 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11271 PossibleBody->getLocStart(),
11272 &BodyColInvalid);
11273 if (BodyColInvalid)
11274 return;
11275
11276 bool StmtColInvalid;
11277 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11278 S->getLocStart(),
11279 &StmtColInvalid);
11280 if (StmtColInvalid)
11281 return;
11282
11283 if (BodyCol > StmtCol)
11284 ProbableTypo = true;
11285 }
11286
11287 if (ProbableTypo) {
11288 Diag(NBody->getSemiLoc(), DiagID);
11289 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11290 }
11291}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011292
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011293//===--- CHECK: Warn on self move with std::move. -------------------------===//
11294
11295/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11296void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11297 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011298 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11299 return;
11300
11301 if (!ActiveTemplateInstantiations.empty())
11302 return;
11303
11304 // Strip parens and casts away.
11305 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11306 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11307
11308 // Check for a call expression
11309 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11310 if (!CE || CE->getNumArgs() != 1)
11311 return;
11312
11313 // Check for a call to std::move
11314 const FunctionDecl *FD = CE->getDirectCallee();
11315 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11316 !FD->getIdentifier()->isStr("move"))
11317 return;
11318
11319 // Get argument from std::move
11320 RHSExpr = CE->getArg(0);
11321
11322 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11323 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11324
11325 // Two DeclRefExpr's, check that the decls are the same.
11326 if (LHSDeclRef && RHSDeclRef) {
11327 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11328 return;
11329 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11330 RHSDeclRef->getDecl()->getCanonicalDecl())
11331 return;
11332
11333 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11334 << LHSExpr->getSourceRange()
11335 << RHSExpr->getSourceRange();
11336 return;
11337 }
11338
11339 // Member variables require a different approach to check for self moves.
11340 // MemberExpr's are the same if every nested MemberExpr refers to the same
11341 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11342 // the base Expr's are CXXThisExpr's.
11343 const Expr *LHSBase = LHSExpr;
11344 const Expr *RHSBase = RHSExpr;
11345 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11346 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11347 if (!LHSME || !RHSME)
11348 return;
11349
11350 while (LHSME && RHSME) {
11351 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11352 RHSME->getMemberDecl()->getCanonicalDecl())
11353 return;
11354
11355 LHSBase = LHSME->getBase();
11356 RHSBase = RHSME->getBase();
11357 LHSME = dyn_cast<MemberExpr>(LHSBase);
11358 RHSME = dyn_cast<MemberExpr>(RHSBase);
11359 }
11360
11361 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11362 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11363 if (LHSDeclRef && RHSDeclRef) {
11364 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11365 return;
11366 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11367 RHSDeclRef->getDecl()->getCanonicalDecl())
11368 return;
11369
11370 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11371 << LHSExpr->getSourceRange()
11372 << RHSExpr->getSourceRange();
11373 return;
11374 }
11375
11376 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11377 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11378 << LHSExpr->getSourceRange()
11379 << RHSExpr->getSourceRange();
11380}
11381
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011382//===--- Layout compatibility ----------------------------------------------//
11383
11384namespace {
11385
11386bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11387
11388/// \brief Check if two enumeration types are layout-compatible.
11389bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11390 // C++11 [dcl.enum] p8:
11391 // Two enumeration types are layout-compatible if they have the same
11392 // underlying type.
11393 return ED1->isComplete() && ED2->isComplete() &&
11394 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11395}
11396
11397/// \brief Check if two fields are layout-compatible.
11398bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11399 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11400 return false;
11401
11402 if (Field1->isBitField() != Field2->isBitField())
11403 return false;
11404
11405 if (Field1->isBitField()) {
11406 // Make sure that the bit-fields are the same length.
11407 unsigned Bits1 = Field1->getBitWidthValue(C);
11408 unsigned Bits2 = Field2->getBitWidthValue(C);
11409
11410 if (Bits1 != Bits2)
11411 return false;
11412 }
11413
11414 return true;
11415}
11416
11417/// \brief Check if two standard-layout structs are layout-compatible.
11418/// (C++11 [class.mem] p17)
11419bool isLayoutCompatibleStruct(ASTContext &C,
11420 RecordDecl *RD1,
11421 RecordDecl *RD2) {
11422 // If both records are C++ classes, check that base classes match.
11423 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11424 // If one of records is a CXXRecordDecl we are in C++ mode,
11425 // thus the other one is a CXXRecordDecl, too.
11426 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11427 // Check number of base classes.
11428 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11429 return false;
11430
11431 // Check the base classes.
11432 for (CXXRecordDecl::base_class_const_iterator
11433 Base1 = D1CXX->bases_begin(),
11434 BaseEnd1 = D1CXX->bases_end(),
11435 Base2 = D2CXX->bases_begin();
11436 Base1 != BaseEnd1;
11437 ++Base1, ++Base2) {
11438 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11439 return false;
11440 }
11441 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11442 // If only RD2 is a C++ class, it should have zero base classes.
11443 if (D2CXX->getNumBases() > 0)
11444 return false;
11445 }
11446
11447 // Check the fields.
11448 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11449 Field2End = RD2->field_end(),
11450 Field1 = RD1->field_begin(),
11451 Field1End = RD1->field_end();
11452 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11453 if (!isLayoutCompatible(C, *Field1, *Field2))
11454 return false;
11455 }
11456 if (Field1 != Field1End || Field2 != Field2End)
11457 return false;
11458
11459 return true;
11460}
11461
11462/// \brief Check if two standard-layout unions are layout-compatible.
11463/// (C++11 [class.mem] p18)
11464bool isLayoutCompatibleUnion(ASTContext &C,
11465 RecordDecl *RD1,
11466 RecordDecl *RD2) {
11467 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011468 for (auto *Field2 : RD2->fields())
11469 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011470
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011471 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011472 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11473 I = UnmatchedFields.begin(),
11474 E = UnmatchedFields.end();
11475
11476 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011477 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011478 bool Result = UnmatchedFields.erase(*I);
11479 (void) Result;
11480 assert(Result);
11481 break;
11482 }
11483 }
11484 if (I == E)
11485 return false;
11486 }
11487
11488 return UnmatchedFields.empty();
11489}
11490
11491bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11492 if (RD1->isUnion() != RD2->isUnion())
11493 return false;
11494
11495 if (RD1->isUnion())
11496 return isLayoutCompatibleUnion(C, RD1, RD2);
11497 else
11498 return isLayoutCompatibleStruct(C, RD1, RD2);
11499}
11500
11501/// \brief Check if two types are layout-compatible in C++11 sense.
11502bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11503 if (T1.isNull() || T2.isNull())
11504 return false;
11505
11506 // C++11 [basic.types] p11:
11507 // If two types T1 and T2 are the same type, then T1 and T2 are
11508 // layout-compatible types.
11509 if (C.hasSameType(T1, T2))
11510 return true;
11511
11512 T1 = T1.getCanonicalType().getUnqualifiedType();
11513 T2 = T2.getCanonicalType().getUnqualifiedType();
11514
11515 const Type::TypeClass TC1 = T1->getTypeClass();
11516 const Type::TypeClass TC2 = T2->getTypeClass();
11517
11518 if (TC1 != TC2)
11519 return false;
11520
11521 if (TC1 == Type::Enum) {
11522 return isLayoutCompatible(C,
11523 cast<EnumType>(T1)->getDecl(),
11524 cast<EnumType>(T2)->getDecl());
11525 } else if (TC1 == Type::Record) {
11526 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11527 return false;
11528
11529 return isLayoutCompatible(C,
11530 cast<RecordType>(T1)->getDecl(),
11531 cast<RecordType>(T2)->getDecl());
11532 }
11533
11534 return false;
11535}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011536} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011537
11538//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11539
11540namespace {
11541/// \brief Given a type tag expression find the type tag itself.
11542///
11543/// \param TypeExpr Type tag expression, as it appears in user's code.
11544///
11545/// \param VD Declaration of an identifier that appears in a type tag.
11546///
11547/// \param MagicValue Type tag magic value.
11548bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11549 const ValueDecl **VD, uint64_t *MagicValue) {
11550 while(true) {
11551 if (!TypeExpr)
11552 return false;
11553
11554 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11555
11556 switch (TypeExpr->getStmtClass()) {
11557 case Stmt::UnaryOperatorClass: {
11558 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11559 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11560 TypeExpr = UO->getSubExpr();
11561 continue;
11562 }
11563 return false;
11564 }
11565
11566 case Stmt::DeclRefExprClass: {
11567 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11568 *VD = DRE->getDecl();
11569 return true;
11570 }
11571
11572 case Stmt::IntegerLiteralClass: {
11573 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11574 llvm::APInt MagicValueAPInt = IL->getValue();
11575 if (MagicValueAPInt.getActiveBits() <= 64) {
11576 *MagicValue = MagicValueAPInt.getZExtValue();
11577 return true;
11578 } else
11579 return false;
11580 }
11581
11582 case Stmt::BinaryConditionalOperatorClass:
11583 case Stmt::ConditionalOperatorClass: {
11584 const AbstractConditionalOperator *ACO =
11585 cast<AbstractConditionalOperator>(TypeExpr);
11586 bool Result;
11587 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11588 if (Result)
11589 TypeExpr = ACO->getTrueExpr();
11590 else
11591 TypeExpr = ACO->getFalseExpr();
11592 continue;
11593 }
11594 return false;
11595 }
11596
11597 case Stmt::BinaryOperatorClass: {
11598 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11599 if (BO->getOpcode() == BO_Comma) {
11600 TypeExpr = BO->getRHS();
11601 continue;
11602 }
11603 return false;
11604 }
11605
11606 default:
11607 return false;
11608 }
11609 }
11610}
11611
11612/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11613///
11614/// \param TypeExpr Expression that specifies a type tag.
11615///
11616/// \param MagicValues Registered magic values.
11617///
11618/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11619/// kind.
11620///
11621/// \param TypeInfo Information about the corresponding C type.
11622///
11623/// \returns true if the corresponding C type was found.
11624bool GetMatchingCType(
11625 const IdentifierInfo *ArgumentKind,
11626 const Expr *TypeExpr, const ASTContext &Ctx,
11627 const llvm::DenseMap<Sema::TypeTagMagicValue,
11628 Sema::TypeTagData> *MagicValues,
11629 bool &FoundWrongKind,
11630 Sema::TypeTagData &TypeInfo) {
11631 FoundWrongKind = false;
11632
11633 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011634 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011635
11636 uint64_t MagicValue;
11637
11638 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11639 return false;
11640
11641 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011642 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011643 if (I->getArgumentKind() != ArgumentKind) {
11644 FoundWrongKind = true;
11645 return false;
11646 }
11647 TypeInfo.Type = I->getMatchingCType();
11648 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11649 TypeInfo.MustBeNull = I->getMustBeNull();
11650 return true;
11651 }
11652 return false;
11653 }
11654
11655 if (!MagicValues)
11656 return false;
11657
11658 llvm::DenseMap<Sema::TypeTagMagicValue,
11659 Sema::TypeTagData>::const_iterator I =
11660 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11661 if (I == MagicValues->end())
11662 return false;
11663
11664 TypeInfo = I->second;
11665 return true;
11666}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011667} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011668
11669void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11670 uint64_t MagicValue, QualType Type,
11671 bool LayoutCompatible,
11672 bool MustBeNull) {
11673 if (!TypeTagForDatatypeMagicValues)
11674 TypeTagForDatatypeMagicValues.reset(
11675 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11676
11677 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11678 (*TypeTagForDatatypeMagicValues)[Magic] =
11679 TypeTagData(Type, LayoutCompatible, MustBeNull);
11680}
11681
11682namespace {
11683bool IsSameCharType(QualType T1, QualType T2) {
11684 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11685 if (!BT1)
11686 return false;
11687
11688 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11689 if (!BT2)
11690 return false;
11691
11692 BuiltinType::Kind T1Kind = BT1->getKind();
11693 BuiltinType::Kind T2Kind = BT2->getKind();
11694
11695 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11696 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11697 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11698 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11699}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011700} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011701
11702void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11703 const Expr * const *ExprArgs) {
11704 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11705 bool IsPointerAttr = Attr->getIsPointer();
11706
11707 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11708 bool FoundWrongKind;
11709 TypeTagData TypeInfo;
11710 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11711 TypeTagForDatatypeMagicValues.get(),
11712 FoundWrongKind, TypeInfo)) {
11713 if (FoundWrongKind)
11714 Diag(TypeTagExpr->getExprLoc(),
11715 diag::warn_type_tag_for_datatype_wrong_kind)
11716 << TypeTagExpr->getSourceRange();
11717 return;
11718 }
11719
11720 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11721 if (IsPointerAttr) {
11722 // Skip implicit cast of pointer to `void *' (as a function argument).
11723 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011724 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011725 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011726 ArgumentExpr = ICE->getSubExpr();
11727 }
11728 QualType ArgumentType = ArgumentExpr->getType();
11729
11730 // Passing a `void*' pointer shouldn't trigger a warning.
11731 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11732 return;
11733
11734 if (TypeInfo.MustBeNull) {
11735 // Type tag with matching void type requires a null pointer.
11736 if (!ArgumentExpr->isNullPointerConstant(Context,
11737 Expr::NPC_ValueDependentIsNotNull)) {
11738 Diag(ArgumentExpr->getExprLoc(),
11739 diag::warn_type_safety_null_pointer_required)
11740 << ArgumentKind->getName()
11741 << ArgumentExpr->getSourceRange()
11742 << TypeTagExpr->getSourceRange();
11743 }
11744 return;
11745 }
11746
11747 QualType RequiredType = TypeInfo.Type;
11748 if (IsPointerAttr)
11749 RequiredType = Context.getPointerType(RequiredType);
11750
11751 bool mismatch = false;
11752 if (!TypeInfo.LayoutCompatible) {
11753 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11754
11755 // C++11 [basic.fundamental] p1:
11756 // Plain char, signed char, and unsigned char are three distinct types.
11757 //
11758 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11759 // char' depending on the current char signedness mode.
11760 if (mismatch)
11761 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11762 RequiredType->getPointeeType())) ||
11763 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11764 mismatch = false;
11765 } else
11766 if (IsPointerAttr)
11767 mismatch = !isLayoutCompatible(Context,
11768 ArgumentType->getPointeeType(),
11769 RequiredType->getPointeeType());
11770 else
11771 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11772
11773 if (mismatch)
11774 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011775 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011776 << TypeInfo.LayoutCompatible << RequiredType
11777 << ArgumentExpr->getSourceRange()
11778 << TypeTagExpr->getSourceRange();
11779}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011780
11781void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11782 CharUnits Alignment) {
11783 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11784}
11785
11786void Sema::DiagnoseMisalignedMembers() {
11787 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011788 const NamedDecl *ND = m.RD;
11789 if (ND->getName().empty()) {
11790 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11791 ND = TD;
11792 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011793 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011794 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011795 }
11796 MisalignedMembers.clear();
11797}
11798
11799void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011800 E = E->IgnoreParens();
11801 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011802 return;
11803 if (isa<UnaryOperator>(E) &&
11804 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11805 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11806 if (isa<MemberExpr>(Op)) {
11807 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11808 MisalignedMember(Op));
11809 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011810 (T->isIntegerType() ||
11811 (T->isPointerType() &&
11812 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011813 MisalignedMembers.erase(MA);
11814 }
11815 }
11816}
11817
11818void Sema::RefersToMemberWithReducedAlignment(
11819 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000011820 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11821 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011822 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011823 if (!ME)
11824 return;
11825
11826 // For a chain of MemberExpr like "a.b.c.d" this list
11827 // will keep FieldDecl's like [d, c, b].
11828 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11829 const MemberExpr *TopME = nullptr;
11830 bool AnyIsPacked = false;
11831 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011832 QualType BaseType = ME->getBase()->getType();
11833 if (ME->isArrow())
11834 BaseType = BaseType->getPointeeType();
11835 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11836
11837 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011838 auto *FD = dyn_cast<FieldDecl>(MD);
11839 // We do not care about non-data members.
11840 if (!FD || FD->isInvalidDecl())
11841 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011842
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011843 AnyIsPacked =
11844 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11845 ReverseMemberChain.push_back(FD);
11846
11847 TopME = ME;
11848 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11849 } while (ME);
11850 assert(TopME && "We did not compute a topmost MemberExpr!");
11851
11852 // Not the scope of this diagnostic.
11853 if (!AnyIsPacked)
11854 return;
11855
11856 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11857 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11858 // TODO: The innermost base of the member expression may be too complicated.
11859 // For now, just disregard these cases. This is left for future
11860 // improvement.
11861 if (!DRE && !isa<CXXThisExpr>(TopBase))
11862 return;
11863
11864 // Alignment expected by the whole expression.
11865 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11866
11867 // No need to do anything else with this case.
11868 if (ExpectedAlignment.isOne())
11869 return;
11870
11871 // Synthesize offset of the whole access.
11872 CharUnits Offset;
11873 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11874 I++) {
11875 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11876 }
11877
11878 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11879 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11880 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11881
11882 // The base expression of the innermost MemberExpr may give
11883 // stronger guarantees than the class containing the member.
11884 if (DRE && !TopME->isArrow()) {
11885 const ValueDecl *VD = DRE->getDecl();
11886 if (!VD->getType()->isReferenceType())
11887 CompleteObjectAlignment =
11888 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11889 }
11890
11891 // Check if the synthesized offset fulfills the alignment.
11892 if (Offset % ExpectedAlignment != 0 ||
11893 // It may fulfill the offset it but the effective alignment may still be
11894 // lower than the expected expression alignment.
11895 CompleteObjectAlignment < ExpectedAlignment) {
11896 // If this happens, we want to determine a sensible culprit of this.
11897 // Intuitively, watching the chain of member expressions from right to
11898 // left, we start with the required alignment (as required by the field
11899 // type) but some packed attribute in that chain has reduced the alignment.
11900 // It may happen that another packed structure increases it again. But if
11901 // we are here such increase has not been enough. So pointing the first
11902 // FieldDecl that either is packed or else its RecordDecl is,
11903 // seems reasonable.
11904 FieldDecl *FD = nullptr;
11905 CharUnits Alignment;
11906 for (FieldDecl *FDI : ReverseMemberChain) {
11907 if (FDI->hasAttr<PackedAttr>() ||
11908 FDI->getParent()->hasAttr<PackedAttr>()) {
11909 FD = FDI;
11910 Alignment = std::min(
11911 Context.getTypeAlignInChars(FD->getType()),
11912 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11913 break;
11914 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011915 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011916 assert(FD && "We did not find a packed FieldDecl!");
11917 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011918 }
11919}
11920
11921void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11922 using namespace std::placeholders;
11923 RefersToMemberWithReducedAlignment(
11924 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11925 _2, _3, _4));
11926}
11927