blob: 49208e20a49d45fd38da53bf630f3a24ae24d280 [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();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001245 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1246 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001247 bool IsInt64Long =
1248 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1249 QualType EltTy =
1250 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001251 if (HasConstPtr)
1252 EltTy = EltTy.withConst();
1253 QualType LHSTy = Context.getPointerType(EltTy);
1254 AssignConvertType ConvTy;
1255 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1256 if (RHS.isInvalid())
1257 return true;
1258 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1259 RHS.get(), AA_Assigning))
1260 return true;
1261 }
1262
1263 // For NEON intrinsics which take an immediate value as part of the
1264 // instruction, range check them here.
1265 unsigned i = 0, l = 0, u = 0;
1266 switch (BuiltinID) {
1267 default:
1268 return false;
Tim Northover12670412014-02-19 10:37:05 +00001269#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001270#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001271#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001272 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001273
Richard Sandiford28940af2014-04-16 08:47:51 +00001274 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001275}
1276
Tim Northovera2ee4332014-03-29 15:09:45 +00001277bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1278 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001279 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001280 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001281 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001282 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001283 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001284 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1285 BuiltinID == AArch64::BI__builtin_arm_strex ||
1286 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001287 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001288 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001289 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1290 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1291 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001292
1293 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1294
1295 // Ensure that we have the proper number of arguments.
1296 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1297 return true;
1298
1299 // Inspect the pointer argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1302 // casts here.
1303 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1304 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1305 if (PointerArgRes.isInvalid())
1306 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001307 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001308
1309 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1310 if (!pointerType) {
1311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << PointerArg->getType() << PointerArg->getSourceRange();
1313 return true;
1314 }
1315
1316 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1317 // task is to insert the appropriate casts into the AST. First work out just
1318 // what the appropriate type is.
1319 QualType ValType = pointerType->getPointeeType();
1320 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1321 if (IsLdrex)
1322 AddrType.addConst();
1323
1324 // Issue a warning if the cast is dodgy.
1325 CastKind CastNeeded = CK_NoOp;
1326 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1327 CastNeeded = CK_BitCast;
1328 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1329 << PointerArg->getType()
1330 << Context.getPointerType(AddrType)
1331 << AA_Passing << PointerArg->getSourceRange();
1332 }
1333
1334 // Finally, do the cast and replace the argument with the corrected version.
1335 AddrType = Context.getPointerType(AddrType);
1336 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1337 if (PointerArgRes.isInvalid())
1338 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001339 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001340
1341 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1342
1343 // In general, we allow ints, floats and pointers to be loaded and stored.
1344 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1345 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1346 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1347 << PointerArg->getType() << PointerArg->getSourceRange();
1348 return true;
1349 }
1350
1351 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001352 if (Context.getTypeSize(ValType) > MaxWidth) {
1353 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001354 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1355 << PointerArg->getType() << PointerArg->getSourceRange();
1356 return true;
1357 }
1358
1359 switch (ValType.getObjCLifetime()) {
1360 case Qualifiers::OCL_None:
1361 case Qualifiers::OCL_ExplicitNone:
1362 // okay
1363 break;
1364
1365 case Qualifiers::OCL_Weak:
1366 case Qualifiers::OCL_Strong:
1367 case Qualifiers::OCL_Autoreleasing:
1368 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1369 << ValType << PointerArg->getSourceRange();
1370 return true;
1371 }
1372
Tim Northover6aacd492013-07-16 09:47:53 +00001373 if (IsLdrex) {
1374 TheCall->setType(ValType);
1375 return false;
1376 }
1377
1378 // Initialize the argument to be stored.
1379 ExprResult ValArg = TheCall->getArg(0);
1380 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1381 Context, ValType, /*consume*/ false);
1382 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1383 if (ValArg.isInvalid())
1384 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001385 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001386
1387 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1388 // but the custom checker bypasses all default analysis.
1389 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001390 return false;
1391}
1392
Nate Begeman4904e322010-06-08 02:47:44 +00001393bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001394 llvm::APSInt Result;
1395
Tim Northover6aacd492013-07-16 09:47:53 +00001396 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001397 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1398 BuiltinID == ARM::BI__builtin_arm_strex ||
1399 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001400 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001401 }
1402
Yi Kong26d104a2014-08-13 19:18:14 +00001403 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1404 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1405 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1406 }
1407
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001408 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1409 BuiltinID == ARM::BI__builtin_arm_wsr64)
1410 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1411
1412 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1413 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1414 BuiltinID == ARM::BI__builtin_arm_wsr ||
1415 BuiltinID == ARM::BI__builtin_arm_wsrp)
1416 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1417
Tim Northover12670412014-02-19 10:37:05 +00001418 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1419 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001420
Yi Kong4efadfb2014-07-03 16:01:25 +00001421 // For intrinsics which take an immediate value as part of the instruction,
1422 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001423 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001424 switch (BuiltinID) {
1425 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001426 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1427 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001428 case ARM::BI__builtin_arm_vcvtr_f:
1429 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001430 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001431 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001432 case ARM::BI__builtin_arm_isb:
1433 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001434 }
Nate Begemand773fe62010-06-13 04:47:52 +00001435
Nate Begemanf568b072010-08-03 21:32:34 +00001436 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001437 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001438}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001439
Tim Northover573cbee2014-05-24 12:52:07 +00001440bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001441 CallExpr *TheCall) {
1442 llvm::APSInt Result;
1443
Tim Northover573cbee2014-05-24 12:52:07 +00001444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1449 }
1450
Yi Konga5548432014-08-13 19:18:20 +00001451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1456 }
1457
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001461
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1467
Tim Northovera2ee4332014-03-29 15:09:45 +00001468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1469 return true;
1470
Yi Kong19a29ac2014-07-17 10:52:06 +00001471 // For intrinsics which take an immediate value as part of the instruction,
1472 // range check them here.
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default: return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1479 }
1480
Yi Kong19a29ac2014-07-17 10:52:06 +00001481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001482}
1483
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001484// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1485// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1486// ordering for DSP is unspecified. MSA is ordered by the data format used
1487// by the underlying instruction i.e., df/m, df/n and then by size.
1488//
1489// FIXME: The size tests here should instead be tablegen'd along with the
1490// definitions from include/clang/Basic/BuiltinsMips.def.
1491// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1492// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001493bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001494 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001495 switch (BuiltinID) {
1496 default: return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1505 // df/m field.
1506 // These intrinsics take an unsigned 3 bit immediate.
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1519 // These intrinsics take an unsigned 4 bit immediate.
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1532 // These intrinsics take an unsigned 5 bit immedate.
1533 // The first block of intrinsics actually have an unsigned 5 bit field,
1534 // not a df/n field.
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1571 // These intrinsics take an unsigned 6 bit immediate.
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1584 // These intrinsics take a signed 5 bit immediate.
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1605 // These intrinsics take an unsigned 8 bit immediate.
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1616 // df/n format
1617 // These intrinsics take an unsigned 4 bit immediate.
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1622 case Mips::BI__builtin_msa_sld_b:
1623 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1624 // These intrinsics take an unsigned 3 bit immediate.
1625 case Mips::BI__builtin_msa_copy_s_h:
1626 case Mips::BI__builtin_msa_copy_u_h:
1627 case Mips::BI__builtin_msa_insve_h:
1628 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1629 case Mips::BI__builtin_msa_sld_h:
1630 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1631 // These intrinsics take an unsigned 2 bit immediate.
1632 case Mips::BI__builtin_msa_copy_s_w:
1633 case Mips::BI__builtin_msa_copy_u_w:
1634 case Mips::BI__builtin_msa_insve_w:
1635 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1636 case Mips::BI__builtin_msa_sld_w:
1637 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1638 // These intrinsics take an unsigned 1 bit immediate.
1639 case Mips::BI__builtin_msa_copy_s_d:
1640 case Mips::BI__builtin_msa_copy_u_d:
1641 case Mips::BI__builtin_msa_insve_d:
1642 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1643 case Mips::BI__builtin_msa_sld_d:
1644 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1645 // Memory offsets and immediate loads.
1646 // These intrinsics take a signed 10 bit immediate.
1647 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1648 case Mips::BI__builtin_msa_ldi_h:
1649 case Mips::BI__builtin_msa_ldi_w:
1650 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1651 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1655 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1656 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1657 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1658 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001659 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001660
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001661 if (!m)
1662 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1663
1664 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1665 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001666}
1667
Kit Bartone50adcb2015-03-30 19:40:59 +00001668bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1669 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001670 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1671 BuiltinID == PPC::BI__builtin_divdeu ||
1672 BuiltinID == PPC::BI__builtin_bpermd;
1673 bool IsTarget64Bit = Context.getTargetInfo()
1674 .getTypeWidth(Context
1675 .getTargetInfo()
1676 .getIntPtrType()) == 64;
1677 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1678 BuiltinID == PPC::BI__builtin_divweu ||
1679 BuiltinID == PPC::BI__builtin_divde ||
1680 BuiltinID == PPC::BI__builtin_divdeu;
1681
1682 if (Is64BitBltin && !IsTarget64Bit)
1683 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1684 << TheCall->getSourceRange();
1685
1686 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1687 (BuiltinID == PPC::BI__builtin_bpermd &&
1688 !Context.getTargetInfo().hasFeature("bpermd")))
1689 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1690 << TheCall->getSourceRange();
1691
Kit Bartone50adcb2015-03-30 19:40:59 +00001692 switch (BuiltinID) {
1693 default: return false;
1694 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1695 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1696 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1697 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1698 case PPC::BI__builtin_tbegin:
1699 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1700 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1701 case PPC::BI__builtin_tabortwc:
1702 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1703 case PPC::BI__builtin_tabortwci:
1704 case PPC::BI__builtin_tabortdci:
1705 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1706 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1707 }
1708 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1709}
1710
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001711bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1712 CallExpr *TheCall) {
1713 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1714 Expr *Arg = TheCall->getArg(0);
1715 llvm::APSInt AbortCode(32);
1716 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1717 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1718 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1719 << Arg->getSourceRange();
1720 }
1721
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001722 // For intrinsics which take an immediate value as part of the instruction,
1723 // range check them here.
1724 unsigned i = 0, l = 0, u = 0;
1725 switch (BuiltinID) {
1726 default: return false;
1727 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1728 case SystemZ::BI__builtin_s390_verimb:
1729 case SystemZ::BI__builtin_s390_verimh:
1730 case SystemZ::BI__builtin_s390_verimf:
1731 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1732 case SystemZ::BI__builtin_s390_vfaeb:
1733 case SystemZ::BI__builtin_s390_vfaeh:
1734 case SystemZ::BI__builtin_s390_vfaef:
1735 case SystemZ::BI__builtin_s390_vfaebs:
1736 case SystemZ::BI__builtin_s390_vfaehs:
1737 case SystemZ::BI__builtin_s390_vfaefs:
1738 case SystemZ::BI__builtin_s390_vfaezb:
1739 case SystemZ::BI__builtin_s390_vfaezh:
1740 case SystemZ::BI__builtin_s390_vfaezf:
1741 case SystemZ::BI__builtin_s390_vfaezbs:
1742 case SystemZ::BI__builtin_s390_vfaezhs:
1743 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1744 case SystemZ::BI__builtin_s390_vfidb:
1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1747 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1748 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vstrcb:
1752 case SystemZ::BI__builtin_s390_vstrch:
1753 case SystemZ::BI__builtin_s390_vstrcf:
1754 case SystemZ::BI__builtin_s390_vstrczb:
1755 case SystemZ::BI__builtin_s390_vstrczh:
1756 case SystemZ::BI__builtin_s390_vstrczf:
1757 case SystemZ::BI__builtin_s390_vstrcbs:
1758 case SystemZ::BI__builtin_s390_vstrchs:
1759 case SystemZ::BI__builtin_s390_vstrcfs:
1760 case SystemZ::BI__builtin_s390_vstrczbs:
1761 case SystemZ::BI__builtin_s390_vstrczhs:
1762 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1763 }
1764 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001765}
1766
Craig Topper5ba2c502015-11-07 08:08:31 +00001767/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1768/// This checks that the target supports __builtin_cpu_supports and
1769/// that the string argument is constant and valid.
1770static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1771 Expr *Arg = TheCall->getArg(0);
1772
1773 // Check if the argument is a string literal.
1774 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1775 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1776 << Arg->getSourceRange();
1777
1778 // Check the contents of the string.
1779 StringRef Feature =
1780 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1781 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1782 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1783 << Arg->getSourceRange();
1784 return false;
1785}
1786
Craig Toppera7e253e2016-09-23 04:48:31 +00001787// Check if the rounding mode is legal.
1788bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1789 // Indicates if this instruction has rounding control or just SAE.
1790 bool HasRC = false;
1791
1792 unsigned ArgNum = 0;
1793 switch (BuiltinID) {
1794 default:
1795 return false;
1796 case X86::BI__builtin_ia32_vcvttsd2si32:
1797 case X86::BI__builtin_ia32_vcvttsd2si64:
1798 case X86::BI__builtin_ia32_vcvttsd2usi32:
1799 case X86::BI__builtin_ia32_vcvttsd2usi64:
1800 case X86::BI__builtin_ia32_vcvttss2si32:
1801 case X86::BI__builtin_ia32_vcvttss2si64:
1802 case X86::BI__builtin_ia32_vcvttss2usi32:
1803 case X86::BI__builtin_ia32_vcvttss2usi64:
1804 ArgNum = 1;
1805 break;
1806 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1813 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1814 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1815 case X86::BI__builtin_ia32_exp2pd_mask:
1816 case X86::BI__builtin_ia32_exp2ps_mask:
1817 case X86::BI__builtin_ia32_getexppd512_mask:
1818 case X86::BI__builtin_ia32_getexpps512_mask:
1819 case X86::BI__builtin_ia32_rcp28pd_mask:
1820 case X86::BI__builtin_ia32_rcp28ps_mask:
1821 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1822 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1823 case X86::BI__builtin_ia32_vcomisd:
1824 case X86::BI__builtin_ia32_vcomiss:
1825 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1826 ArgNum = 3;
1827 break;
1828 case X86::BI__builtin_ia32_cmppd512_mask:
1829 case X86::BI__builtin_ia32_cmpps512_mask:
1830 case X86::BI__builtin_ia32_cmpsd_mask:
1831 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001832 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001833 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1834 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001835 case X86::BI__builtin_ia32_maxpd512_mask:
1836 case X86::BI__builtin_ia32_maxps512_mask:
1837 case X86::BI__builtin_ia32_maxsd_round_mask:
1838 case X86::BI__builtin_ia32_maxss_round_mask:
1839 case X86::BI__builtin_ia32_minpd512_mask:
1840 case X86::BI__builtin_ia32_minps512_mask:
1841 case X86::BI__builtin_ia32_minsd_round_mask:
1842 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001843 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1844 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1845 case X86::BI__builtin_ia32_reducepd512_mask:
1846 case X86::BI__builtin_ia32_reduceps512_mask:
1847 case X86::BI__builtin_ia32_rndscalepd_mask:
1848 case X86::BI__builtin_ia32_rndscaleps_mask:
1849 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1850 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1851 ArgNum = 4;
1852 break;
1853 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001857 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001858 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001859 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001860 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001861 case X86::BI__builtin_ia32_rangepd512_mask:
1862 case X86::BI__builtin_ia32_rangeps512_mask:
1863 case X86::BI__builtin_ia32_rangesd128_round_mask:
1864 case X86::BI__builtin_ia32_rangess128_round_mask:
1865 case X86::BI__builtin_ia32_reducesd_mask:
1866 case X86::BI__builtin_ia32_reducess_mask:
1867 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1868 case X86::BI__builtin_ia32_rndscaless_round_mask:
1869 ArgNum = 5;
1870 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001871 case X86::BI__builtin_ia32_vcvtsd2si64:
1872 case X86::BI__builtin_ia32_vcvtsd2si32:
1873 case X86::BI__builtin_ia32_vcvtsd2usi32:
1874 case X86::BI__builtin_ia32_vcvtsd2usi64:
1875 case X86::BI__builtin_ia32_vcvtss2si32:
1876 case X86::BI__builtin_ia32_vcvtss2si64:
1877 case X86::BI__builtin_ia32_vcvtss2usi32:
1878 case X86::BI__builtin_ia32_vcvtss2usi64:
1879 ArgNum = 1;
1880 HasRC = true;
1881 break;
Craig Topper8e066312016-11-07 07:01:09 +00001882 case X86::BI__builtin_ia32_cvtsi2sd64:
1883 case X86::BI__builtin_ia32_cvtsi2ss32:
1884 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001885 case X86::BI__builtin_ia32_cvtusi2sd64:
1886 case X86::BI__builtin_ia32_cvtusi2ss32:
1887 case X86::BI__builtin_ia32_cvtusi2ss64:
1888 ArgNum = 2;
1889 HasRC = true;
1890 break;
1891 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1894 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1895 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1896 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1897 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1898 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1899 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1901 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001902 case X86::BI__builtin_ia32_sqrtpd512_mask:
1903 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001904 ArgNum = 3;
1905 HasRC = true;
1906 break;
1907 case X86::BI__builtin_ia32_addpd512_mask:
1908 case X86::BI__builtin_ia32_addps512_mask:
1909 case X86::BI__builtin_ia32_divpd512_mask:
1910 case X86::BI__builtin_ia32_divps512_mask:
1911 case X86::BI__builtin_ia32_mulpd512_mask:
1912 case X86::BI__builtin_ia32_mulps512_mask:
1913 case X86::BI__builtin_ia32_subpd512_mask:
1914 case X86::BI__builtin_ia32_subps512_mask:
1915 case X86::BI__builtin_ia32_addss_round_mask:
1916 case X86::BI__builtin_ia32_addsd_round_mask:
1917 case X86::BI__builtin_ia32_divss_round_mask:
1918 case X86::BI__builtin_ia32_divsd_round_mask:
1919 case X86::BI__builtin_ia32_mulss_round_mask:
1920 case X86::BI__builtin_ia32_mulsd_round_mask:
1921 case X86::BI__builtin_ia32_subss_round_mask:
1922 case X86::BI__builtin_ia32_subsd_round_mask:
1923 case X86::BI__builtin_ia32_scalefpd512_mask:
1924 case X86::BI__builtin_ia32_scalefps512_mask:
1925 case X86::BI__builtin_ia32_scalefsd_round_mask:
1926 case X86::BI__builtin_ia32_scalefss_round_mask:
1927 case X86::BI__builtin_ia32_getmantpd512_mask:
1928 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001929 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1930 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1931 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001932 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1933 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1934 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1935 case X86::BI__builtin_ia32_vfmaddps512_mask:
1936 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1937 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1944 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1946 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1947 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1948 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1949 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1950 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1951 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1952 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1953 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1954 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1955 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1956 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1957 case X86::BI__builtin_ia32_vfmaddss3_mask:
1958 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1959 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1960 ArgNum = 4;
1961 HasRC = true;
1962 break;
1963 case X86::BI__builtin_ia32_getmantsd_round_mask:
1964 case X86::BI__builtin_ia32_getmantss_round_mask:
1965 ArgNum = 5;
1966 HasRC = true;
1967 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001968 }
1969
1970 llvm::APSInt Result;
1971
1972 // We can't check the value of a dependent argument.
1973 Expr *Arg = TheCall->getArg(ArgNum);
1974 if (Arg->isTypeDependent() || Arg->isValueDependent())
1975 return false;
1976
1977 // Check constant-ness first.
1978 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1979 return true;
1980
1981 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1982 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1983 // combined with ROUND_NO_EXC.
1984 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1985 Result == 8/*ROUND_NO_EXC*/ ||
1986 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1987 return false;
1988
1989 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1990 << Arg->getSourceRange();
1991}
1992
Craig Topperf0ddc892016-09-23 04:48:27 +00001993bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1994 if (BuiltinID == X86::BI__builtin_cpu_supports)
1995 return SemaBuiltinCpuSupports(*this, TheCall);
1996
1997 if (BuiltinID == X86::BI__builtin_ms_va_start)
1998 return SemaBuiltinMSVAStart(TheCall);
1999
Craig Toppera7e253e2016-09-23 04:48:31 +00002000 // If the intrinsic has rounding or SAE make sure its valid.
2001 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2002 return true;
2003
Craig Topperf0ddc892016-09-23 04:48:27 +00002004 // For intrinsics which take an immediate value as part of the instruction,
2005 // range check them here.
2006 int i = 0, l = 0, u = 0;
2007 switch (BuiltinID) {
2008 default:
2009 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002010 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002011 i = 1; l = 0; u = 3;
2012 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002013 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002014 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2015 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2016 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2017 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002018 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002019 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002020 case X86::BI__builtin_ia32_vpermil2pd:
2021 case X86::BI__builtin_ia32_vpermil2pd256:
2022 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002023 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002024 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002025 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002026 case X86::BI__builtin_ia32_cmpb128_mask:
2027 case X86::BI__builtin_ia32_cmpw128_mask:
2028 case X86::BI__builtin_ia32_cmpd128_mask:
2029 case X86::BI__builtin_ia32_cmpq128_mask:
2030 case X86::BI__builtin_ia32_cmpb256_mask:
2031 case X86::BI__builtin_ia32_cmpw256_mask:
2032 case X86::BI__builtin_ia32_cmpd256_mask:
2033 case X86::BI__builtin_ia32_cmpq256_mask:
2034 case X86::BI__builtin_ia32_cmpb512_mask:
2035 case X86::BI__builtin_ia32_cmpw512_mask:
2036 case X86::BI__builtin_ia32_cmpd512_mask:
2037 case X86::BI__builtin_ia32_cmpq512_mask:
2038 case X86::BI__builtin_ia32_ucmpb128_mask:
2039 case X86::BI__builtin_ia32_ucmpw128_mask:
2040 case X86::BI__builtin_ia32_ucmpd128_mask:
2041 case X86::BI__builtin_ia32_ucmpq128_mask:
2042 case X86::BI__builtin_ia32_ucmpb256_mask:
2043 case X86::BI__builtin_ia32_ucmpw256_mask:
2044 case X86::BI__builtin_ia32_ucmpd256_mask:
2045 case X86::BI__builtin_ia32_ucmpq256_mask:
2046 case X86::BI__builtin_ia32_ucmpb512_mask:
2047 case X86::BI__builtin_ia32_ucmpw512_mask:
2048 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002049 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002050 case X86::BI__builtin_ia32_vpcomub:
2051 case X86::BI__builtin_ia32_vpcomuw:
2052 case X86::BI__builtin_ia32_vpcomud:
2053 case X86::BI__builtin_ia32_vpcomuq:
2054 case X86::BI__builtin_ia32_vpcomb:
2055 case X86::BI__builtin_ia32_vpcomw:
2056 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002057 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002058 i = 2; l = 0; u = 7;
2059 break;
2060 case X86::BI__builtin_ia32_roundps:
2061 case X86::BI__builtin_ia32_roundpd:
2062 case X86::BI__builtin_ia32_roundps256:
2063 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002064 i = 1; l = 0; u = 15;
2065 break;
2066 case X86::BI__builtin_ia32_roundss:
2067 case X86::BI__builtin_ia32_roundsd:
2068 case X86::BI__builtin_ia32_rangepd128_mask:
2069 case X86::BI__builtin_ia32_rangepd256_mask:
2070 case X86::BI__builtin_ia32_rangepd512_mask:
2071 case X86::BI__builtin_ia32_rangeps128_mask:
2072 case X86::BI__builtin_ia32_rangeps256_mask:
2073 case X86::BI__builtin_ia32_rangeps512_mask:
2074 case X86::BI__builtin_ia32_getmantsd_round_mask:
2075 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002076 i = 2; l = 0; u = 15;
2077 break;
2078 case X86::BI__builtin_ia32_cmpps:
2079 case X86::BI__builtin_ia32_cmpss:
2080 case X86::BI__builtin_ia32_cmppd:
2081 case X86::BI__builtin_ia32_cmpsd:
2082 case X86::BI__builtin_ia32_cmpps256:
2083 case X86::BI__builtin_ia32_cmppd256:
2084 case X86::BI__builtin_ia32_cmpps128_mask:
2085 case X86::BI__builtin_ia32_cmppd128_mask:
2086 case X86::BI__builtin_ia32_cmpps256_mask:
2087 case X86::BI__builtin_ia32_cmppd256_mask:
2088 case X86::BI__builtin_ia32_cmpps512_mask:
2089 case X86::BI__builtin_ia32_cmppd512_mask:
2090 case X86::BI__builtin_ia32_cmpsd_mask:
2091 case X86::BI__builtin_ia32_cmpss_mask:
2092 i = 2; l = 0; u = 31;
2093 break;
2094 case X86::BI__builtin_ia32_xabort:
2095 i = 0; l = -128; u = 255;
2096 break;
2097 case X86::BI__builtin_ia32_pshufw:
2098 case X86::BI__builtin_ia32_aeskeygenassist128:
2099 i = 1; l = -128; u = 255;
2100 break;
2101 case X86::BI__builtin_ia32_vcvtps2ph:
2102 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002103 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2104 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2105 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2106 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2107 case X86::BI__builtin_ia32_rndscaleps_mask:
2108 case X86::BI__builtin_ia32_rndscalepd_mask:
2109 case X86::BI__builtin_ia32_reducepd128_mask:
2110 case X86::BI__builtin_ia32_reducepd256_mask:
2111 case X86::BI__builtin_ia32_reducepd512_mask:
2112 case X86::BI__builtin_ia32_reduceps128_mask:
2113 case X86::BI__builtin_ia32_reduceps256_mask:
2114 case X86::BI__builtin_ia32_reduceps512_mask:
2115 case X86::BI__builtin_ia32_prold512_mask:
2116 case X86::BI__builtin_ia32_prolq512_mask:
2117 case X86::BI__builtin_ia32_prold128_mask:
2118 case X86::BI__builtin_ia32_prold256_mask:
2119 case X86::BI__builtin_ia32_prolq128_mask:
2120 case X86::BI__builtin_ia32_prolq256_mask:
2121 case X86::BI__builtin_ia32_prord128_mask:
2122 case X86::BI__builtin_ia32_prord256_mask:
2123 case X86::BI__builtin_ia32_prorq128_mask:
2124 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002125 case X86::BI__builtin_ia32_fpclasspd128_mask:
2126 case X86::BI__builtin_ia32_fpclasspd256_mask:
2127 case X86::BI__builtin_ia32_fpclassps128_mask:
2128 case X86::BI__builtin_ia32_fpclassps256_mask:
2129 case X86::BI__builtin_ia32_fpclassps512_mask:
2130 case X86::BI__builtin_ia32_fpclasspd512_mask:
2131 case X86::BI__builtin_ia32_fpclasssd_mask:
2132 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002133 i = 1; l = 0; u = 255;
2134 break;
2135 case X86::BI__builtin_ia32_palignr:
2136 case X86::BI__builtin_ia32_insertps128:
2137 case X86::BI__builtin_ia32_dpps:
2138 case X86::BI__builtin_ia32_dppd:
2139 case X86::BI__builtin_ia32_dpps256:
2140 case X86::BI__builtin_ia32_mpsadbw128:
2141 case X86::BI__builtin_ia32_mpsadbw256:
2142 case X86::BI__builtin_ia32_pcmpistrm128:
2143 case X86::BI__builtin_ia32_pcmpistri128:
2144 case X86::BI__builtin_ia32_pcmpistria128:
2145 case X86::BI__builtin_ia32_pcmpistric128:
2146 case X86::BI__builtin_ia32_pcmpistrio128:
2147 case X86::BI__builtin_ia32_pcmpistris128:
2148 case X86::BI__builtin_ia32_pcmpistriz128:
2149 case X86::BI__builtin_ia32_pclmulqdq128:
2150 case X86::BI__builtin_ia32_vperm2f128_pd256:
2151 case X86::BI__builtin_ia32_vperm2f128_ps256:
2152 case X86::BI__builtin_ia32_vperm2f128_si256:
2153 case X86::BI__builtin_ia32_permti256:
2154 i = 2; l = -128; u = 255;
2155 break;
2156 case X86::BI__builtin_ia32_palignr128:
2157 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002158 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002159 case X86::BI__builtin_ia32_vcomisd:
2160 case X86::BI__builtin_ia32_vcomiss:
2161 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2162 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2163 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2164 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002165 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2166 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2167 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2168 i = 2; l = 0; u = 255;
2169 break;
2170 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2171 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2172 case X86::BI__builtin_ia32_fixupimmps512_mask:
2173 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2174 case X86::BI__builtin_ia32_fixupimmsd_mask:
2175 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2176 case X86::BI__builtin_ia32_fixupimmss_mask:
2177 case X86::BI__builtin_ia32_fixupimmss_maskz:
2178 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2179 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2180 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2181 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2182 case X86::BI__builtin_ia32_fixupimmps128_mask:
2183 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2184 case X86::BI__builtin_ia32_fixupimmps256_mask:
2185 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2186 case X86::BI__builtin_ia32_pternlogd512_mask:
2187 case X86::BI__builtin_ia32_pternlogd512_maskz:
2188 case X86::BI__builtin_ia32_pternlogq512_mask:
2189 case X86::BI__builtin_ia32_pternlogq512_maskz:
2190 case X86::BI__builtin_ia32_pternlogd128_mask:
2191 case X86::BI__builtin_ia32_pternlogd128_maskz:
2192 case X86::BI__builtin_ia32_pternlogd256_mask:
2193 case X86::BI__builtin_ia32_pternlogd256_maskz:
2194 case X86::BI__builtin_ia32_pternlogq128_mask:
2195 case X86::BI__builtin_ia32_pternlogq128_maskz:
2196 case X86::BI__builtin_ia32_pternlogq256_mask:
2197 case X86::BI__builtin_ia32_pternlogq256_maskz:
2198 i = 3; l = 0; u = 255;
2199 break;
2200 case X86::BI__builtin_ia32_pcmpestrm128:
2201 case X86::BI__builtin_ia32_pcmpestri128:
2202 case X86::BI__builtin_ia32_pcmpestria128:
2203 case X86::BI__builtin_ia32_pcmpestric128:
2204 case X86::BI__builtin_ia32_pcmpestrio128:
2205 case X86::BI__builtin_ia32_pcmpestris128:
2206 case X86::BI__builtin_ia32_pcmpestriz128:
2207 i = 4; l = -128; u = 255;
2208 break;
2209 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2210 case X86::BI__builtin_ia32_rndscaless_round_mask:
2211 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002212 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002213 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002214 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002215}
2216
Richard Smith55ce3522012-06-25 20:30:08 +00002217/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2218/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2219/// Returns true when the format fits the function and the FormatStringInfo has
2220/// been populated.
2221bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2222 FormatStringInfo *FSI) {
2223 FSI->HasVAListArg = Format->getFirstArg() == 0;
2224 FSI->FormatIdx = Format->getFormatIdx() - 1;
2225 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002226
Richard Smith55ce3522012-06-25 20:30:08 +00002227 // The way the format attribute works in GCC, the implicit this argument
2228 // of member functions is counted. However, it doesn't appear in our own
2229 // lists, so decrement format_idx in that case.
2230 if (IsCXXMember) {
2231 if(FSI->FormatIdx == 0)
2232 return false;
2233 --FSI->FormatIdx;
2234 if (FSI->FirstDataArg != 0)
2235 --FSI->FirstDataArg;
2236 }
2237 return true;
2238}
Mike Stump11289f42009-09-09 15:08:12 +00002239
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002240/// Checks if a the given expression evaluates to null.
2241///
2242/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002243static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002244 // If the expression has non-null type, it doesn't evaluate to null.
2245 if (auto nullability
2246 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2247 if (*nullability == NullabilityKind::NonNull)
2248 return false;
2249 }
2250
Ted Kremeneka146db32014-01-17 06:24:47 +00002251 // As a special case, transparent unions initialized with zero are
2252 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002253 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002254 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2255 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002256 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002257 if (const InitListExpr *ILE =
2258 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002259 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002260 }
2261
2262 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002263 return (!Expr->isValueDependent() &&
2264 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2265 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002266}
2267
2268static void CheckNonNullArgument(Sema &S,
2269 const Expr *ArgExpr,
2270 SourceLocation CallSiteLoc) {
2271 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002272 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2273 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002274}
2275
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002276bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2277 FormatStringInfo FSI;
2278 if ((GetFormatStringType(Format) == FST_NSString) &&
2279 getFormatStringInfo(Format, false, &FSI)) {
2280 Idx = FSI.FormatIdx;
2281 return true;
2282 }
2283 return false;
2284}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002285/// \brief Diagnose use of %s directive in an NSString which is being passed
2286/// as formatting string to formatting method.
2287static void
2288DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2289 const NamedDecl *FDecl,
2290 Expr **Args,
2291 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002292 unsigned Idx = 0;
2293 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002294 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2295 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002296 Idx = 2;
2297 Format = true;
2298 }
2299 else
2300 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2301 if (S.GetFormatNSStringIdx(I, Idx)) {
2302 Format = true;
2303 break;
2304 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002305 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002306 if (!Format || NumArgs <= Idx)
2307 return;
2308 const Expr *FormatExpr = Args[Idx];
2309 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2310 FormatExpr = CSCE->getSubExpr();
2311 const StringLiteral *FormatString;
2312 if (const ObjCStringLiteral *OSL =
2313 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2314 FormatString = OSL->getString();
2315 else
2316 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2317 if (!FormatString)
2318 return;
2319 if (S.FormatStringHasSArg(FormatString)) {
2320 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2321 << "%s" << 1 << 1;
2322 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2323 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002324 }
2325}
2326
Douglas Gregorb4866e82015-06-19 18:13:19 +00002327/// Determine whether the given type has a non-null nullability annotation.
2328static bool isNonNullType(ASTContext &ctx, QualType type) {
2329 if (auto nullability = type->getNullability(ctx))
2330 return *nullability == NullabilityKind::NonNull;
2331
2332 return false;
2333}
2334
Ted Kremenek2bc73332014-01-17 06:24:43 +00002335static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002336 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002337 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002338 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002339 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002340 assert((FDecl || Proto) && "Need a function declaration or prototype");
2341
Ted Kremenek9aedc152014-01-17 06:24:56 +00002342 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002343 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002344 if (FDecl) {
2345 // Handle the nonnull attribute on the function/method declaration itself.
2346 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2347 if (!NonNull->args_size()) {
2348 // Easy case: all pointer arguments are nonnull.
2349 for (const auto *Arg : Args)
2350 if (S.isValidPointerAttrType(Arg->getType()))
2351 CheckNonNullArgument(S, Arg, CallSiteLoc);
2352 return;
2353 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002354
Douglas Gregorb4866e82015-06-19 18:13:19 +00002355 for (unsigned Val : NonNull->args()) {
2356 if (Val >= Args.size())
2357 continue;
2358 if (NonNullArgs.empty())
2359 NonNullArgs.resize(Args.size());
2360 NonNullArgs.set(Val);
2361 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002362 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002363 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002364
Douglas Gregorb4866e82015-06-19 18:13:19 +00002365 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2366 // Handle the nonnull attribute on the parameters of the
2367 // function/method.
2368 ArrayRef<ParmVarDecl*> parms;
2369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2370 parms = FD->parameters();
2371 else
2372 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2373
2374 unsigned ParamIndex = 0;
2375 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2376 I != E; ++I, ++ParamIndex) {
2377 const ParmVarDecl *PVD = *I;
2378 if (PVD->hasAttr<NonNullAttr>() ||
2379 isNonNullType(S.Context, PVD->getType())) {
2380 if (NonNullArgs.empty())
2381 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002382
Douglas Gregorb4866e82015-06-19 18:13:19 +00002383 NonNullArgs.set(ParamIndex);
2384 }
2385 }
2386 } else {
2387 // If we have a non-function, non-method declaration but no
2388 // function prototype, try to dig out the function prototype.
2389 if (!Proto) {
2390 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2391 QualType type = VD->getType().getNonReferenceType();
2392 if (auto pointerType = type->getAs<PointerType>())
2393 type = pointerType->getPointeeType();
2394 else if (auto blockType = type->getAs<BlockPointerType>())
2395 type = blockType->getPointeeType();
2396 // FIXME: data member pointers?
2397
2398 // Dig out the function prototype, if there is one.
2399 Proto = type->getAs<FunctionProtoType>();
2400 }
2401 }
2402
2403 // Fill in non-null argument information from the nullability
2404 // information on the parameter types (if we have them).
2405 if (Proto) {
2406 unsigned Index = 0;
2407 for (auto paramType : Proto->getParamTypes()) {
2408 if (isNonNullType(S.Context, paramType)) {
2409 if (NonNullArgs.empty())
2410 NonNullArgs.resize(Args.size());
2411
2412 NonNullArgs.set(Index);
2413 }
2414
2415 ++Index;
2416 }
2417 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002418 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002419
Douglas Gregorb4866e82015-06-19 18:13:19 +00002420 // Check for non-null arguments.
2421 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2422 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002423 if (NonNullArgs[ArgIndex])
2424 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002425 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002426}
2427
Richard Smith55ce3522012-06-25 20:30:08 +00002428/// Handles the checks for format strings, non-POD arguments to vararg
2429/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002430void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2431 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002432 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002433 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002434 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002435 if (CurContext->isDependentContext())
2436 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002437
Ted Kremenekb8176da2010-09-09 04:33:05 +00002438 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002439 llvm::SmallBitVector CheckedVarArgs;
2440 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002441 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002442 // Only create vector if there are format attributes.
2443 CheckedVarArgs.resize(Args.size());
2444
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002445 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002446 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002447 }
Richard Smithd7293d72013-08-05 18:49:43 +00002448 }
Richard Smith55ce3522012-06-25 20:30:08 +00002449
2450 // Refuse POD arguments that weren't caught by the format string
2451 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002452 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2453 if (CallType != VariadicDoesNotApply &&
2454 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002455 unsigned NumParams = Proto ? Proto->getNumParams()
2456 : FDecl && isa<FunctionDecl>(FDecl)
2457 ? cast<FunctionDecl>(FDecl)->getNumParams()
2458 : FDecl && isa<ObjCMethodDecl>(FDecl)
2459 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2460 : 0;
2461
Alp Toker9cacbab2014-01-20 20:26:09 +00002462 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002463 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002464 if (const Expr *Arg = Args[ArgIdx]) {
2465 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2466 checkVariadicArgument(Arg, CallType);
2467 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002468 }
Richard Smithd7293d72013-08-05 18:49:43 +00002469 }
Mike Stump11289f42009-09-09 15:08:12 +00002470
Douglas Gregorb4866e82015-06-19 18:13:19 +00002471 if (FDecl || Proto) {
2472 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002473
Richard Trieu41bc0992013-06-22 00:20:41 +00002474 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002475 if (FDecl) {
2476 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2477 CheckArgumentWithTypeTag(I, Args.data());
2478 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002479 }
Richard Smith55ce3522012-06-25 20:30:08 +00002480}
2481
2482/// CheckConstructorCall - Check a constructor call for correctness and safety
2483/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002484void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2485 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002486 const FunctionProtoType *Proto,
2487 SourceLocation Loc) {
2488 VariadicCallType CallType =
2489 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002490 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2491 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002492}
2493
2494/// CheckFunctionCall - Check a direct function call for various correctness
2495/// and safety properties not strictly enforced by the C type system.
2496bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2497 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002498 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2499 isa<CXXMethodDecl>(FDecl);
2500 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2501 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002502 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2503 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002504 Expr** Args = TheCall->getArgs();
2505 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002506 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002507 // If this is a call to a member operator, hide the first argument
2508 // from checkCall.
2509 // FIXME: Our choice of AST representation here is less than ideal.
2510 ++Args;
2511 --NumArgs;
2512 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002513 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002514 IsMemberFunction, TheCall->getRParenLoc(),
2515 TheCall->getCallee()->getSourceRange(), CallType);
2516
2517 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2518 // None of the checks below are needed for functions that don't have
2519 // simple names (e.g., C++ conversion functions).
2520 if (!FnInfo)
2521 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002522
Richard Trieua7f30b12016-12-06 01:42:28 +00002523 CheckAbsoluteValueFunction(TheCall, FDecl);
2524 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002525
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002526 if (getLangOpts().ObjC1)
2527 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002528
Anna Zaks22122702012-01-17 00:37:07 +00002529 unsigned CMId = FDecl->getMemoryFunctionKind();
2530 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002531 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002532
Anna Zaks201d4892012-01-13 21:52:01 +00002533 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002534 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002535 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002536 else if (CMId == Builtin::BIstrncat)
2537 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002538 else
Anna Zaks22122702012-01-17 00:37:07 +00002539 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002540
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002541 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002542}
2543
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002544bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002545 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002546 VariadicCallType CallType =
2547 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002548
Douglas Gregorb4866e82015-06-19 18:13:19 +00002549 checkCall(Method, nullptr, Args,
2550 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2551 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002552
2553 return false;
2554}
2555
Richard Trieu664c4c62013-06-20 21:03:13 +00002556bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2557 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002558 QualType Ty;
2559 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002560 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002561 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002562 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002563 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002564 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002565
Douglas Gregorb4866e82015-06-19 18:13:19 +00002566 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2567 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002568 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002569
Richard Trieu664c4c62013-06-20 21:03:13 +00002570 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002571 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002572 CallType = VariadicDoesNotApply;
2573 } else if (Ty->isBlockPointerType()) {
2574 CallType = VariadicBlock;
2575 } else { // Ty->isFunctionPointerType()
2576 CallType = VariadicFunction;
2577 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002578
Douglas Gregorb4866e82015-06-19 18:13:19 +00002579 checkCall(NDecl, Proto,
2580 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2581 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002582 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002583
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002584 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002585}
2586
Richard Trieu41bc0992013-06-22 00:20:41 +00002587/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2588/// such as function pointers returned from functions.
2589bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002590 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002591 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002592 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002593 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002594 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002595 TheCall->getCallee()->getSourceRange(), CallType);
2596
2597 return false;
2598}
2599
Tim Northovere94a34c2014-03-11 10:49:14 +00002600static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002601 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002602 return false;
2603
JF Bastiendda2cb12016-04-18 18:01:49 +00002604 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002605 switch (Op) {
2606 case AtomicExpr::AO__c11_atomic_init:
2607 llvm_unreachable("There is no ordering argument for an init");
2608
2609 case AtomicExpr::AO__c11_atomic_load:
2610 case AtomicExpr::AO__atomic_load_n:
2611 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002612 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2613 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002614
2615 case AtomicExpr::AO__c11_atomic_store:
2616 case AtomicExpr::AO__atomic_store:
2617 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002618 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2619 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2620 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002621
2622 default:
2623 return true;
2624 }
2625}
2626
Richard Smithfeea8832012-04-12 05:08:17 +00002627ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2628 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002629 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2630 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002631
Richard Smithfeea8832012-04-12 05:08:17 +00002632 // All these operations take one of the following forms:
2633 enum {
2634 // C __c11_atomic_init(A *, C)
2635 Init,
2636 // C __c11_atomic_load(A *, int)
2637 Load,
2638 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002639 LoadCopy,
2640 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002641 Copy,
2642 // C __c11_atomic_add(A *, M, int)
2643 Arithmetic,
2644 // C __atomic_exchange_n(A *, CP, int)
2645 Xchg,
2646 // void __atomic_exchange(A *, C *, CP, int)
2647 GNUXchg,
2648 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2649 C11CmpXchg,
2650 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2651 GNUCmpXchg
2652 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002653 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2654 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002655 // where:
2656 // C is an appropriate type,
2657 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2658 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2659 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2660 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002661
Gabor Horvath98bd0982015-03-16 09:59:54 +00002662 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2663 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2664 AtomicExpr::AO__atomic_load,
2665 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002666 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2667 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2668 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2669 Op == AtomicExpr::AO__atomic_store_n ||
2670 Op == AtomicExpr::AO__atomic_exchange_n ||
2671 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2672 bool IsAddSub = false;
2673
2674 switch (Op) {
2675 case AtomicExpr::AO__c11_atomic_init:
2676 Form = Init;
2677 break;
2678
2679 case AtomicExpr::AO__c11_atomic_load:
2680 case AtomicExpr::AO__atomic_load_n:
2681 Form = Load;
2682 break;
2683
Richard Smithfeea8832012-04-12 05:08:17 +00002684 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002685 Form = LoadCopy;
2686 break;
2687
2688 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002689 case AtomicExpr::AO__atomic_store:
2690 case AtomicExpr::AO__atomic_store_n:
2691 Form = Copy;
2692 break;
2693
2694 case AtomicExpr::AO__c11_atomic_fetch_add:
2695 case AtomicExpr::AO__c11_atomic_fetch_sub:
2696 case AtomicExpr::AO__atomic_fetch_add:
2697 case AtomicExpr::AO__atomic_fetch_sub:
2698 case AtomicExpr::AO__atomic_add_fetch:
2699 case AtomicExpr::AO__atomic_sub_fetch:
2700 IsAddSub = true;
2701 // Fall through.
2702 case AtomicExpr::AO__c11_atomic_fetch_and:
2703 case AtomicExpr::AO__c11_atomic_fetch_or:
2704 case AtomicExpr::AO__c11_atomic_fetch_xor:
2705 case AtomicExpr::AO__atomic_fetch_and:
2706 case AtomicExpr::AO__atomic_fetch_or:
2707 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002708 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002709 case AtomicExpr::AO__atomic_and_fetch:
2710 case AtomicExpr::AO__atomic_or_fetch:
2711 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002712 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002713 Form = Arithmetic;
2714 break;
2715
2716 case AtomicExpr::AO__c11_atomic_exchange:
2717 case AtomicExpr::AO__atomic_exchange_n:
2718 Form = Xchg;
2719 break;
2720
2721 case AtomicExpr::AO__atomic_exchange:
2722 Form = GNUXchg;
2723 break;
2724
2725 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2726 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2727 Form = C11CmpXchg;
2728 break;
2729
2730 case AtomicExpr::AO__atomic_compare_exchange:
2731 case AtomicExpr::AO__atomic_compare_exchange_n:
2732 Form = GNUCmpXchg;
2733 break;
2734 }
2735
2736 // Check we have the right number of arguments.
2737 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002738 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002739 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002740 << TheCall->getCallee()->getSourceRange();
2741 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002742 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2743 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002744 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002745 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002746 << TheCall->getCallee()->getSourceRange();
2747 return ExprError();
2748 }
2749
Richard Smithfeea8832012-04-12 05:08:17 +00002750 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002751 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002752 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2753 if (ConvertedPtr.isInvalid())
2754 return ExprError();
2755
2756 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002757 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2758 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002759 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002760 << Ptr->getType() << Ptr->getSourceRange();
2761 return ExprError();
2762 }
2763
Richard Smithfeea8832012-04-12 05:08:17 +00002764 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2765 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2766 QualType ValType = AtomTy; // 'C'
2767 if (IsC11) {
2768 if (!AtomTy->isAtomicType()) {
2769 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2770 << Ptr->getType() << Ptr->getSourceRange();
2771 return ExprError();
2772 }
Richard Smithe00921a2012-09-15 06:09:58 +00002773 if (AtomTy.isConstQualified()) {
2774 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2775 << Ptr->getType() << Ptr->getSourceRange();
2776 return ExprError();
2777 }
Richard Smithfeea8832012-04-12 05:08:17 +00002778 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002779 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002780 if (ValType.isConstQualified()) {
2781 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2782 << Ptr->getType() << Ptr->getSourceRange();
2783 return ExprError();
2784 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002785 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002786
Richard Smithfeea8832012-04-12 05:08:17 +00002787 // For an arithmetic operation, the implied arithmetic must be well-formed.
2788 if (Form == Arithmetic) {
2789 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2790 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2791 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2792 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2793 return ExprError();
2794 }
2795 if (!IsAddSub && !ValType->isIntegerType()) {
2796 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2797 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2798 return ExprError();
2799 }
David Majnemere85cff82015-01-28 05:48:06 +00002800 if (IsC11 && ValType->isPointerType() &&
2801 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2802 diag::err_incomplete_type)) {
2803 return ExprError();
2804 }
Richard Smithfeea8832012-04-12 05:08:17 +00002805 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2806 // For __atomic_*_n operations, the value type must be a scalar integral or
2807 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002808 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002809 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2810 return ExprError();
2811 }
2812
Eli Friedmanaa769812013-09-11 03:49:34 +00002813 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2814 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002815 // For GNU atomics, require a trivially-copyable type. This is not part of
2816 // the GNU atomics specification, but we enforce it for sanity.
2817 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002818 << Ptr->getType() << Ptr->getSourceRange();
2819 return ExprError();
2820 }
2821
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002822 switch (ValType.getObjCLifetime()) {
2823 case Qualifiers::OCL_None:
2824 case Qualifiers::OCL_ExplicitNone:
2825 // okay
2826 break;
2827
2828 case Qualifiers::OCL_Weak:
2829 case Qualifiers::OCL_Strong:
2830 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002831 // FIXME: Can this happen? By this point, ValType should be known
2832 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002833 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2834 << ValType << Ptr->getSourceRange();
2835 return ExprError();
2836 }
2837
David Majnemerc6eb6502015-06-03 00:26:35 +00002838 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2839 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002840 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002841 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002842 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002843 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002844 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002845 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002846 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002847 ResultType = Context.BoolTy;
2848
Richard Smithfeea8832012-04-12 05:08:17 +00002849 // The type of a parameter passed 'by value'. In the GNU atomics, such
2850 // arguments are actually passed as pointers.
2851 QualType ByValType = ValType; // 'CP'
2852 if (!IsC11 && !IsN)
2853 ByValType = Ptr->getType();
2854
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002855 // The first argument --- the pointer --- has a fixed type; we
2856 // deduce the types of the rest of the arguments accordingly. Walk
2857 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002858 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002859 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002860 if (i < NumVals[Form] + 1) {
2861 switch (i) {
2862 case 1:
2863 // The second argument is the non-atomic operand. For arithmetic, this
2864 // is always passed by value, and for a compare_exchange it is always
2865 // passed by address. For the rest, GNU uses by-address and C11 uses
2866 // by-value.
2867 assert(Form != Load);
2868 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2869 Ty = ValType;
2870 else if (Form == Copy || Form == Xchg)
2871 Ty = ByValType;
2872 else if (Form == Arithmetic)
2873 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002874 else {
2875 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002876 // Treat this argument as _Nonnull as we want to show a warning if
2877 // NULL is passed into it.
2878 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002879 unsigned AS = 0;
2880 // Keep address space of non-atomic pointer type.
2881 if (const PointerType *PtrTy =
2882 ValArg->getType()->getAs<PointerType>()) {
2883 AS = PtrTy->getPointeeType().getAddressSpace();
2884 }
2885 Ty = Context.getPointerType(
2886 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2887 }
Richard Smithfeea8832012-04-12 05:08:17 +00002888 break;
2889 case 2:
2890 // The third argument to compare_exchange / GNU exchange is a
2891 // (pointer to a) desired value.
2892 Ty = ByValType;
2893 break;
2894 case 3:
2895 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2896 Ty = Context.BoolTy;
2897 break;
2898 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002899 } else {
2900 // The order(s) are always converted to int.
2901 Ty = Context.IntTy;
2902 }
Richard Smithfeea8832012-04-12 05:08:17 +00002903
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002904 InitializedEntity Entity =
2905 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002906 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002907 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2908 if (Arg.isInvalid())
2909 return true;
2910 TheCall->setArg(i, Arg.get());
2911 }
2912
Richard Smithfeea8832012-04-12 05:08:17 +00002913 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002914 SmallVector<Expr*, 5> SubExprs;
2915 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002916 switch (Form) {
2917 case Init:
2918 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002919 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002920 break;
2921 case Load:
2922 SubExprs.push_back(TheCall->getArg(1)); // Order
2923 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002924 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002925 case Copy:
2926 case Arithmetic:
2927 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002928 SubExprs.push_back(TheCall->getArg(2)); // Order
2929 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002930 break;
2931 case GNUXchg:
2932 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2933 SubExprs.push_back(TheCall->getArg(3)); // Order
2934 SubExprs.push_back(TheCall->getArg(1)); // Val1
2935 SubExprs.push_back(TheCall->getArg(2)); // Val2
2936 break;
2937 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002938 SubExprs.push_back(TheCall->getArg(3)); // Order
2939 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002940 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002941 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002942 break;
2943 case GNUCmpXchg:
2944 SubExprs.push_back(TheCall->getArg(4)); // Order
2945 SubExprs.push_back(TheCall->getArg(1)); // Val1
2946 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2947 SubExprs.push_back(TheCall->getArg(2)); // Val2
2948 SubExprs.push_back(TheCall->getArg(3)); // Weak
2949 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002950 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002951
2952 if (SubExprs.size() >= 2 && Form != Init) {
2953 llvm::APSInt Result(32);
2954 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2955 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002956 Diag(SubExprs[1]->getLocStart(),
2957 diag::warn_atomic_op_has_invalid_memory_order)
2958 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002959 }
2960
Fariborz Jahanian615de762013-05-28 17:37:39 +00002961 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2962 SubExprs, ResultType, Op,
2963 TheCall->getRParenLoc());
2964
2965 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2966 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2967 Context.AtomicUsesUnsupportedLibcall(AE))
2968 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2969 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002970
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002971 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002972}
2973
John McCall29ad95b2011-08-27 01:09:30 +00002974/// checkBuiltinArgument - Given a call to a builtin function, perform
2975/// normal type-checking on the given argument, updating the call in
2976/// place. This is useful when a builtin function requires custom
2977/// type-checking for some of its arguments but not necessarily all of
2978/// them.
2979///
2980/// Returns true on error.
2981static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2982 FunctionDecl *Fn = E->getDirectCallee();
2983 assert(Fn && "builtin call without direct callee!");
2984
2985 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2986 InitializedEntity Entity =
2987 InitializedEntity::InitializeParameter(S.Context, Param);
2988
2989 ExprResult Arg = E->getArg(0);
2990 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2991 if (Arg.isInvalid())
2992 return true;
2993
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002994 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002995 return false;
2996}
2997
Chris Lattnerdc046542009-05-08 06:58:22 +00002998/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2999/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3000/// type of its first argument. The main ActOnCallExpr routines have already
3001/// promoted the types of arguments because all of these calls are prototyped as
3002/// void(...).
3003///
3004/// This function goes through and does final semantic checking for these
3005/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003006ExprResult
3007Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003008 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003009 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3010 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3011
3012 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003013 if (TheCall->getNumArgs() < 1) {
3014 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3015 << 0 << 1 << TheCall->getNumArgs()
3016 << TheCall->getCallee()->getSourceRange();
3017 return ExprError();
3018 }
Mike Stump11289f42009-09-09 15:08:12 +00003019
Chris Lattnerdc046542009-05-08 06:58:22 +00003020 // Inspect the first argument of the atomic builtin. This should always be
3021 // a pointer type, whose element is an integral scalar or pointer type.
3022 // Because it is a pointer type, we don't have to worry about any implicit
3023 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003024 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003025 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003026 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3027 if (FirstArgResult.isInvalid())
3028 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003029 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003030 TheCall->setArg(0, FirstArg);
3031
John McCall31168b02011-06-15 23:02:42 +00003032 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3033 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3035 << FirstArg->getType() << FirstArg->getSourceRange();
3036 return ExprError();
3037 }
Mike Stump11289f42009-09-09 15:08:12 +00003038
John McCall31168b02011-06-15 23:02:42 +00003039 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003040 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003041 !ValType->isBlockPointerType()) {
3042 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3043 << FirstArg->getType() << FirstArg->getSourceRange();
3044 return ExprError();
3045 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003046
John McCall31168b02011-06-15 23:02:42 +00003047 switch (ValType.getObjCLifetime()) {
3048 case Qualifiers::OCL_None:
3049 case Qualifiers::OCL_ExplicitNone:
3050 // okay
3051 break;
3052
3053 case Qualifiers::OCL_Weak:
3054 case Qualifiers::OCL_Strong:
3055 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003056 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003057 << ValType << FirstArg->getSourceRange();
3058 return ExprError();
3059 }
3060
John McCallb50451a2011-10-05 07:41:44 +00003061 // Strip any qualifiers off ValType.
3062 ValType = ValType.getUnqualifiedType();
3063
Chandler Carruth3973af72010-07-18 20:54:12 +00003064 // The majority of builtins return a value, but a few have special return
3065 // types, so allow them to override appropriately below.
3066 QualType ResultType = ValType;
3067
Chris Lattnerdc046542009-05-08 06:58:22 +00003068 // We need to figure out which concrete builtin this maps onto. For example,
3069 // __sync_fetch_and_add with a 2 byte object turns into
3070 // __sync_fetch_and_add_2.
3071#define BUILTIN_ROW(x) \
3072 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3073 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003074
Chris Lattnerdc046542009-05-08 06:58:22 +00003075 static const unsigned BuiltinIndices[][5] = {
3076 BUILTIN_ROW(__sync_fetch_and_add),
3077 BUILTIN_ROW(__sync_fetch_and_sub),
3078 BUILTIN_ROW(__sync_fetch_and_or),
3079 BUILTIN_ROW(__sync_fetch_and_and),
3080 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003081 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003082
Chris Lattnerdc046542009-05-08 06:58:22 +00003083 BUILTIN_ROW(__sync_add_and_fetch),
3084 BUILTIN_ROW(__sync_sub_and_fetch),
3085 BUILTIN_ROW(__sync_and_and_fetch),
3086 BUILTIN_ROW(__sync_or_and_fetch),
3087 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003088 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003089
Chris Lattnerdc046542009-05-08 06:58:22 +00003090 BUILTIN_ROW(__sync_val_compare_and_swap),
3091 BUILTIN_ROW(__sync_bool_compare_and_swap),
3092 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003093 BUILTIN_ROW(__sync_lock_release),
3094 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003095 };
Mike Stump11289f42009-09-09 15:08:12 +00003096#undef BUILTIN_ROW
3097
Chris Lattnerdc046542009-05-08 06:58:22 +00003098 // Determine the index of the size.
3099 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003100 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003101 case 1: SizeIndex = 0; break;
3102 case 2: SizeIndex = 1; break;
3103 case 4: SizeIndex = 2; break;
3104 case 8: SizeIndex = 3; break;
3105 case 16: SizeIndex = 4; break;
3106 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003107 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3108 << FirstArg->getType() << FirstArg->getSourceRange();
3109 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003110 }
Mike Stump11289f42009-09-09 15:08:12 +00003111
Chris Lattnerdc046542009-05-08 06:58:22 +00003112 // Each of these builtins has one pointer argument, followed by some number of
3113 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3114 // that we ignore. Find out which row of BuiltinIndices to read from as well
3115 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003116 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003117 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003118 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003119 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003120 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003121 case Builtin::BI__sync_fetch_and_add:
3122 case Builtin::BI__sync_fetch_and_add_1:
3123 case Builtin::BI__sync_fetch_and_add_2:
3124 case Builtin::BI__sync_fetch_and_add_4:
3125 case Builtin::BI__sync_fetch_and_add_8:
3126 case Builtin::BI__sync_fetch_and_add_16:
3127 BuiltinIndex = 0;
3128 break;
3129
3130 case Builtin::BI__sync_fetch_and_sub:
3131 case Builtin::BI__sync_fetch_and_sub_1:
3132 case Builtin::BI__sync_fetch_and_sub_2:
3133 case Builtin::BI__sync_fetch_and_sub_4:
3134 case Builtin::BI__sync_fetch_and_sub_8:
3135 case Builtin::BI__sync_fetch_and_sub_16:
3136 BuiltinIndex = 1;
3137 break;
3138
3139 case Builtin::BI__sync_fetch_and_or:
3140 case Builtin::BI__sync_fetch_and_or_1:
3141 case Builtin::BI__sync_fetch_and_or_2:
3142 case Builtin::BI__sync_fetch_and_or_4:
3143 case Builtin::BI__sync_fetch_and_or_8:
3144 case Builtin::BI__sync_fetch_and_or_16:
3145 BuiltinIndex = 2;
3146 break;
3147
3148 case Builtin::BI__sync_fetch_and_and:
3149 case Builtin::BI__sync_fetch_and_and_1:
3150 case Builtin::BI__sync_fetch_and_and_2:
3151 case Builtin::BI__sync_fetch_and_and_4:
3152 case Builtin::BI__sync_fetch_and_and_8:
3153 case Builtin::BI__sync_fetch_and_and_16:
3154 BuiltinIndex = 3;
3155 break;
Mike Stump11289f42009-09-09 15:08:12 +00003156
Douglas Gregor73722482011-11-28 16:30:08 +00003157 case Builtin::BI__sync_fetch_and_xor:
3158 case Builtin::BI__sync_fetch_and_xor_1:
3159 case Builtin::BI__sync_fetch_and_xor_2:
3160 case Builtin::BI__sync_fetch_and_xor_4:
3161 case Builtin::BI__sync_fetch_and_xor_8:
3162 case Builtin::BI__sync_fetch_and_xor_16:
3163 BuiltinIndex = 4;
3164 break;
3165
Hal Finkeld2208b52014-10-02 20:53:50 +00003166 case Builtin::BI__sync_fetch_and_nand:
3167 case Builtin::BI__sync_fetch_and_nand_1:
3168 case Builtin::BI__sync_fetch_and_nand_2:
3169 case Builtin::BI__sync_fetch_and_nand_4:
3170 case Builtin::BI__sync_fetch_and_nand_8:
3171 case Builtin::BI__sync_fetch_and_nand_16:
3172 BuiltinIndex = 5;
3173 WarnAboutSemanticsChange = true;
3174 break;
3175
Douglas Gregor73722482011-11-28 16:30:08 +00003176 case Builtin::BI__sync_add_and_fetch:
3177 case Builtin::BI__sync_add_and_fetch_1:
3178 case Builtin::BI__sync_add_and_fetch_2:
3179 case Builtin::BI__sync_add_and_fetch_4:
3180 case Builtin::BI__sync_add_and_fetch_8:
3181 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003182 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003183 break;
3184
3185 case Builtin::BI__sync_sub_and_fetch:
3186 case Builtin::BI__sync_sub_and_fetch_1:
3187 case Builtin::BI__sync_sub_and_fetch_2:
3188 case Builtin::BI__sync_sub_and_fetch_4:
3189 case Builtin::BI__sync_sub_and_fetch_8:
3190 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003191 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003192 break;
3193
3194 case Builtin::BI__sync_and_and_fetch:
3195 case Builtin::BI__sync_and_and_fetch_1:
3196 case Builtin::BI__sync_and_and_fetch_2:
3197 case Builtin::BI__sync_and_and_fetch_4:
3198 case Builtin::BI__sync_and_and_fetch_8:
3199 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003200 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003201 break;
3202
3203 case Builtin::BI__sync_or_and_fetch:
3204 case Builtin::BI__sync_or_and_fetch_1:
3205 case Builtin::BI__sync_or_and_fetch_2:
3206 case Builtin::BI__sync_or_and_fetch_4:
3207 case Builtin::BI__sync_or_and_fetch_8:
3208 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003209 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003210 break;
3211
3212 case Builtin::BI__sync_xor_and_fetch:
3213 case Builtin::BI__sync_xor_and_fetch_1:
3214 case Builtin::BI__sync_xor_and_fetch_2:
3215 case Builtin::BI__sync_xor_and_fetch_4:
3216 case Builtin::BI__sync_xor_and_fetch_8:
3217 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003218 BuiltinIndex = 10;
3219 break;
3220
3221 case Builtin::BI__sync_nand_and_fetch:
3222 case Builtin::BI__sync_nand_and_fetch_1:
3223 case Builtin::BI__sync_nand_and_fetch_2:
3224 case Builtin::BI__sync_nand_and_fetch_4:
3225 case Builtin::BI__sync_nand_and_fetch_8:
3226 case Builtin::BI__sync_nand_and_fetch_16:
3227 BuiltinIndex = 11;
3228 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003229 break;
Mike Stump11289f42009-09-09 15:08:12 +00003230
Chris Lattnerdc046542009-05-08 06:58:22 +00003231 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003232 case Builtin::BI__sync_val_compare_and_swap_1:
3233 case Builtin::BI__sync_val_compare_and_swap_2:
3234 case Builtin::BI__sync_val_compare_and_swap_4:
3235 case Builtin::BI__sync_val_compare_and_swap_8:
3236 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003237 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003238 NumFixed = 2;
3239 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003240
Chris Lattnerdc046542009-05-08 06:58:22 +00003241 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003242 case Builtin::BI__sync_bool_compare_and_swap_1:
3243 case Builtin::BI__sync_bool_compare_and_swap_2:
3244 case Builtin::BI__sync_bool_compare_and_swap_4:
3245 case Builtin::BI__sync_bool_compare_and_swap_8:
3246 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003247 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003248 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003249 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003250 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003251
3252 case Builtin::BI__sync_lock_test_and_set:
3253 case Builtin::BI__sync_lock_test_and_set_1:
3254 case Builtin::BI__sync_lock_test_and_set_2:
3255 case Builtin::BI__sync_lock_test_and_set_4:
3256 case Builtin::BI__sync_lock_test_and_set_8:
3257 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003258 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003259 break;
3260
Chris Lattnerdc046542009-05-08 06:58:22 +00003261 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003262 case Builtin::BI__sync_lock_release_1:
3263 case Builtin::BI__sync_lock_release_2:
3264 case Builtin::BI__sync_lock_release_4:
3265 case Builtin::BI__sync_lock_release_8:
3266 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003267 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003268 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003269 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003270 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003271
3272 case Builtin::BI__sync_swap:
3273 case Builtin::BI__sync_swap_1:
3274 case Builtin::BI__sync_swap_2:
3275 case Builtin::BI__sync_swap_4:
3276 case Builtin::BI__sync_swap_8:
3277 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003278 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003279 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003280 }
Mike Stump11289f42009-09-09 15:08:12 +00003281
Chris Lattnerdc046542009-05-08 06:58:22 +00003282 // Now that we know how many fixed arguments we expect, first check that we
3283 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003284 if (TheCall->getNumArgs() < 1+NumFixed) {
3285 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3286 << 0 << 1+NumFixed << TheCall->getNumArgs()
3287 << TheCall->getCallee()->getSourceRange();
3288 return ExprError();
3289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Hal Finkeld2208b52014-10-02 20:53:50 +00003291 if (WarnAboutSemanticsChange) {
3292 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3293 << TheCall->getCallee()->getSourceRange();
3294 }
3295
Chris Lattner5b9241b2009-05-08 15:36:58 +00003296 // Get the decl for the concrete builtin from this, we can tell what the
3297 // concrete integer type we should convert to is.
3298 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003299 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003300 FunctionDecl *NewBuiltinDecl;
3301 if (NewBuiltinID == BuiltinID)
3302 NewBuiltinDecl = FDecl;
3303 else {
3304 // Perform builtin lookup to avoid redeclaring it.
3305 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3306 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3307 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3308 assert(Res.getFoundDecl());
3309 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003310 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003311 return ExprError();
3312 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003313
John McCallcf142162010-08-07 06:22:56 +00003314 // The first argument --- the pointer --- has a fixed type; we
3315 // deduce the types of the rest of the arguments accordingly. Walk
3316 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003317 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003318 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003319
Chris Lattnerdc046542009-05-08 06:58:22 +00003320 // GCC does an implicit conversion to the pointer or integer ValType. This
3321 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003322 // Initialize the argument.
3323 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3324 ValType, /*consume*/ false);
3325 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003326 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003327 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003328
Chris Lattnerdc046542009-05-08 06:58:22 +00003329 // Okay, we have something that *can* be converted to the right type. Check
3330 // to see if there is a potentially weird extension going on here. This can
3331 // happen when you do an atomic operation on something like an char* and
3332 // pass in 42. The 42 gets converted to char. This is even more strange
3333 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003334 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003335 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003338 ASTContext& Context = this->getASTContext();
3339
3340 // Create a new DeclRefExpr to refer to the new decl.
3341 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3342 Context,
3343 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003344 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003345 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003346 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003347 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003348 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003349 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003350
Chris Lattnerdc046542009-05-08 06:58:22 +00003351 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003352 // FIXME: This loses syntactic information.
3353 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3354 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3355 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003356 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003357
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003358 // Change the result type of the call to match the original value type. This
3359 // is arbitrary, but the codegen for these builtins ins design to handle it
3360 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003361 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003362
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003363 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003364}
3365
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003366/// SemaBuiltinNontemporalOverloaded - We have a call to
3367/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3368/// overloaded function based on the pointer type of its last argument.
3369///
3370/// This function goes through and does final semantic checking for these
3371/// builtins.
3372ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3373 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3374 DeclRefExpr *DRE =
3375 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3376 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3377 unsigned BuiltinID = FDecl->getBuiltinID();
3378 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3379 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3380 "Unexpected nontemporal load/store builtin!");
3381 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3382 unsigned numArgs = isStore ? 2 : 1;
3383
3384 // Ensure that we have the proper number of arguments.
3385 if (checkArgCount(*this, TheCall, numArgs))
3386 return ExprError();
3387
3388 // Inspect the last argument of the nontemporal builtin. This should always
3389 // be a pointer type, from which we imply the type of the memory access.
3390 // Because it is a pointer type, we don't have to worry about any implicit
3391 // casts here.
3392 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3393 ExprResult PointerArgResult =
3394 DefaultFunctionArrayLvalueConversion(PointerArg);
3395
3396 if (PointerArgResult.isInvalid())
3397 return ExprError();
3398 PointerArg = PointerArgResult.get();
3399 TheCall->setArg(numArgs - 1, PointerArg);
3400
3401 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3402 if (!pointerType) {
3403 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3404 << PointerArg->getType() << PointerArg->getSourceRange();
3405 return ExprError();
3406 }
3407
3408 QualType ValType = pointerType->getPointeeType();
3409
3410 // Strip any qualifiers off ValType.
3411 ValType = ValType.getUnqualifiedType();
3412 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3413 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3414 !ValType->isVectorType()) {
3415 Diag(DRE->getLocStart(),
3416 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3417 << PointerArg->getType() << PointerArg->getSourceRange();
3418 return ExprError();
3419 }
3420
3421 if (!isStore) {
3422 TheCall->setType(ValType);
3423 return TheCallResult;
3424 }
3425
3426 ExprResult ValArg = TheCall->getArg(0);
3427 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3428 Context, ValType, /*consume*/ false);
3429 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3430 if (ValArg.isInvalid())
3431 return ExprError();
3432
3433 TheCall->setArg(0, ValArg.get());
3434 TheCall->setType(Context.VoidTy);
3435 return TheCallResult;
3436}
3437
Chris Lattner6436fb62009-02-18 06:01:06 +00003438/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003439/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003440/// Note: It might also make sense to do the UTF-16 conversion here (would
3441/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003442bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003443 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003444 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3445
Douglas Gregorfb65e592011-07-27 05:40:30 +00003446 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003447 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3448 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003449 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003450 }
Mike Stump11289f42009-09-09 15:08:12 +00003451
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003452 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003453 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003454 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003455 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3456 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3457 llvm::UTF16 *ToPtr = &ToBuf[0];
3458
3459 llvm::ConversionResult Result =
3460 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3461 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003462 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003463 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003464 Diag(Arg->getLocStart(),
3465 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3466 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003467 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003468}
3469
Mehdi Amini06d367c2016-10-24 20:39:34 +00003470/// CheckObjCString - Checks that the format string argument to the os_log()
3471/// and os_trace() functions is correct, and converts it to const char *.
3472ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3473 Arg = Arg->IgnoreParenCasts();
3474 auto *Literal = dyn_cast<StringLiteral>(Arg);
3475 if (!Literal) {
3476 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3477 Literal = ObjcLiteral->getString();
3478 }
3479 }
3480
3481 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3482 return ExprError(
3483 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3484 << Arg->getSourceRange());
3485 }
3486
3487 ExprResult Result(Literal);
3488 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3489 InitializedEntity Entity =
3490 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3491 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3492 return Result;
3493}
3494
Charles Davisc7d5c942015-09-17 20:55:33 +00003495/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3496/// for validity. Emit an error and return true on failure; return false
3497/// on success.
3498bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003499 Expr *Fn = TheCall->getCallee();
3500 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003501 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003502 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003503 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3504 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003505 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003506 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003507 return true;
3508 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003509
3510 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003511 return Diag(TheCall->getLocEnd(),
3512 diag::err_typecheck_call_too_few_args_at_least)
3513 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003514 }
3515
John McCall29ad95b2011-08-27 01:09:30 +00003516 // Type-check the first argument normally.
3517 if (checkBuiltinArgument(*this, TheCall, 0))
3518 return true;
3519
Chris Lattnere202e6a2007-12-20 00:05:45 +00003520 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003521 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003522 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003523 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003524 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003525 else if (FunctionDecl *FD = getCurFunctionDecl())
3526 isVariadic = FD->isVariadic();
3527 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003528 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003529
Chris Lattnere202e6a2007-12-20 00:05:45 +00003530 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003531 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3532 return true;
3533 }
Mike Stump11289f42009-09-09 15:08:12 +00003534
Chris Lattner43be2e62007-12-19 23:59:04 +00003535 // Verify that the second argument to the builtin is the last argument of the
3536 // current function or method.
3537 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003538 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003539
Nico Weber9eea7642013-05-24 23:31:57 +00003540 // These are valid if SecondArgIsLastNamedArgument is false after the next
3541 // block.
3542 QualType Type;
3543 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003544 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003545
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003546 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3547 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003548 // FIXME: This isn't correct for methods (results in bogus warning).
3549 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003550 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003551 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003552 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003553 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003554 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003555 else
David Majnemera3debed2016-06-24 05:33:44 +00003556 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003557 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003558
3559 Type = PV->getType();
3560 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003561 IsCRegister =
3562 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003563 }
3564 }
Mike Stump11289f42009-09-09 15:08:12 +00003565
Chris Lattner43be2e62007-12-19 23:59:04 +00003566 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003567 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003568 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003569 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003570 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3571 // Promotable integers are UB, but enumerations need a bit of
3572 // extra checking to see what their promotable type actually is.
3573 if (!Type->isPromotableIntegerType())
3574 return false;
3575 if (!Type->isEnumeralType())
3576 return true;
3577 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3578 return !(ED &&
3579 Context.typesAreCompatible(ED->getPromotionType(), Type));
3580 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003581 unsigned Reason = 0;
3582 if (Type->isReferenceType()) Reason = 1;
3583 else if (IsCRegister) Reason = 2;
3584 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003585 Diag(ParamLoc, diag::note_parameter_type) << Type;
3586 }
3587
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003588 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003589 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003590}
Chris Lattner43be2e62007-12-19 23:59:04 +00003591
Charles Davisc7d5c942015-09-17 20:55:33 +00003592/// Check the arguments to '__builtin_va_start' for validity, and that
3593/// it was called from a function of the native ABI.
3594/// Emit an error and return true on failure; return false on success.
3595bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3596 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3597 // On x64 Windows, don't allow this in System V ABI functions.
3598 // (Yes, that means there's no corresponding way to support variadic
3599 // System V ABI functions on Windows.)
3600 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3601 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3602 clang::CallingConv CC = CC_C;
3603 if (const FunctionDecl *FD = getCurFunctionDecl())
3604 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3605 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3606 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3607 return Diag(TheCall->getCallee()->getLocStart(),
3608 diag::err_va_start_used_in_wrong_abi_function)
3609 << (OS != llvm::Triple::Win32);
3610 }
3611 return SemaBuiltinVAStartImpl(TheCall);
3612}
3613
3614/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3615/// it was called from a Win64 ABI function.
3616/// Emit an error and return true on failure; return false on success.
3617bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3618 // This only makes sense for x86-64.
3619 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3620 Expr *Callee = TheCall->getCallee();
3621 if (TT.getArch() != llvm::Triple::x86_64)
3622 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3623 // Don't allow this in System V ABI functions.
3624 clang::CallingConv CC = CC_C;
3625 if (const FunctionDecl *FD = getCurFunctionDecl())
3626 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3627 if (CC == CC_X86_64SysV ||
3628 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3629 return Diag(Callee->getLocStart(),
3630 diag::err_ms_va_start_used_in_sysv_function);
3631 return SemaBuiltinVAStartImpl(TheCall);
3632}
3633
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003634bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3635 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3636 // const char *named_addr);
3637
3638 Expr *Func = Call->getCallee();
3639
3640 if (Call->getNumArgs() < 3)
3641 return Diag(Call->getLocEnd(),
3642 diag::err_typecheck_call_too_few_args_at_least)
3643 << 0 /*function call*/ << 3 << Call->getNumArgs();
3644
3645 // Determine whether the current function is variadic or not.
3646 bool IsVariadic;
3647 if (BlockScopeInfo *CurBlock = getCurBlock())
3648 IsVariadic = CurBlock->TheDecl->isVariadic();
3649 else if (FunctionDecl *FD = getCurFunctionDecl())
3650 IsVariadic = FD->isVariadic();
3651 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3652 IsVariadic = MD->isVariadic();
3653 else
3654 llvm_unreachable("unexpected statement type");
3655
3656 if (!IsVariadic) {
3657 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3658 return true;
3659 }
3660
3661 // Type-check the first argument normally.
3662 if (checkBuiltinArgument(*this, Call, 0))
3663 return true;
3664
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003665 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003666 unsigned ArgNo;
3667 QualType Type;
3668 } ArgumentTypes[] = {
3669 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3670 { 2, Context.getSizeType() },
3671 };
3672
3673 for (const auto &AT : ArgumentTypes) {
3674 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3675 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3676 continue;
3677 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3678 << Arg->getType() << AT.Type << 1 /* different class */
3679 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3680 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3681 }
3682
3683 return false;
3684}
3685
Chris Lattner2da14fb2007-12-20 00:26:33 +00003686/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3687/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003688bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3689 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003690 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003691 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003692 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003693 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003694 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003695 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003696 << SourceRange(TheCall->getArg(2)->getLocStart(),
3697 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003698
John Wiegley01296292011-04-08 18:41:53 +00003699 ExprResult OrigArg0 = TheCall->getArg(0);
3700 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003701
Chris Lattner2da14fb2007-12-20 00:26:33 +00003702 // Do standard promotions between the two arguments, returning their common
3703 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003704 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003705 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3706 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003707
3708 // Make sure any conversions are pushed back into the call; this is
3709 // type safe since unordered compare builtins are declared as "_Bool
3710 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003711 TheCall->setArg(0, OrigArg0.get());
3712 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003713
John Wiegley01296292011-04-08 18:41:53 +00003714 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003715 return false;
3716
Chris Lattner2da14fb2007-12-20 00:26:33 +00003717 // If the common type isn't a real floating type, then the arguments were
3718 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003719 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003720 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003721 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003722 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3723 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003724
Chris Lattner2da14fb2007-12-20 00:26:33 +00003725 return false;
3726}
3727
Benjamin Kramer634fc102010-02-15 22:42:31 +00003728/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3729/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003730/// to check everything. We expect the last argument to be a floating point
3731/// value.
3732bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3733 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003734 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003735 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003736 if (TheCall->getNumArgs() > NumArgs)
3737 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003738 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003739 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003740 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003741 (*(TheCall->arg_end()-1))->getLocEnd());
3742
Benjamin Kramer64aae502010-02-16 10:07:31 +00003743 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003744
Eli Friedman7e4faac2009-08-31 20:06:00 +00003745 if (OrigArg->isTypeDependent())
3746 return false;
3747
Chris Lattner68784ef2010-05-06 05:50:07 +00003748 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003749 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003750 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003751 diag::err_typecheck_call_invalid_unary_fp)
3752 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003753
Neil Hickey88c0fac2016-12-13 16:22:50 +00003754 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003755 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003756 // Only remove standard FloatCasts, leaving other casts inplace
3757 if (Cast->getCastKind() == CK_FloatingCast) {
3758 Expr *CastArg = Cast->getSubExpr();
3759 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3760 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3761 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3762 "promotion from float to either float or double is the only expected cast here");
3763 Cast->setSubExpr(nullptr);
3764 TheCall->setArg(NumArgs-1, CastArg);
3765 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003766 }
3767 }
3768
Eli Friedman7e4faac2009-08-31 20:06:00 +00003769 return false;
3770}
3771
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003772/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3773// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003774ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003775 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003776 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003777 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003778 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3779 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003780
Nate Begemana0110022010-06-08 00:16:34 +00003781 // Determine which of the following types of shufflevector we're checking:
3782 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003783 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003784 QualType resType = TheCall->getArg(0)->getType();
3785 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003786
Douglas Gregorc25f7662009-05-19 22:10:17 +00003787 if (!TheCall->getArg(0)->isTypeDependent() &&
3788 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003789 QualType LHSType = TheCall->getArg(0)->getType();
3790 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003791
Craig Topperbaca3892013-07-29 06:47:04 +00003792 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3793 return ExprError(Diag(TheCall->getLocStart(),
3794 diag::err_shufflevector_non_vector)
3795 << SourceRange(TheCall->getArg(0)->getLocStart(),
3796 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003797
Nate Begemana0110022010-06-08 00:16:34 +00003798 numElements = LHSType->getAs<VectorType>()->getNumElements();
3799 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003800
Nate Begemana0110022010-06-08 00:16:34 +00003801 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3802 // with mask. If so, verify that RHS is an integer vector type with the
3803 // same number of elts as lhs.
3804 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003805 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003806 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003807 return ExprError(Diag(TheCall->getLocStart(),
3808 diag::err_shufflevector_incompatible_vector)
3809 << SourceRange(TheCall->getArg(1)->getLocStart(),
3810 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003811 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003812 return ExprError(Diag(TheCall->getLocStart(),
3813 diag::err_shufflevector_incompatible_vector)
3814 << SourceRange(TheCall->getArg(0)->getLocStart(),
3815 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003816 } else if (numElements != numResElements) {
3817 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003818 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003819 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003820 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003821 }
3822
3823 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003824 if (TheCall->getArg(i)->isTypeDependent() ||
3825 TheCall->getArg(i)->isValueDependent())
3826 continue;
3827
Nate Begemana0110022010-06-08 00:16:34 +00003828 llvm::APSInt Result(32);
3829 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3830 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003831 diag::err_shufflevector_nonconstant_argument)
3832 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003833
Craig Topper50ad5b72013-08-03 17:40:38 +00003834 // Allow -1 which will be translated to undef in the IR.
3835 if (Result.isSigned() && Result.isAllOnesValue())
3836 continue;
3837
Chris Lattner7ab824e2008-08-10 02:05:13 +00003838 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003839 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003840 diag::err_shufflevector_argument_too_large)
3841 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003842 }
3843
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003844 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003845
Chris Lattner7ab824e2008-08-10 02:05:13 +00003846 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003847 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003848 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003849 }
3850
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003851 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3852 TheCall->getCallee()->getLocStart(),
3853 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003854}
Chris Lattner43be2e62007-12-19 23:59:04 +00003855
Hal Finkelc4d7c822013-09-18 03:29:45 +00003856/// SemaConvertVectorExpr - Handle __builtin_convertvector
3857ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3858 SourceLocation BuiltinLoc,
3859 SourceLocation RParenLoc) {
3860 ExprValueKind VK = VK_RValue;
3861 ExprObjectKind OK = OK_Ordinary;
3862 QualType DstTy = TInfo->getType();
3863 QualType SrcTy = E->getType();
3864
3865 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3866 return ExprError(Diag(BuiltinLoc,
3867 diag::err_convertvector_non_vector)
3868 << E->getSourceRange());
3869 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3870 return ExprError(Diag(BuiltinLoc,
3871 diag::err_convertvector_non_vector_type));
3872
3873 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3874 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3875 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3876 if (SrcElts != DstElts)
3877 return ExprError(Diag(BuiltinLoc,
3878 diag::err_convertvector_incompatible_vector)
3879 << E->getSourceRange());
3880 }
3881
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003882 return new (Context)
3883 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003884}
3885
Daniel Dunbarb7257262008-07-21 22:59:13 +00003886/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3887// This is declared to take (const void*, ...) and can take two
3888// optional constant int args.
3889bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003890 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003891
Chris Lattner3b054132008-11-19 05:08:23 +00003892 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003893 return Diag(TheCall->getLocEnd(),
3894 diag::err_typecheck_call_too_many_args_at_most)
3895 << 0 /*function call*/ << 3 << NumArgs
3896 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003897
3898 // Argument 0 is checked for us and the remaining arguments must be
3899 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003900 for (unsigned i = 1; i != NumArgs; ++i)
3901 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003902 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003903
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003904 return false;
3905}
3906
Hal Finkelf0417332014-07-17 14:25:55 +00003907/// SemaBuiltinAssume - Handle __assume (MS Extension).
3908// __assume does not evaluate its arguments, and should warn if its argument
3909// has side effects.
3910bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3911 Expr *Arg = TheCall->getArg(0);
3912 if (Arg->isInstantiationDependent()) return false;
3913
3914 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003915 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003916 << Arg->getSourceRange()
3917 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3918
3919 return false;
3920}
3921
David Majnemer86b1bfa2016-10-31 18:07:57 +00003922/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003923/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3924/// than 8.
3925bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3926 // The alignment must be a constant integer.
3927 Expr *Arg = TheCall->getArg(1);
3928
3929 // We can't check the value of a dependent argument.
3930 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003931 if (const auto *UE =
3932 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3933 if (UE->getKind() == UETT_AlignOf)
3934 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3935 << Arg->getSourceRange();
3936
David Majnemer51169932016-10-31 05:37:48 +00003937 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3938
3939 if (!Result.isPowerOf2())
3940 return Diag(TheCall->getLocStart(),
3941 diag::err_alignment_not_power_of_two)
3942 << Arg->getSourceRange();
3943
3944 if (Result < Context.getCharWidth())
3945 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3946 << (unsigned)Context.getCharWidth()
3947 << Arg->getSourceRange();
3948
3949 if (Result > INT32_MAX)
3950 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3951 << INT32_MAX
3952 << Arg->getSourceRange();
3953 }
3954
3955 return false;
3956}
3957
3958/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003959/// as (const void*, size_t, ...) and can take one optional constant int arg.
3960bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3961 unsigned NumArgs = TheCall->getNumArgs();
3962
3963 if (NumArgs > 3)
3964 return Diag(TheCall->getLocEnd(),
3965 diag::err_typecheck_call_too_many_args_at_most)
3966 << 0 /*function call*/ << 3 << NumArgs
3967 << TheCall->getSourceRange();
3968
3969 // The alignment must be a constant integer.
3970 Expr *Arg = TheCall->getArg(1);
3971
3972 // We can't check the value of a dependent argument.
3973 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3974 llvm::APSInt Result;
3975 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3976 return true;
3977
3978 if (!Result.isPowerOf2())
3979 return Diag(TheCall->getLocStart(),
3980 diag::err_alignment_not_power_of_two)
3981 << Arg->getSourceRange();
3982 }
3983
3984 if (NumArgs > 2) {
3985 ExprResult Arg(TheCall->getArg(2));
3986 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3987 Context.getSizeType(), false);
3988 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3989 if (Arg.isInvalid()) return true;
3990 TheCall->setArg(2, Arg.get());
3991 }
Hal Finkelf0417332014-07-17 14:25:55 +00003992
3993 return false;
3994}
3995
Mehdi Amini06d367c2016-10-24 20:39:34 +00003996bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3997 unsigned BuiltinID =
3998 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3999 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4000
4001 unsigned NumArgs = TheCall->getNumArgs();
4002 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4003 if (NumArgs < NumRequiredArgs) {
4004 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4005 << 0 /* function call */ << NumRequiredArgs << NumArgs
4006 << TheCall->getSourceRange();
4007 }
4008 if (NumArgs >= NumRequiredArgs + 0x100) {
4009 return Diag(TheCall->getLocEnd(),
4010 diag::err_typecheck_call_too_many_args_at_most)
4011 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4012 << TheCall->getSourceRange();
4013 }
4014 unsigned i = 0;
4015
4016 // For formatting call, check buffer arg.
4017 if (!IsSizeCall) {
4018 ExprResult Arg(TheCall->getArg(i));
4019 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4020 Context, Context.VoidPtrTy, false);
4021 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4022 if (Arg.isInvalid())
4023 return true;
4024 TheCall->setArg(i, Arg.get());
4025 i++;
4026 }
4027
4028 // Check string literal arg.
4029 unsigned FormatIdx = i;
4030 {
4031 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4032 if (Arg.isInvalid())
4033 return true;
4034 TheCall->setArg(i, Arg.get());
4035 i++;
4036 }
4037
4038 // Make sure variadic args are scalar.
4039 unsigned FirstDataArg = i;
4040 while (i < NumArgs) {
4041 ExprResult Arg = DefaultVariadicArgumentPromotion(
4042 TheCall->getArg(i), VariadicFunction, nullptr);
4043 if (Arg.isInvalid())
4044 return true;
4045 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4046 if (ArgSize.getQuantity() >= 0x100) {
4047 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4048 << i << (int)ArgSize.getQuantity() << 0xff
4049 << TheCall->getSourceRange();
4050 }
4051 TheCall->setArg(i, Arg.get());
4052 i++;
4053 }
4054
4055 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4056 // call to avoid duplicate diagnostics.
4057 if (!IsSizeCall) {
4058 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4059 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4060 bool Success = CheckFormatArguments(
4061 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4062 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4063 CheckedVarArgs);
4064 if (!Success)
4065 return true;
4066 }
4067
4068 if (IsSizeCall) {
4069 TheCall->setType(Context.getSizeType());
4070 } else {
4071 TheCall->setType(Context.VoidPtrTy);
4072 }
4073 return false;
4074}
4075
Eric Christopher8d0c6212010-04-17 02:26:23 +00004076/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4077/// TheCall is a constant expression.
4078bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4079 llvm::APSInt &Result) {
4080 Expr *Arg = TheCall->getArg(ArgNum);
4081 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4082 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4083
4084 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4085
4086 if (!Arg->isIntegerConstantExpr(Result, Context))
4087 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004088 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004089
Chris Lattnerd545ad12009-09-23 06:06:36 +00004090 return false;
4091}
4092
Richard Sandiford28940af2014-04-16 08:47:51 +00004093/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4094/// TheCall is a constant expression in the range [Low, High].
4095bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4096 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004097 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004098
4099 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004100 Expr *Arg = TheCall->getArg(ArgNum);
4101 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004102 return false;
4103
Eric Christopher8d0c6212010-04-17 02:26:23 +00004104 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004105 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004106 return true;
4107
Richard Sandiford28940af2014-04-16 08:47:51 +00004108 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004109 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004110 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004111
4112 return false;
4113}
4114
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004115/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4116/// TheCall is a constant expression is a multiple of Num..
4117bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4118 unsigned Num) {
4119 llvm::APSInt Result;
4120
4121 // We can't check the value of a dependent argument.
4122 Expr *Arg = TheCall->getArg(ArgNum);
4123 if (Arg->isTypeDependent() || Arg->isValueDependent())
4124 return false;
4125
4126 // Check constant-ness first.
4127 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4128 return true;
4129
4130 if (Result.getSExtValue() % Num != 0)
4131 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4132 << Num << Arg->getSourceRange();
4133
4134 return false;
4135}
4136
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004137/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4138/// TheCall is an ARM/AArch64 special register string literal.
4139bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4140 int ArgNum, unsigned ExpectedFieldNum,
4141 bool AllowName) {
4142 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4143 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4144 BuiltinID == ARM::BI__builtin_arm_rsr ||
4145 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4146 BuiltinID == ARM::BI__builtin_arm_wsr ||
4147 BuiltinID == ARM::BI__builtin_arm_wsrp;
4148 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4149 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4150 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4151 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4152 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4153 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4154 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4155
4156 // We can't check the value of a dependent argument.
4157 Expr *Arg = TheCall->getArg(ArgNum);
4158 if (Arg->isTypeDependent() || Arg->isValueDependent())
4159 return false;
4160
4161 // Check if the argument is a string literal.
4162 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4163 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4164 << Arg->getSourceRange();
4165
4166 // Check the type of special register given.
4167 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4168 SmallVector<StringRef, 6> Fields;
4169 Reg.split(Fields, ":");
4170
4171 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4172 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4173 << Arg->getSourceRange();
4174
4175 // If the string is the name of a register then we cannot check that it is
4176 // valid here but if the string is of one the forms described in ACLE then we
4177 // can check that the supplied fields are integers and within the valid
4178 // ranges.
4179 if (Fields.size() > 1) {
4180 bool FiveFields = Fields.size() == 5;
4181
4182 bool ValidString = true;
4183 if (IsARMBuiltin) {
4184 ValidString &= Fields[0].startswith_lower("cp") ||
4185 Fields[0].startswith_lower("p");
4186 if (ValidString)
4187 Fields[0] =
4188 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4189
4190 ValidString &= Fields[2].startswith_lower("c");
4191 if (ValidString)
4192 Fields[2] = Fields[2].drop_front(1);
4193
4194 if (FiveFields) {
4195 ValidString &= Fields[3].startswith_lower("c");
4196 if (ValidString)
4197 Fields[3] = Fields[3].drop_front(1);
4198 }
4199 }
4200
4201 SmallVector<int, 5> Ranges;
4202 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004203 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004204 else
4205 Ranges.append({15, 7, 15});
4206
4207 for (unsigned i=0; i<Fields.size(); ++i) {
4208 int IntField;
4209 ValidString &= !Fields[i].getAsInteger(10, IntField);
4210 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4211 }
4212
4213 if (!ValidString)
4214 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4215 << Arg->getSourceRange();
4216
4217 } else if (IsAArch64Builtin && Fields.size() == 1) {
4218 // If the register name is one of those that appear in the condition below
4219 // and the special register builtin being used is one of the write builtins,
4220 // then we require that the argument provided for writing to the register
4221 // is an integer constant expression. This is because it will be lowered to
4222 // an MSR (immediate) instruction, so we need to know the immediate at
4223 // compile time.
4224 if (TheCall->getNumArgs() != 2)
4225 return false;
4226
4227 std::string RegLower = Reg.lower();
4228 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4229 RegLower != "pan" && RegLower != "uao")
4230 return false;
4231
4232 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4233 }
4234
4235 return false;
4236}
4237
Eli Friedmanc97d0142009-05-03 06:04:26 +00004238/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004239/// This checks that the target supports __builtin_longjmp and
4240/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004241bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004242 if (!Context.getTargetInfo().hasSjLjLowering())
4243 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4244 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4245
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004246 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004247 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004248
Eric Christopher8d0c6212010-04-17 02:26:23 +00004249 // TODO: This is less than ideal. Overload this to take a value.
4250 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4251 return true;
4252
4253 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004254 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4255 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4256
4257 return false;
4258}
4259
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004260/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4261/// This checks that the target supports __builtin_setjmp.
4262bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4263 if (!Context.getTargetInfo().hasSjLjLowering())
4264 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4265 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4266 return false;
4267}
4268
Richard Smithd7293d72013-08-05 18:49:43 +00004269namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004270class UncoveredArgHandler {
4271 enum { Unknown = -1, AllCovered = -2 };
4272 signed FirstUncoveredArg;
4273 SmallVector<const Expr *, 4> DiagnosticExprs;
4274
4275public:
4276 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4277
4278 bool hasUncoveredArg() const {
4279 return (FirstUncoveredArg >= 0);
4280 }
4281
4282 unsigned getUncoveredArg() const {
4283 assert(hasUncoveredArg() && "no uncovered argument");
4284 return FirstUncoveredArg;
4285 }
4286
4287 void setAllCovered() {
4288 // A string has been found with all arguments covered, so clear out
4289 // the diagnostics.
4290 DiagnosticExprs.clear();
4291 FirstUncoveredArg = AllCovered;
4292 }
4293
4294 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4295 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4296
4297 // Don't update if a previous string covers all arguments.
4298 if (FirstUncoveredArg == AllCovered)
4299 return;
4300
4301 // UncoveredArgHandler tracks the highest uncovered argument index
4302 // and with it all the strings that match this index.
4303 if (NewFirstUncoveredArg == FirstUncoveredArg)
4304 DiagnosticExprs.push_back(StrExpr);
4305 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4306 DiagnosticExprs.clear();
4307 DiagnosticExprs.push_back(StrExpr);
4308 FirstUncoveredArg = NewFirstUncoveredArg;
4309 }
4310 }
4311
4312 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4313};
4314
Richard Smithd7293d72013-08-05 18:49:43 +00004315enum StringLiteralCheckType {
4316 SLCT_NotALiteral,
4317 SLCT_UncheckedLiteral,
4318 SLCT_CheckedLiteral
4319};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004320} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004321
Stephen Hines648c3692016-09-16 01:07:04 +00004322static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4323 BinaryOperatorKind BinOpKind,
4324 bool AddendIsRight) {
4325 unsigned BitWidth = Offset.getBitWidth();
4326 unsigned AddendBitWidth = Addend.getBitWidth();
4327 // There might be negative interim results.
4328 if (Addend.isUnsigned()) {
4329 Addend = Addend.zext(++AddendBitWidth);
4330 Addend.setIsSigned(true);
4331 }
4332 // Adjust the bit width of the APSInts.
4333 if (AddendBitWidth > BitWidth) {
4334 Offset = Offset.sext(AddendBitWidth);
4335 BitWidth = AddendBitWidth;
4336 } else if (BitWidth > AddendBitWidth) {
4337 Addend = Addend.sext(BitWidth);
4338 }
4339
4340 bool Ov = false;
4341 llvm::APSInt ResOffset = Offset;
4342 if (BinOpKind == BO_Add)
4343 ResOffset = Offset.sadd_ov(Addend, Ov);
4344 else {
4345 assert(AddendIsRight && BinOpKind == BO_Sub &&
4346 "operator must be add or sub with addend on the right");
4347 ResOffset = Offset.ssub_ov(Addend, Ov);
4348 }
4349
4350 // We add an offset to a pointer here so we should support an offset as big as
4351 // possible.
4352 if (Ov) {
4353 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004354 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004355 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4356 return;
4357 }
4358
4359 Offset = ResOffset;
4360}
4361
4362namespace {
4363// This is a wrapper class around StringLiteral to support offsetted string
4364// literals as format strings. It takes the offset into account when returning
4365// the string and its length or the source locations to display notes correctly.
4366class FormatStringLiteral {
4367 const StringLiteral *FExpr;
4368 int64_t Offset;
4369
4370 public:
4371 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4372 : FExpr(fexpr), Offset(Offset) {}
4373
4374 StringRef getString() const {
4375 return FExpr->getString().drop_front(Offset);
4376 }
4377
4378 unsigned getByteLength() const {
4379 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4380 }
4381 unsigned getLength() const { return FExpr->getLength() - Offset; }
4382 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4383
4384 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4385
4386 QualType getType() const { return FExpr->getType(); }
4387
4388 bool isAscii() const { return FExpr->isAscii(); }
4389 bool isWide() const { return FExpr->isWide(); }
4390 bool isUTF8() const { return FExpr->isUTF8(); }
4391 bool isUTF16() const { return FExpr->isUTF16(); }
4392 bool isUTF32() const { return FExpr->isUTF32(); }
4393 bool isPascal() const { return FExpr->isPascal(); }
4394
4395 SourceLocation getLocationOfByte(
4396 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4397 const TargetInfo &Target, unsigned *StartToken = nullptr,
4398 unsigned *StartTokenByteOffset = nullptr) const {
4399 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4400 StartToken, StartTokenByteOffset);
4401 }
4402
4403 SourceLocation getLocStart() const LLVM_READONLY {
4404 return FExpr->getLocStart().getLocWithOffset(Offset);
4405 }
4406 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4407};
4408} // end anonymous namespace
4409
4410static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004411 const Expr *OrigFormatExpr,
4412 ArrayRef<const Expr *> Args,
4413 bool HasVAListArg, unsigned format_idx,
4414 unsigned firstDataArg,
4415 Sema::FormatStringType Type,
4416 bool inFunctionCall,
4417 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004418 llvm::SmallBitVector &CheckedVarArgs,
4419 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004420
Richard Smith55ce3522012-06-25 20:30:08 +00004421// Determine if an expression is a string literal or constant string.
4422// If this function returns false on the arguments to a function expecting a
4423// format string, we will usually need to emit a warning.
4424// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004425static StringLiteralCheckType
4426checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4427 bool HasVAListArg, unsigned format_idx,
4428 unsigned firstDataArg, Sema::FormatStringType Type,
4429 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004430 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004431 UncoveredArgHandler &UncoveredArg,
4432 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004433 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004434 assert(Offset.isSigned() && "invalid offset");
4435
Douglas Gregorc25f7662009-05-19 22:10:17 +00004436 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004437 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004438
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004439 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004440
Richard Smithd7293d72013-08-05 18:49:43 +00004441 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004442 // Technically -Wformat-nonliteral does not warn about this case.
4443 // The behavior of printf and friends in this case is implementation
4444 // dependent. Ideally if the format string cannot be null then
4445 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004446 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004447
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004448 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004449 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004450 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004451 // The expression is a literal if both sub-expressions were, and it was
4452 // completely checked only if both sub-expressions were checked.
4453 const AbstractConditionalOperator *C =
4454 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004455
4456 // Determine whether it is necessary to check both sub-expressions, for
4457 // example, because the condition expression is a constant that can be
4458 // evaluated at compile time.
4459 bool CheckLeft = true, CheckRight = true;
4460
4461 bool Cond;
4462 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4463 if (Cond)
4464 CheckRight = false;
4465 else
4466 CheckLeft = false;
4467 }
4468
Stephen Hines648c3692016-09-16 01:07:04 +00004469 // We need to maintain the offsets for the right and the left hand side
4470 // separately to check if every possible indexed expression is a valid
4471 // string literal. They might have different offsets for different string
4472 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004473 StringLiteralCheckType Left;
4474 if (!CheckLeft)
4475 Left = SLCT_UncheckedLiteral;
4476 else {
4477 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4478 HasVAListArg, format_idx, firstDataArg,
4479 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004480 CheckedVarArgs, UncoveredArg, Offset);
4481 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004482 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004483 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004484 }
4485
Richard Smith55ce3522012-06-25 20:30:08 +00004486 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004487 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004488 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004489 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004490 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004491
4492 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004493 }
4494
4495 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004496 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4497 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004498 }
4499
John McCallc07a0c72011-02-17 10:25:35 +00004500 case Stmt::OpaqueValueExprClass:
4501 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4502 E = src;
4503 goto tryAgain;
4504 }
Richard Smith55ce3522012-06-25 20:30:08 +00004505 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004506
Ted Kremeneka8890832011-02-24 23:03:04 +00004507 case Stmt::PredefinedExprClass:
4508 // While __func__, etc., are technically not string literals, they
4509 // cannot contain format specifiers and thus are not a security
4510 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004511 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004512
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004513 case Stmt::DeclRefExprClass: {
4514 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004515
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004516 // As an exception, do not flag errors for variables binding to
4517 // const string literals.
4518 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4519 bool isConstant = false;
4520 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004521
Richard Smithd7293d72013-08-05 18:49:43 +00004522 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4523 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004524 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004525 isConstant = T.isConstant(S.Context) &&
4526 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004527 } else if (T->isObjCObjectPointerType()) {
4528 // In ObjC, there is usually no "const ObjectPointer" type,
4529 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004530 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004531 }
Mike Stump11289f42009-09-09 15:08:12 +00004532
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004533 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004534 if (const Expr *Init = VD->getAnyInitializer()) {
4535 // Look through initializers like const char c[] = { "foo" }
4536 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4537 if (InitList->isStringLiteralInit())
4538 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4539 }
Richard Smithd7293d72013-08-05 18:49:43 +00004540 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004541 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004542 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004543 /*InFunctionCall*/ false, CheckedVarArgs,
4544 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004545 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004546 }
Mike Stump11289f42009-09-09 15:08:12 +00004547
Anders Carlssonb012ca92009-06-28 19:55:58 +00004548 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4549 // special check to see if the format string is a function parameter
4550 // of the function calling the printf function. If the function
4551 // has an attribute indicating it is a printf-like function, then we
4552 // should suppress warnings concerning non-literals being used in a call
4553 // to a vprintf function. For example:
4554 //
4555 // void
4556 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4557 // va_list ap;
4558 // va_start(ap, fmt);
4559 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4560 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004561 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004562 if (HasVAListArg) {
4563 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4564 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4565 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004566 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004567 // adjust for implicit parameter
4568 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4569 if (MD->isInstance())
4570 ++PVIndex;
4571 // We also check if the formats are compatible.
4572 // We can't pass a 'scanf' string to a 'printf' function.
4573 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004574 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004575 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004576 }
4577 }
4578 }
4579 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004580 }
Mike Stump11289f42009-09-09 15:08:12 +00004581
Richard Smith55ce3522012-06-25 20:30:08 +00004582 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004583 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004584
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004585 case Stmt::CallExprClass:
4586 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004587 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004588 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4589 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4590 unsigned ArgIndex = FA->getFormatIdx();
4591 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4592 if (MD->isInstance())
4593 --ArgIndex;
4594 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004595
Richard Smithd7293d72013-08-05 18:49:43 +00004596 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004597 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004598 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004599 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004600 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4601 unsigned BuiltinID = FD->getBuiltinID();
4602 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4603 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4604 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004605 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004606 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004607 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004608 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004609 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004610 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004611 }
4612 }
Mike Stump11289f42009-09-09 15:08:12 +00004613
Richard Smith55ce3522012-06-25 20:30:08 +00004614 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004615 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004616 case Stmt::ObjCMessageExprClass: {
4617 const auto *ME = cast<ObjCMessageExpr>(E);
4618 if (const auto *ND = ME->getMethodDecl()) {
4619 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4620 unsigned ArgIndex = FA->getFormatIdx();
4621 const Expr *Arg = ME->getArg(ArgIndex - 1);
4622 return checkFormatStringExpr(
4623 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4624 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4625 }
4626 }
4627
4628 return SLCT_NotALiteral;
4629 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004630 case Stmt::ObjCStringLiteralClass:
4631 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004632 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004633
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004634 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004635 StrE = ObjCFExpr->getString();
4636 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004637 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004638
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004639 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004640 if (Offset.isNegative() || Offset > StrE->getLength()) {
4641 // TODO: It would be better to have an explicit warning for out of
4642 // bounds literals.
4643 return SLCT_NotALiteral;
4644 }
4645 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4646 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004647 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004648 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004649 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004650 }
Mike Stump11289f42009-09-09 15:08:12 +00004651
Richard Smith55ce3522012-06-25 20:30:08 +00004652 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004653 }
Stephen Hines648c3692016-09-16 01:07:04 +00004654 case Stmt::BinaryOperatorClass: {
4655 llvm::APSInt LResult;
4656 llvm::APSInt RResult;
4657
4658 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4659
4660 // A string literal + an int offset is still a string literal.
4661 if (BinOp->isAdditiveOp()) {
4662 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4663 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4664
4665 if (LIsInt != RIsInt) {
4666 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4667
4668 if (LIsInt) {
4669 if (BinOpKind == BO_Add) {
4670 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4671 E = BinOp->getRHS();
4672 goto tryAgain;
4673 }
4674 } else {
4675 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4676 E = BinOp->getLHS();
4677 goto tryAgain;
4678 }
4679 }
Stephen Hines648c3692016-09-16 01:07:04 +00004680 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004681
4682 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004683 }
4684 case Stmt::UnaryOperatorClass: {
4685 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4686 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4687 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4688 llvm::APSInt IndexResult;
4689 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4690 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4691 E = ASE->getBase();
4692 goto tryAgain;
4693 }
4694 }
4695
4696 return SLCT_NotALiteral;
4697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004699 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004700 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004701 }
4702}
4703
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004704Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004705 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004706 .Case("scanf", FST_Scanf)
4707 .Cases("printf", "printf0", FST_Printf)
4708 .Cases("NSString", "CFString", FST_NSString)
4709 .Case("strftime", FST_Strftime)
4710 .Case("strfmon", FST_Strfmon)
4711 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4712 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4713 .Case("os_trace", FST_OSLog)
4714 .Case("os_log", FST_OSLog)
4715 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004716}
4717
Jordan Rose3e0ec582012-07-19 18:10:23 +00004718/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004719/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004720/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004721bool Sema::CheckFormatArguments(const FormatAttr *Format,
4722 ArrayRef<const Expr *> Args,
4723 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004724 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004725 SourceLocation Loc, SourceRange Range,
4726 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004727 FormatStringInfo FSI;
4728 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004729 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004730 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004731 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004732 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004733}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004734
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004735bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004736 bool HasVAListArg, unsigned format_idx,
4737 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004738 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004739 SourceLocation Loc, SourceRange Range,
4740 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004741 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004742 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004743 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004744 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004745 }
Mike Stump11289f42009-09-09 15:08:12 +00004746
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004747 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004748
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004749 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004750 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004751 // Dynamically generated format strings are difficult to
4752 // automatically vet at compile time. Requiring that format strings
4753 // are string literals: (1) permits the checking of format strings by
4754 // the compiler and thereby (2) can practically remove the source of
4755 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004756
Mike Stump11289f42009-09-09 15:08:12 +00004757 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004758 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004759 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004760 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004761 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004762 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004763 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4764 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004765 /*IsFunctionCall*/ true, CheckedVarArgs,
4766 UncoveredArg,
4767 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004768
4769 // Generate a diagnostic where an uncovered argument is detected.
4770 if (UncoveredArg.hasUncoveredArg()) {
4771 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4772 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4773 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4774 }
4775
Richard Smith55ce3522012-06-25 20:30:08 +00004776 if (CT != SLCT_NotALiteral)
4777 // Literal format string found, check done!
4778 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004779
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004780 // Strftime is particular as it always uses a single 'time' argument,
4781 // so it is safe to pass a non-literal string.
4782 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004783 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004784
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004785 // Do not emit diag when the string param is a macro expansion and the
4786 // format is either NSString or CFString. This is a hack to prevent
4787 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4788 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004789 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4790 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004791 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004792
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004793 // If there are no arguments specified, warn with -Wformat-security, otherwise
4794 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004795 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004796 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4797 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004798 switch (Type) {
4799 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004800 break;
4801 case FST_Kprintf:
4802 case FST_FreeBSDKPrintf:
4803 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004804 Diag(FormatLoc, diag::note_format_security_fixit)
4805 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004806 break;
4807 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004808 Diag(FormatLoc, diag::note_format_security_fixit)
4809 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004810 break;
4811 }
4812 } else {
4813 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004814 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004815 }
Richard Smith55ce3522012-06-25 20:30:08 +00004816 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004817}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004818
Ted Kremenekab278de2010-01-28 23:39:18 +00004819namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004820class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4821protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004822 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004823 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004824 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004825 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004826 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004827 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004828 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004829 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004830 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004831 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004832 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004833 bool usesPositionalArgs;
4834 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004835 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004836 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004837 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004838 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004839
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004840public:
Stephen Hines648c3692016-09-16 01:07:04 +00004841 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004842 const Expr *origFormatExpr,
4843 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004844 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004845 ArrayRef<const Expr *> Args, unsigned formatIdx,
4846 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004847 llvm::SmallBitVector &CheckedVarArgs,
4848 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004849 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4850 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4851 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4852 usesPositionalArgs(false), atFirstArg(true),
4853 inFunctionCall(inFunctionCall), CallType(callType),
4854 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004855 CoveredArgs.resize(numDataArgs);
4856 CoveredArgs.reset();
4857 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004858
Ted Kremenek019d2242010-01-29 01:50:07 +00004859 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004860
Ted Kremenek02087932010-07-16 02:11:22 +00004861 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004862 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004863
Jordan Rose92303592012-09-08 04:00:03 +00004864 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004865 const analyze_format_string::FormatSpecifier &FS,
4866 const analyze_format_string::ConversionSpecifier &CS,
4867 const char *startSpecifier, unsigned specifierLen,
4868 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004869
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004870 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004871 const analyze_format_string::FormatSpecifier &FS,
4872 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004873
4874 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004875 const analyze_format_string::ConversionSpecifier &CS,
4876 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004877
Craig Toppere14c0f82014-03-12 04:55:44 +00004878 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004879
Craig Toppere14c0f82014-03-12 04:55:44 +00004880 void HandleInvalidPosition(const char *startSpecifier,
4881 unsigned specifierLen,
4882 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004883
Craig Toppere14c0f82014-03-12 04:55:44 +00004884 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004885
Craig Toppere14c0f82014-03-12 04:55:44 +00004886 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004887
Richard Trieu03cf7b72011-10-28 00:41:25 +00004888 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004889 static void
4890 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4891 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4892 bool IsStringLocation, Range StringRange,
4893 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004894
Ted Kremenek02087932010-07-16 02:11:22 +00004895protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004896 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4897 const char *startSpec,
4898 unsigned specifierLen,
4899 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004900
4901 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4902 const char *startSpec,
4903 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004904
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004905 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004906 CharSourceRange getSpecifierRange(const char *startSpecifier,
4907 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004908 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004909
Ted Kremenek5739de72010-01-29 01:06:55 +00004910 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004911
4912 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4913 const analyze_format_string::ConversionSpecifier &CS,
4914 const char *startSpecifier, unsigned specifierLen,
4915 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004916
4917 template <typename Range>
4918 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4919 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004920 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004921};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004922} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004923
Ted Kremenek02087932010-07-16 02:11:22 +00004924SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004925 return OrigFormatExpr->getSourceRange();
4926}
4927
Ted Kremenek02087932010-07-16 02:11:22 +00004928CharSourceRange CheckFormatHandler::
4929getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004930 SourceLocation Start = getLocationOfByte(startSpecifier);
4931 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4932
4933 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004934 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004935
4936 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004937}
4938
Ted Kremenek02087932010-07-16 02:11:22 +00004939SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004940 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4941 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004942}
4943
Ted Kremenek02087932010-07-16 02:11:22 +00004944void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4945 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004946 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4947 getLocationOfByte(startSpecifier),
4948 /*IsStringLocation*/true,
4949 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004950}
4951
Jordan Rose92303592012-09-08 04:00:03 +00004952void CheckFormatHandler::HandleInvalidLengthModifier(
4953 const analyze_format_string::FormatSpecifier &FS,
4954 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004955 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004956 using namespace analyze_format_string;
4957
4958 const LengthModifier &LM = FS.getLengthModifier();
4959 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4960
4961 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004962 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004963 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004964 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004965 getLocationOfByte(LM.getStart()),
4966 /*IsStringLocation*/true,
4967 getSpecifierRange(startSpecifier, specifierLen));
4968
4969 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4970 << FixedLM->toString()
4971 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4972
4973 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004974 FixItHint Hint;
4975 if (DiagID == diag::warn_format_nonsensical_length)
4976 Hint = FixItHint::CreateRemoval(LMRange);
4977
4978 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004979 getLocationOfByte(LM.getStart()),
4980 /*IsStringLocation*/true,
4981 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004982 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004983 }
4984}
4985
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004986void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004987 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004988 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004989 using namespace analyze_format_string;
4990
4991 const LengthModifier &LM = FS.getLengthModifier();
4992 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4993
4994 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004995 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004996 if (FixedLM) {
4997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4998 << LM.toString() << 0,
4999 getLocationOfByte(LM.getStart()),
5000 /*IsStringLocation*/true,
5001 getSpecifierRange(startSpecifier, specifierLen));
5002
5003 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5004 << FixedLM->toString()
5005 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5006
5007 } else {
5008 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5009 << LM.toString() << 0,
5010 getLocationOfByte(LM.getStart()),
5011 /*IsStringLocation*/true,
5012 getSpecifierRange(startSpecifier, specifierLen));
5013 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005014}
5015
5016void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5017 const analyze_format_string::ConversionSpecifier &CS,
5018 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005019 using namespace analyze_format_string;
5020
5021 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005022 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005023 if (FixedCS) {
5024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5025 << CS.toString() << /*conversion specifier*/1,
5026 getLocationOfByte(CS.getStart()),
5027 /*IsStringLocation*/true,
5028 getSpecifierRange(startSpecifier, specifierLen));
5029
5030 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5031 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5032 << FixedCS->toString()
5033 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5034 } else {
5035 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5036 << CS.toString() << /*conversion specifier*/1,
5037 getLocationOfByte(CS.getStart()),
5038 /*IsStringLocation*/true,
5039 getSpecifierRange(startSpecifier, specifierLen));
5040 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005041}
5042
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005043void CheckFormatHandler::HandlePosition(const char *startPos,
5044 unsigned posLen) {
5045 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5046 getLocationOfByte(startPos),
5047 /*IsStringLocation*/true,
5048 getSpecifierRange(startPos, posLen));
5049}
5050
Ted Kremenekd1668192010-02-27 01:41:03 +00005051void
Ted Kremenek02087932010-07-16 02:11:22 +00005052CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5053 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005054 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5055 << (unsigned) p,
5056 getLocationOfByte(startPos), /*IsStringLocation*/true,
5057 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005058}
5059
Ted Kremenek02087932010-07-16 02:11:22 +00005060void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005061 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005062 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5063 getLocationOfByte(startPos),
5064 /*IsStringLocation*/true,
5065 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005066}
5067
Ted Kremenek02087932010-07-16 02:11:22 +00005068void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005069 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005070 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005071 EmitFormatDiagnostic(
5072 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5073 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5074 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005075 }
Ted Kremenek02087932010-07-16 02:11:22 +00005076}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005077
Jordan Rose58bbe422012-07-19 18:10:08 +00005078// Note that this may return NULL if there was an error parsing or building
5079// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005080const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005081 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005082}
5083
5084void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005085 // Does the number of data arguments exceed the number of
5086 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005087 if (!HasVAListArg) {
5088 // Find any arguments that weren't covered.
5089 CoveredArgs.flip();
5090 signed notCoveredArg = CoveredArgs.find_first();
5091 if (notCoveredArg >= 0) {
5092 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005093 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5094 } else {
5095 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005096 }
5097 }
5098}
5099
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005100void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5101 const Expr *ArgExpr) {
5102 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5103 "Invalid state");
5104
5105 if (!ArgExpr)
5106 return;
5107
5108 SourceLocation Loc = ArgExpr->getLocStart();
5109
5110 if (S.getSourceManager().isInSystemMacro(Loc))
5111 return;
5112
5113 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5114 for (auto E : DiagnosticExprs)
5115 PDiag << E->getSourceRange();
5116
5117 CheckFormatHandler::EmitFormatDiagnostic(
5118 S, IsFunctionCall, DiagnosticExprs[0],
5119 PDiag, Loc, /*IsStringLocation*/false,
5120 DiagnosticExprs[0]->getSourceRange());
5121}
5122
Ted Kremenekce815422010-07-19 21:25:57 +00005123bool
5124CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5125 SourceLocation Loc,
5126 const char *startSpec,
5127 unsigned specifierLen,
5128 const char *csStart,
5129 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005130 bool keepGoing = true;
5131 if (argIndex < NumDataArgs) {
5132 // Consider the argument coverered, even though the specifier doesn't
5133 // make sense.
5134 CoveredArgs.set(argIndex);
5135 }
5136 else {
5137 // If argIndex exceeds the number of data arguments we
5138 // don't issue a warning because that is just a cascade of warnings (and
5139 // they may have intended '%%' anyway). We don't want to continue processing
5140 // the format string after this point, however, as we will like just get
5141 // gibberish when trying to match arguments.
5142 keepGoing = false;
5143 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005144
5145 StringRef Specifier(csStart, csLen);
5146
5147 // If the specifier in non-printable, it could be the first byte of a UTF-8
5148 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5149 // hex value.
5150 std::string CodePointStr;
5151 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005152 llvm::UTF32 CodePoint;
5153 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5154 const llvm::UTF8 *E =
5155 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5156 llvm::ConversionResult Result =
5157 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005158
Justin Lebar90910552016-09-30 00:38:45 +00005159 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005160 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005161 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005162 }
5163
5164 llvm::raw_string_ostream OS(CodePointStr);
5165 if (CodePoint < 256)
5166 OS << "\\x" << llvm::format("%02x", CodePoint);
5167 else if (CodePoint <= 0xFFFF)
5168 OS << "\\u" << llvm::format("%04x", CodePoint);
5169 else
5170 OS << "\\U" << llvm::format("%08x", CodePoint);
5171 OS.flush();
5172 Specifier = CodePointStr;
5173 }
5174
5175 EmitFormatDiagnostic(
5176 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5177 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5178
Ted Kremenekce815422010-07-19 21:25:57 +00005179 return keepGoing;
5180}
5181
Richard Trieu03cf7b72011-10-28 00:41:25 +00005182void
5183CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5184 const char *startSpec,
5185 unsigned specifierLen) {
5186 EmitFormatDiagnostic(
5187 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5188 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5189}
5190
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005191bool
5192CheckFormatHandler::CheckNumArgs(
5193 const analyze_format_string::FormatSpecifier &FS,
5194 const analyze_format_string::ConversionSpecifier &CS,
5195 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5196
5197 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005198 PartialDiagnostic PDiag = FS.usesPositionalArg()
5199 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5200 << (argIndex+1) << NumDataArgs)
5201 : S.PDiag(diag::warn_printf_insufficient_data_args);
5202 EmitFormatDiagnostic(
5203 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5204 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005205
5206 // Since more arguments than conversion tokens are given, by extension
5207 // all arguments are covered, so mark this as so.
5208 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005209 return false;
5210 }
5211 return true;
5212}
5213
Richard Trieu03cf7b72011-10-28 00:41:25 +00005214template<typename Range>
5215void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5216 SourceLocation Loc,
5217 bool IsStringLocation,
5218 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005219 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005220 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005221 Loc, IsStringLocation, StringRange, FixIt);
5222}
5223
5224/// \brief If the format string is not within the funcion call, emit a note
5225/// so that the function call and string are in diagnostic messages.
5226///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005227/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005228/// call and only one diagnostic message will be produced. Otherwise, an
5229/// extra note will be emitted pointing to location of the format string.
5230///
5231/// \param ArgumentExpr the expression that is passed as the format string
5232/// argument in the function call. Used for getting locations when two
5233/// diagnostics are emitted.
5234///
5235/// \param PDiag the callee should already have provided any strings for the
5236/// diagnostic message. This function only adds locations and fixits
5237/// to diagnostics.
5238///
5239/// \param Loc primary location for diagnostic. If two diagnostics are
5240/// required, one will be at Loc and a new SourceLocation will be created for
5241/// the other one.
5242///
5243/// \param IsStringLocation if true, Loc points to the format string should be
5244/// used for the note. Otherwise, Loc points to the argument list and will
5245/// be used with PDiag.
5246///
5247/// \param StringRange some or all of the string to highlight. This is
5248/// templated so it can accept either a CharSourceRange or a SourceRange.
5249///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005250/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005251template <typename Range>
5252void CheckFormatHandler::EmitFormatDiagnostic(
5253 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5254 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5255 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005256 if (InFunctionCall) {
5257 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5258 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005259 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005260 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005261 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5262 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005263
5264 const Sema::SemaDiagnosticBuilder &Note =
5265 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5266 diag::note_format_string_defined);
5267
5268 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005269 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005270 }
5271}
5272
Ted Kremenek02087932010-07-16 02:11:22 +00005273//===--- CHECK: Printf format string checking ------------------------------===//
5274
5275namespace {
5276class CheckPrintfHandler : public CheckFormatHandler {
5277public:
Stephen Hines648c3692016-09-16 01:07:04 +00005278 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005279 const Expr *origFormatExpr,
5280 const Sema::FormatStringType type, unsigned firstDataArg,
5281 unsigned numDataArgs, bool isObjC, const char *beg,
5282 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005283 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005284 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005285 llvm::SmallBitVector &CheckedVarArgs,
5286 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005287 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5288 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5289 inFunctionCall, CallType, CheckedVarArgs,
5290 UncoveredArg) {}
5291
5292 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5293
5294 /// Returns true if '%@' specifiers are allowed in the format string.
5295 bool allowsObjCArg() const {
5296 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5297 FSType == Sema::FST_OSTrace;
5298 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005299
Ted Kremenek02087932010-07-16 02:11:22 +00005300 bool HandleInvalidPrintfConversionSpecifier(
5301 const analyze_printf::PrintfSpecifier &FS,
5302 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005303 unsigned specifierLen) override;
5304
Ted Kremenek02087932010-07-16 02:11:22 +00005305 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5306 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005307 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005308 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5309 const char *StartSpecifier,
5310 unsigned SpecifierLen,
5311 const Expr *E);
5312
Ted Kremenek02087932010-07-16 02:11:22 +00005313 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5314 const char *startSpecifier, unsigned specifierLen);
5315 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5316 const analyze_printf::OptionalAmount &Amt,
5317 unsigned type,
5318 const char *startSpecifier, unsigned specifierLen);
5319 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5320 const analyze_printf::OptionalFlag &flag,
5321 const char *startSpecifier, unsigned specifierLen);
5322 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5323 const analyze_printf::OptionalFlag &ignoredFlag,
5324 const analyze_printf::OptionalFlag &flag,
5325 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005326 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005327 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005328
5329 void HandleEmptyObjCModifierFlag(const char *startFlag,
5330 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005331
Ted Kremenek2b417712015-07-02 05:39:16 +00005332 void HandleInvalidObjCModifierFlag(const char *startFlag,
5333 unsigned flagLen) override;
5334
5335 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5336 const char *flagsEnd,
5337 const char *conversionPosition)
5338 override;
5339};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005340} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005341
5342bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5343 const analyze_printf::PrintfSpecifier &FS,
5344 const char *startSpecifier,
5345 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005346 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005347 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005348
Ted Kremenekce815422010-07-19 21:25:57 +00005349 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5350 getLocationOfByte(CS.getStart()),
5351 startSpecifier, specifierLen,
5352 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005353}
5354
Ted Kremenek02087932010-07-16 02:11:22 +00005355bool CheckPrintfHandler::HandleAmount(
5356 const analyze_format_string::OptionalAmount &Amt,
5357 unsigned k, const char *startSpecifier,
5358 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005359 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005360 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005361 unsigned argIndex = Amt.getArgIndex();
5362 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005363 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5364 << k,
5365 getLocationOfByte(Amt.getStart()),
5366 /*IsStringLocation*/true,
5367 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005368 // Don't do any more checking. We will just emit
5369 // spurious errors.
5370 return false;
5371 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005372
Ted Kremenek5739de72010-01-29 01:06:55 +00005373 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005374 // Although not in conformance with C99, we also allow the argument to be
5375 // an 'unsigned int' as that is a reasonably safe case. GCC also
5376 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005377 CoveredArgs.set(argIndex);
5378 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005379 if (!Arg)
5380 return false;
5381
Ted Kremenek5739de72010-01-29 01:06:55 +00005382 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005383
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005384 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5385 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005386
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005387 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005388 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005389 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005390 << T << Arg->getSourceRange(),
5391 getLocationOfByte(Amt.getStart()),
5392 /*IsStringLocation*/true,
5393 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005394 // Don't do any more checking. We will just emit
5395 // spurious errors.
5396 return false;
5397 }
5398 }
5399 }
5400 return true;
5401}
Ted Kremenek5739de72010-01-29 01:06:55 +00005402
Tom Careb49ec692010-06-17 19:00:27 +00005403void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005404 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005405 const analyze_printf::OptionalAmount &Amt,
5406 unsigned type,
5407 const char *startSpecifier,
5408 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005409 const analyze_printf::PrintfConversionSpecifier &CS =
5410 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005411
Richard Trieu03cf7b72011-10-28 00:41:25 +00005412 FixItHint fixit =
5413 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5414 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5415 Amt.getConstantLength()))
5416 : FixItHint();
5417
5418 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5419 << type << CS.toString(),
5420 getLocationOfByte(Amt.getStart()),
5421 /*IsStringLocation*/true,
5422 getSpecifierRange(startSpecifier, specifierLen),
5423 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005424}
5425
Ted Kremenek02087932010-07-16 02:11:22 +00005426void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005427 const analyze_printf::OptionalFlag &flag,
5428 const char *startSpecifier,
5429 unsigned specifierLen) {
5430 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005431 const analyze_printf::PrintfConversionSpecifier &CS =
5432 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005433 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5434 << flag.toString() << CS.toString(),
5435 getLocationOfByte(flag.getPosition()),
5436 /*IsStringLocation*/true,
5437 getSpecifierRange(startSpecifier, specifierLen),
5438 FixItHint::CreateRemoval(
5439 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005440}
5441
5442void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005443 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005444 const analyze_printf::OptionalFlag &ignoredFlag,
5445 const analyze_printf::OptionalFlag &flag,
5446 const char *startSpecifier,
5447 unsigned specifierLen) {
5448 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5450 << ignoredFlag.toString() << flag.toString(),
5451 getLocationOfByte(ignoredFlag.getPosition()),
5452 /*IsStringLocation*/true,
5453 getSpecifierRange(startSpecifier, specifierLen),
5454 FixItHint::CreateRemoval(
5455 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005456}
5457
Ted Kremenek2b417712015-07-02 05:39:16 +00005458// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5459// bool IsStringLocation, Range StringRange,
5460// ArrayRef<FixItHint> Fixit = None);
5461
5462void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5463 unsigned flagLen) {
5464 // Warn about an empty flag.
5465 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5466 getLocationOfByte(startFlag),
5467 /*IsStringLocation*/true,
5468 getSpecifierRange(startFlag, flagLen));
5469}
5470
5471void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5472 unsigned flagLen) {
5473 // Warn about an invalid flag.
5474 auto Range = getSpecifierRange(startFlag, flagLen);
5475 StringRef flag(startFlag, flagLen);
5476 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5477 getLocationOfByte(startFlag),
5478 /*IsStringLocation*/true,
5479 Range, FixItHint::CreateRemoval(Range));
5480}
5481
5482void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5483 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5484 // Warn about using '[...]' without a '@' conversion.
5485 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5486 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5487 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5488 getLocationOfByte(conversionPosition),
5489 /*IsStringLocation*/true,
5490 Range, FixItHint::CreateRemoval(Range));
5491}
5492
Richard Smith55ce3522012-06-25 20:30:08 +00005493// Determines if the specified is a C++ class or struct containing
5494// a member with the specified name and kind (e.g. a CXXMethodDecl named
5495// "c_str()").
5496template<typename MemberKind>
5497static llvm::SmallPtrSet<MemberKind*, 1>
5498CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5499 const RecordType *RT = Ty->getAs<RecordType>();
5500 llvm::SmallPtrSet<MemberKind*, 1> Results;
5501
5502 if (!RT)
5503 return Results;
5504 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005505 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005506 return Results;
5507
Alp Tokerb6cc5922014-05-03 03:45:55 +00005508 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005509 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005510 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005511
5512 // We just need to include all members of the right kind turned up by the
5513 // filter, at this point.
5514 if (S.LookupQualifiedName(R, RT->getDecl()))
5515 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5516 NamedDecl *decl = (*I)->getUnderlyingDecl();
5517 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5518 Results.insert(FK);
5519 }
5520 return Results;
5521}
5522
Richard Smith2868a732014-02-28 01:36:39 +00005523/// Check if we could call '.c_str()' on an object.
5524///
5525/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5526/// allow the call, or if it would be ambiguous).
5527bool Sema::hasCStrMethod(const Expr *E) {
5528 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5529 MethodSet Results =
5530 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5531 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5532 MI != ME; ++MI)
5533 if ((*MI)->getMinRequiredArguments() == 0)
5534 return true;
5535 return false;
5536}
5537
Richard Smith55ce3522012-06-25 20:30:08 +00005538// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005539// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005540// Returns true when a c_str() conversion method is found.
5541bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005542 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005543 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5544
5545 MethodSet Results =
5546 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5547
5548 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5549 MI != ME; ++MI) {
5550 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005551 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005552 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005553 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005554 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005555 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5556 << "c_str()"
5557 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5558 return true;
5559 }
5560 }
5561
5562 return false;
5563}
5564
Ted Kremenekab278de2010-01-28 23:39:18 +00005565bool
Ted Kremenek02087932010-07-16 02:11:22 +00005566CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005567 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005568 const char *startSpecifier,
5569 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005570 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005571 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005572 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005573
Ted Kremenek6cd69422010-07-19 22:01:06 +00005574 if (FS.consumesDataArgument()) {
5575 if (atFirstArg) {
5576 atFirstArg = false;
5577 usesPositionalArgs = FS.usesPositionalArg();
5578 }
5579 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005580 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5581 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005582 return false;
5583 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005584 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005585
Ted Kremenekd1668192010-02-27 01:41:03 +00005586 // First check if the field width, precision, and conversion specifier
5587 // have matching data arguments.
5588 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5589 startSpecifier, specifierLen)) {
5590 return false;
5591 }
5592
5593 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5594 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005595 return false;
5596 }
5597
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005598 if (!CS.consumesDataArgument()) {
5599 // FIXME: Technically specifying a precision or field width here
5600 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005601 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005602 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005603
Ted Kremenek4a49d982010-02-26 19:18:41 +00005604 // Consume the argument.
5605 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005606 if (argIndex < NumDataArgs) {
5607 // The check to see if the argIndex is valid will come later.
5608 // We set the bit here because we may exit early from this
5609 // function if we encounter some other error.
5610 CoveredArgs.set(argIndex);
5611 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005612
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005613 // FreeBSD kernel extensions.
5614 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5615 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5616 // We need at least two arguments.
5617 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5618 return false;
5619
5620 // Claim the second argument.
5621 CoveredArgs.set(argIndex + 1);
5622
5623 // Type check the first argument (int for %b, pointer for %D)
5624 const Expr *Ex = getDataArg(argIndex);
5625 const analyze_printf::ArgType &AT =
5626 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5627 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5628 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5629 EmitFormatDiagnostic(
5630 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5631 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5632 << false << Ex->getSourceRange(),
5633 Ex->getLocStart(), /*IsStringLocation*/false,
5634 getSpecifierRange(startSpecifier, specifierLen));
5635
5636 // Type check the second argument (char * for both %b and %D)
5637 Ex = getDataArg(argIndex + 1);
5638 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5639 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5640 EmitFormatDiagnostic(
5641 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5642 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5643 << false << Ex->getSourceRange(),
5644 Ex->getLocStart(), /*IsStringLocation*/false,
5645 getSpecifierRange(startSpecifier, specifierLen));
5646
5647 return true;
5648 }
5649
Ted Kremenek4a49d982010-02-26 19:18:41 +00005650 // Check for using an Objective-C specific conversion specifier
5651 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005652 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005653 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5654 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005655 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005656
Mehdi Amini06d367c2016-10-24 20:39:34 +00005657 // %P can only be used with os_log.
5658 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5659 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5660 specifierLen);
5661 }
5662
5663 // %n is not allowed with os_log.
5664 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5665 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5666 getLocationOfByte(CS.getStart()),
5667 /*IsStringLocation*/ false,
5668 getSpecifierRange(startSpecifier, specifierLen));
5669
5670 return true;
5671 }
5672
5673 // Only scalars are allowed for os_trace.
5674 if (FSType == Sema::FST_OSTrace &&
5675 (CS.getKind() == ConversionSpecifier::PArg ||
5676 CS.getKind() == ConversionSpecifier::sArg ||
5677 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5678 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5679 specifierLen);
5680 }
5681
5682 // Check for use of public/private annotation outside of os_log().
5683 if (FSType != Sema::FST_OSLog) {
5684 if (FS.isPublic().isSet()) {
5685 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5686 << "public",
5687 getLocationOfByte(FS.isPublic().getPosition()),
5688 /*IsStringLocation*/ false,
5689 getSpecifierRange(startSpecifier, specifierLen));
5690 }
5691 if (FS.isPrivate().isSet()) {
5692 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5693 << "private",
5694 getLocationOfByte(FS.isPrivate().getPosition()),
5695 /*IsStringLocation*/ false,
5696 getSpecifierRange(startSpecifier, specifierLen));
5697 }
5698 }
5699
Tom Careb49ec692010-06-17 19:00:27 +00005700 // Check for invalid use of field width
5701 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005702 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005703 startSpecifier, specifierLen);
5704 }
5705
5706 // Check for invalid use of precision
5707 if (!FS.hasValidPrecision()) {
5708 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5709 startSpecifier, specifierLen);
5710 }
5711
Mehdi Amini06d367c2016-10-24 20:39:34 +00005712 // Precision is mandatory for %P specifier.
5713 if (CS.getKind() == ConversionSpecifier::PArg &&
5714 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5715 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5716 getLocationOfByte(startSpecifier),
5717 /*IsStringLocation*/ false,
5718 getSpecifierRange(startSpecifier, specifierLen));
5719 }
5720
Tom Careb49ec692010-06-17 19:00:27 +00005721 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005722 if (!FS.hasValidThousandsGroupingPrefix())
5723 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005724 if (!FS.hasValidLeadingZeros())
5725 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5726 if (!FS.hasValidPlusPrefix())
5727 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005728 if (!FS.hasValidSpacePrefix())
5729 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005730 if (!FS.hasValidAlternativeForm())
5731 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5732 if (!FS.hasValidLeftJustified())
5733 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5734
5735 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005736 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5737 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5738 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005739 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5740 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5741 startSpecifier, specifierLen);
5742
5743 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005744 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005745 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5746 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005747 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005748 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005749 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005750 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5751 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005752
Jordan Rose92303592012-09-08 04:00:03 +00005753 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5754 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5755
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005756 // The remaining checks depend on the data arguments.
5757 if (HasVAListArg)
5758 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005759
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005760 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005761 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005762
Jordan Rose58bbe422012-07-19 18:10:08 +00005763 const Expr *Arg = getDataArg(argIndex);
5764 if (!Arg)
5765 return true;
5766
5767 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005768}
5769
Jordan Roseaee34382012-09-05 22:56:26 +00005770static bool requiresParensToAddCast(const Expr *E) {
5771 // FIXME: We should have a general way to reason about operator
5772 // precedence and whether parens are actually needed here.
5773 // Take care of a few common cases where they aren't.
5774 const Expr *Inside = E->IgnoreImpCasts();
5775 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5776 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5777
5778 switch (Inside->getStmtClass()) {
5779 case Stmt::ArraySubscriptExprClass:
5780 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005781 case Stmt::CharacterLiteralClass:
5782 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005783 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005784 case Stmt::FloatingLiteralClass:
5785 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005786 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005787 case Stmt::ObjCArrayLiteralClass:
5788 case Stmt::ObjCBoolLiteralExprClass:
5789 case Stmt::ObjCBoxedExprClass:
5790 case Stmt::ObjCDictionaryLiteralClass:
5791 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005792 case Stmt::ObjCIvarRefExprClass:
5793 case Stmt::ObjCMessageExprClass:
5794 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005795 case Stmt::ObjCStringLiteralClass:
5796 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005797 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005798 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005799 case Stmt::UnaryOperatorClass:
5800 return false;
5801 default:
5802 return true;
5803 }
5804}
5805
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005806static std::pair<QualType, StringRef>
5807shouldNotPrintDirectly(const ASTContext &Context,
5808 QualType IntendedTy,
5809 const Expr *E) {
5810 // Use a 'while' to peel off layers of typedefs.
5811 QualType TyTy = IntendedTy;
5812 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5813 StringRef Name = UserTy->getDecl()->getName();
5814 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5815 .Case("NSInteger", Context.LongTy)
5816 .Case("NSUInteger", Context.UnsignedLongTy)
5817 .Case("SInt32", Context.IntTy)
5818 .Case("UInt32", Context.UnsignedIntTy)
5819 .Default(QualType());
5820
5821 if (!CastTy.isNull())
5822 return std::make_pair(CastTy, Name);
5823
5824 TyTy = UserTy->desugar();
5825 }
5826
5827 // Strip parens if necessary.
5828 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5829 return shouldNotPrintDirectly(Context,
5830 PE->getSubExpr()->getType(),
5831 PE->getSubExpr());
5832
5833 // If this is a conditional expression, then its result type is constructed
5834 // via usual arithmetic conversions and thus there might be no necessary
5835 // typedef sugar there. Recurse to operands to check for NSInteger &
5836 // Co. usage condition.
5837 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5838 QualType TrueTy, FalseTy;
5839 StringRef TrueName, FalseName;
5840
5841 std::tie(TrueTy, TrueName) =
5842 shouldNotPrintDirectly(Context,
5843 CO->getTrueExpr()->getType(),
5844 CO->getTrueExpr());
5845 std::tie(FalseTy, FalseName) =
5846 shouldNotPrintDirectly(Context,
5847 CO->getFalseExpr()->getType(),
5848 CO->getFalseExpr());
5849
5850 if (TrueTy == FalseTy)
5851 return std::make_pair(TrueTy, TrueName);
5852 else if (TrueTy.isNull())
5853 return std::make_pair(FalseTy, FalseName);
5854 else if (FalseTy.isNull())
5855 return std::make_pair(TrueTy, TrueName);
5856 }
5857
5858 return std::make_pair(QualType(), StringRef());
5859}
5860
Richard Smith55ce3522012-06-25 20:30:08 +00005861bool
5862CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5863 const char *StartSpecifier,
5864 unsigned SpecifierLen,
5865 const Expr *E) {
5866 using namespace analyze_format_string;
5867 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005868 // Now type check the data expression that matches the
5869 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005870 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005871 if (!AT.isValid())
5872 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005873
Jordan Rose598ec092012-12-05 18:44:40 +00005874 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005875 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5876 ExprTy = TET->getUnderlyingExpr()->getType();
5877 }
5878
Seth Cantrellb4802962015-03-04 03:12:10 +00005879 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5880
5881 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005882 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005883 }
Jordan Rose98709982012-06-04 22:48:57 +00005884
Jordan Rose22b74712012-09-05 22:56:19 +00005885 // Look through argument promotions for our error message's reported type.
5886 // This includes the integral and floating promotions, but excludes array
5887 // and function pointer decay; seeing that an argument intended to be a
5888 // string has type 'char [6]' is probably more confusing than 'char *'.
5889 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5890 if (ICE->getCastKind() == CK_IntegralCast ||
5891 ICE->getCastKind() == CK_FloatingCast) {
5892 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005893 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005894
5895 // Check if we didn't match because of an implicit cast from a 'char'
5896 // or 'short' to an 'int'. This is done because printf is a varargs
5897 // function.
5898 if (ICE->getType() == S.Context.IntTy ||
5899 ICE->getType() == S.Context.UnsignedIntTy) {
5900 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005901 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005902 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005903 }
Jordan Rose98709982012-06-04 22:48:57 +00005904 }
Jordan Rose598ec092012-12-05 18:44:40 +00005905 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5906 // Special case for 'a', which has type 'int' in C.
5907 // Note, however, that we do /not/ want to treat multibyte constants like
5908 // 'MooV' as characters! This form is deprecated but still exists.
5909 if (ExprTy == S.Context.IntTy)
5910 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5911 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005912 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005913
Jordan Rosebc53ed12014-05-31 04:12:14 +00005914 // Look through enums to their underlying type.
5915 bool IsEnum = false;
5916 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5917 ExprTy = EnumTy->getDecl()->getIntegerType();
5918 IsEnum = true;
5919 }
5920
Jordan Rose0e5badd2012-12-05 18:44:49 +00005921 // %C in an Objective-C context prints a unichar, not a wchar_t.
5922 // If the argument is an integer of some kind, believe the %C and suggest
5923 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005924 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005925 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005926 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5927 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5928 !ExprTy->isCharType()) {
5929 // 'unichar' is defined as a typedef of unsigned short, but we should
5930 // prefer using the typedef if it is visible.
5931 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005932
5933 // While we are here, check if the value is an IntegerLiteral that happens
5934 // to be within the valid range.
5935 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5936 const llvm::APInt &V = IL->getValue();
5937 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5938 return true;
5939 }
5940
Jordan Rose0e5badd2012-12-05 18:44:49 +00005941 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5942 Sema::LookupOrdinaryName);
5943 if (S.LookupName(Result, S.getCurScope())) {
5944 NamedDecl *ND = Result.getFoundDecl();
5945 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5946 if (TD->getUnderlyingType() == IntendedTy)
5947 IntendedTy = S.Context.getTypedefType(TD);
5948 }
5949 }
5950 }
5951
5952 // Special-case some of Darwin's platform-independence types by suggesting
5953 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005954 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005955 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005956 QualType CastTy;
5957 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5958 if (!CastTy.isNull()) {
5959 IntendedTy = CastTy;
5960 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005961 }
5962 }
5963
Jordan Rose22b74712012-09-05 22:56:19 +00005964 // We may be able to offer a FixItHint if it is a supported type.
5965 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005966 bool success =
5967 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005968
Jordan Rose22b74712012-09-05 22:56:19 +00005969 if (success) {
5970 // Get the fix string from the fixed format specifier
5971 SmallString<16> buf;
5972 llvm::raw_svector_ostream os(buf);
5973 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005974
Jordan Roseaee34382012-09-05 22:56:26 +00005975 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5976
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005977 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005978 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5979 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5980 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5981 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005982 // In this case, the specifier is wrong and should be changed to match
5983 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005984 EmitFormatDiagnostic(S.PDiag(diag)
5985 << AT.getRepresentativeTypeName(S.Context)
5986 << IntendedTy << IsEnum << E->getSourceRange(),
5987 E->getLocStart(),
5988 /*IsStringLocation*/ false, SpecRange,
5989 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005990 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005991 // The canonical type for formatting this value is different from the
5992 // actual type of the expression. (This occurs, for example, with Darwin's
5993 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5994 // should be printed as 'long' for 64-bit compatibility.)
5995 // Rather than emitting a normal format/argument mismatch, we want to
5996 // add a cast to the recommended type (and correct the format string
5997 // if necessary).
5998 SmallString<16> CastBuf;
5999 llvm::raw_svector_ostream CastFix(CastBuf);
6000 CastFix << "(";
6001 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6002 CastFix << ")";
6003
6004 SmallVector<FixItHint,4> Hints;
6005 if (!AT.matchesType(S.Context, IntendedTy))
6006 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6007
6008 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6009 // If there's already a cast present, just replace it.
6010 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6011 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6012
6013 } else if (!requiresParensToAddCast(E)) {
6014 // If the expression has high enough precedence,
6015 // just write the C-style cast.
6016 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6017 CastFix.str()));
6018 } else {
6019 // Otherwise, add parens around the expression as well as the cast.
6020 CastFix << "(";
6021 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6022 CastFix.str()));
6023
Alp Tokerb6cc5922014-05-03 03:45:55 +00006024 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006025 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6026 }
6027
Jordan Rose0e5badd2012-12-05 18:44:49 +00006028 if (ShouldNotPrintDirectly) {
6029 // The expression has a type that should not be printed directly.
6030 // We extract the name from the typedef because we don't want to show
6031 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006032 StringRef Name;
6033 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6034 Name = TypedefTy->getDecl()->getName();
6035 else
6036 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006037 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006038 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006039 << E->getSourceRange(),
6040 E->getLocStart(), /*IsStringLocation=*/false,
6041 SpecRange, Hints);
6042 } else {
6043 // In this case, the expression could be printed using a different
6044 // specifier, but we've decided that the specifier is probably correct
6045 // and we should cast instead. Just use the normal warning message.
6046 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006047 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6048 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006049 << E->getSourceRange(),
6050 E->getLocStart(), /*IsStringLocation*/false,
6051 SpecRange, Hints);
6052 }
Jordan Roseaee34382012-09-05 22:56:26 +00006053 }
Jordan Rose22b74712012-09-05 22:56:19 +00006054 } else {
6055 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6056 SpecifierLen);
6057 // Since the warning for passing non-POD types to variadic functions
6058 // was deferred until now, we emit a warning for non-POD
6059 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006060 switch (S.isValidVarArgType(ExprTy)) {
6061 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006062 case Sema::VAK_ValidInCXX11: {
6063 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6064 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6065 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6066 }
Richard Smithd7293d72013-08-05 18:49:43 +00006067
Seth Cantrellb4802962015-03-04 03:12:10 +00006068 EmitFormatDiagnostic(
6069 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6070 << IsEnum << CSR << E->getSourceRange(),
6071 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6072 break;
6073 }
Richard Smithd7293d72013-08-05 18:49:43 +00006074 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006075 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006076 EmitFormatDiagnostic(
6077 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006078 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006079 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006080 << CallType
6081 << AT.getRepresentativeTypeName(S.Context)
6082 << CSR
6083 << E->getSourceRange(),
6084 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006085 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006086 break;
6087
6088 case Sema::VAK_Invalid:
6089 if (ExprTy->isObjCObjectType())
6090 EmitFormatDiagnostic(
6091 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6092 << S.getLangOpts().CPlusPlus11
6093 << ExprTy
6094 << CallType
6095 << AT.getRepresentativeTypeName(S.Context)
6096 << CSR
6097 << E->getSourceRange(),
6098 E->getLocStart(), /*IsStringLocation*/false, CSR);
6099 else
6100 // FIXME: If this is an initializer list, suggest removing the braces
6101 // or inserting a cast to the target type.
6102 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6103 << isa<InitListExpr>(E) << ExprTy << CallType
6104 << AT.getRepresentativeTypeName(S.Context)
6105 << E->getSourceRange();
6106 break;
6107 }
6108
6109 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6110 "format string specifier index out of range");
6111 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006112 }
6113
Ted Kremenekab278de2010-01-28 23:39:18 +00006114 return true;
6115}
6116
Ted Kremenek02087932010-07-16 02:11:22 +00006117//===--- CHECK: Scanf format string checking ------------------------------===//
6118
6119namespace {
6120class CheckScanfHandler : public CheckFormatHandler {
6121public:
Stephen Hines648c3692016-09-16 01:07:04 +00006122 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006123 const Expr *origFormatExpr, Sema::FormatStringType type,
6124 unsigned firstDataArg, unsigned numDataArgs,
6125 const char *beg, bool hasVAListArg,
6126 ArrayRef<const Expr *> Args, unsigned formatIdx,
6127 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006128 llvm::SmallBitVector &CheckedVarArgs,
6129 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006130 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6131 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6132 inFunctionCall, CallType, CheckedVarArgs,
6133 UncoveredArg) {}
6134
Ted Kremenek02087932010-07-16 02:11:22 +00006135 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6136 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006137 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006138
6139 bool HandleInvalidScanfConversionSpecifier(
6140 const analyze_scanf::ScanfSpecifier &FS,
6141 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006142 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006143
Craig Toppere14c0f82014-03-12 04:55:44 +00006144 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006145};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006146} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006147
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006148void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6149 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006150 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6151 getLocationOfByte(end), /*IsStringLocation*/true,
6152 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006153}
6154
Ted Kremenekce815422010-07-19 21:25:57 +00006155bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6156 const analyze_scanf::ScanfSpecifier &FS,
6157 const char *startSpecifier,
6158 unsigned specifierLen) {
6159
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006160 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006161 FS.getConversionSpecifier();
6162
6163 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6164 getLocationOfByte(CS.getStart()),
6165 startSpecifier, specifierLen,
6166 CS.getStart(), CS.getLength());
6167}
6168
Ted Kremenek02087932010-07-16 02:11:22 +00006169bool CheckScanfHandler::HandleScanfSpecifier(
6170 const analyze_scanf::ScanfSpecifier &FS,
6171 const char *startSpecifier,
6172 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006173 using namespace analyze_scanf;
6174 using namespace analyze_format_string;
6175
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006176 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006177
Ted Kremenek6cd69422010-07-19 22:01:06 +00006178 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6179 // be used to decide if we are using positional arguments consistently.
6180 if (FS.consumesDataArgument()) {
6181 if (atFirstArg) {
6182 atFirstArg = false;
6183 usesPositionalArgs = FS.usesPositionalArg();
6184 }
6185 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006186 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6187 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006188 return false;
6189 }
Ted Kremenek02087932010-07-16 02:11:22 +00006190 }
6191
6192 // Check if the field with is non-zero.
6193 const OptionalAmount &Amt = FS.getFieldWidth();
6194 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6195 if (Amt.getConstantAmount() == 0) {
6196 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6197 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006198 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6199 getLocationOfByte(Amt.getStart()),
6200 /*IsStringLocation*/true, R,
6201 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006202 }
6203 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006204
Ted Kremenek02087932010-07-16 02:11:22 +00006205 if (!FS.consumesDataArgument()) {
6206 // FIXME: Technically specifying a precision or field width here
6207 // makes no sense. Worth issuing a warning at some point.
6208 return true;
6209 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006210
Ted Kremenek02087932010-07-16 02:11:22 +00006211 // Consume the argument.
6212 unsigned argIndex = FS.getArgIndex();
6213 if (argIndex < NumDataArgs) {
6214 // The check to see if the argIndex is valid will come later.
6215 // We set the bit here because we may exit early from this
6216 // function if we encounter some other error.
6217 CoveredArgs.set(argIndex);
6218 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006219
Ted Kremenek4407ea42010-07-20 20:04:47 +00006220 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006221 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006222 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6223 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006224 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006225 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006226 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006227 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6228 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006229
Jordan Rose92303592012-09-08 04:00:03 +00006230 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6231 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6232
Ted Kremenek02087932010-07-16 02:11:22 +00006233 // The remaining checks depend on the data arguments.
6234 if (HasVAListArg)
6235 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006236
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006237 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006238 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006239
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006240 // Check that the argument type matches the format specifier.
6241 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006242 if (!Ex)
6243 return true;
6244
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006245 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006246
6247 if (!AT.isValid()) {
6248 return true;
6249 }
6250
Seth Cantrellb4802962015-03-04 03:12:10 +00006251 analyze_format_string::ArgType::MatchKind match =
6252 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006253 if (match == analyze_format_string::ArgType::Match) {
6254 return true;
6255 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006256
Seth Cantrell79340072015-03-04 05:58:08 +00006257 ScanfSpecifier fixedFS = FS;
6258 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6259 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006260
Seth Cantrell79340072015-03-04 05:58:08 +00006261 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6262 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6263 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6264 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006265
Seth Cantrell79340072015-03-04 05:58:08 +00006266 if (success) {
6267 // Get the fix string from the fixed format specifier.
6268 SmallString<128> buf;
6269 llvm::raw_svector_ostream os(buf);
6270 fixedFS.toString(os);
6271
6272 EmitFormatDiagnostic(
6273 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6274 << Ex->getType() << false << Ex->getSourceRange(),
6275 Ex->getLocStart(),
6276 /*IsStringLocation*/ false,
6277 getSpecifierRange(startSpecifier, specifierLen),
6278 FixItHint::CreateReplacement(
6279 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6280 } else {
6281 EmitFormatDiagnostic(S.PDiag(diag)
6282 << AT.getRepresentativeTypeName(S.Context)
6283 << Ex->getType() << false << Ex->getSourceRange(),
6284 Ex->getLocStart(),
6285 /*IsStringLocation*/ false,
6286 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006287 }
6288
Ted Kremenek02087932010-07-16 02:11:22 +00006289 return true;
6290}
6291
Stephen Hines648c3692016-09-16 01:07:04 +00006292static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006293 const Expr *OrigFormatExpr,
6294 ArrayRef<const Expr *> Args,
6295 bool HasVAListArg, unsigned format_idx,
6296 unsigned firstDataArg,
6297 Sema::FormatStringType Type,
6298 bool inFunctionCall,
6299 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006300 llvm::SmallBitVector &CheckedVarArgs,
6301 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006302 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006303 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006304 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006305 S, inFunctionCall, Args[format_idx],
6306 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006307 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006308 return;
6309 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006310
Ted Kremenekab278de2010-01-28 23:39:18 +00006311 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006312 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006313 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006314 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006315 const ConstantArrayType *T =
6316 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006317 assert(T && "String literal not of constant array type!");
6318 size_t TypeSize = T->getSize().getZExtValue();
6319 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006320 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006321
6322 // Emit a warning if the string literal is truncated and does not contain an
6323 // embedded null character.
6324 if (TypeSize <= StrRef.size() &&
6325 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6326 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006327 S, inFunctionCall, Args[format_idx],
6328 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006329 FExpr->getLocStart(),
6330 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6331 return;
6332 }
6333
Ted Kremenekab278de2010-01-28 23:39:18 +00006334 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006335 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006336 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006337 S, inFunctionCall, Args[format_idx],
6338 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006339 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006340 return;
6341 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006342
6343 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006344 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6345 Type == Sema::FST_OSTrace) {
6346 CheckPrintfHandler H(
6347 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6348 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6349 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6350 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006351
Hans Wennborg23926bd2011-12-15 10:25:47 +00006352 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006353 S.getLangOpts(),
6354 S.Context.getTargetInfo(),
6355 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006356 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006357 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006358 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6359 numDataArgs, Str, HasVAListArg, Args, format_idx,
6360 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006361
Hans Wennborg23926bd2011-12-15 10:25:47 +00006362 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006363 S.getLangOpts(),
6364 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006365 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006366 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006367}
6368
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006369bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6370 // Str - The format string. NOTE: this is NOT null-terminated!
6371 StringRef StrRef = FExpr->getString();
6372 const char *Str = StrRef.data();
6373 // Account for cases where the string literal is truncated in a declaration.
6374 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6375 assert(T && "String literal not of constant array type!");
6376 size_t TypeSize = T->getSize().getZExtValue();
6377 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6378 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6379 getLangOpts(),
6380 Context.getTargetInfo());
6381}
6382
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006383//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6384
6385// Returns the related absolute value function that is larger, of 0 if one
6386// does not exist.
6387static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6388 switch (AbsFunction) {
6389 default:
6390 return 0;
6391
6392 case Builtin::BI__builtin_abs:
6393 return Builtin::BI__builtin_labs;
6394 case Builtin::BI__builtin_labs:
6395 return Builtin::BI__builtin_llabs;
6396 case Builtin::BI__builtin_llabs:
6397 return 0;
6398
6399 case Builtin::BI__builtin_fabsf:
6400 return Builtin::BI__builtin_fabs;
6401 case Builtin::BI__builtin_fabs:
6402 return Builtin::BI__builtin_fabsl;
6403 case Builtin::BI__builtin_fabsl:
6404 return 0;
6405
6406 case Builtin::BI__builtin_cabsf:
6407 return Builtin::BI__builtin_cabs;
6408 case Builtin::BI__builtin_cabs:
6409 return Builtin::BI__builtin_cabsl;
6410 case Builtin::BI__builtin_cabsl:
6411 return 0;
6412
6413 case Builtin::BIabs:
6414 return Builtin::BIlabs;
6415 case Builtin::BIlabs:
6416 return Builtin::BIllabs;
6417 case Builtin::BIllabs:
6418 return 0;
6419
6420 case Builtin::BIfabsf:
6421 return Builtin::BIfabs;
6422 case Builtin::BIfabs:
6423 return Builtin::BIfabsl;
6424 case Builtin::BIfabsl:
6425 return 0;
6426
6427 case Builtin::BIcabsf:
6428 return Builtin::BIcabs;
6429 case Builtin::BIcabs:
6430 return Builtin::BIcabsl;
6431 case Builtin::BIcabsl:
6432 return 0;
6433 }
6434}
6435
6436// Returns the argument type of the absolute value function.
6437static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6438 unsigned AbsType) {
6439 if (AbsType == 0)
6440 return QualType();
6441
6442 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6443 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6444 if (Error != ASTContext::GE_None)
6445 return QualType();
6446
6447 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6448 if (!FT)
6449 return QualType();
6450
6451 if (FT->getNumParams() != 1)
6452 return QualType();
6453
6454 return FT->getParamType(0);
6455}
6456
6457// Returns the best absolute value function, or zero, based on type and
6458// current absolute value function.
6459static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6460 unsigned AbsFunctionKind) {
6461 unsigned BestKind = 0;
6462 uint64_t ArgSize = Context.getTypeSize(ArgType);
6463 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6464 Kind = getLargerAbsoluteValueFunction(Kind)) {
6465 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6466 if (Context.getTypeSize(ParamType) >= ArgSize) {
6467 if (BestKind == 0)
6468 BestKind = Kind;
6469 else if (Context.hasSameType(ParamType, ArgType)) {
6470 BestKind = Kind;
6471 break;
6472 }
6473 }
6474 }
6475 return BestKind;
6476}
6477
6478enum AbsoluteValueKind {
6479 AVK_Integer,
6480 AVK_Floating,
6481 AVK_Complex
6482};
6483
6484static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6485 if (T->isIntegralOrEnumerationType())
6486 return AVK_Integer;
6487 if (T->isRealFloatingType())
6488 return AVK_Floating;
6489 if (T->isAnyComplexType())
6490 return AVK_Complex;
6491
6492 llvm_unreachable("Type not integer, floating, or complex");
6493}
6494
6495// Changes the absolute value function to a different type. Preserves whether
6496// the function is a builtin.
6497static unsigned changeAbsFunction(unsigned AbsKind,
6498 AbsoluteValueKind ValueKind) {
6499 switch (ValueKind) {
6500 case AVK_Integer:
6501 switch (AbsKind) {
6502 default:
6503 return 0;
6504 case Builtin::BI__builtin_fabsf:
6505 case Builtin::BI__builtin_fabs:
6506 case Builtin::BI__builtin_fabsl:
6507 case Builtin::BI__builtin_cabsf:
6508 case Builtin::BI__builtin_cabs:
6509 case Builtin::BI__builtin_cabsl:
6510 return Builtin::BI__builtin_abs;
6511 case Builtin::BIfabsf:
6512 case Builtin::BIfabs:
6513 case Builtin::BIfabsl:
6514 case Builtin::BIcabsf:
6515 case Builtin::BIcabs:
6516 case Builtin::BIcabsl:
6517 return Builtin::BIabs;
6518 }
6519 case AVK_Floating:
6520 switch (AbsKind) {
6521 default:
6522 return 0;
6523 case Builtin::BI__builtin_abs:
6524 case Builtin::BI__builtin_labs:
6525 case Builtin::BI__builtin_llabs:
6526 case Builtin::BI__builtin_cabsf:
6527 case Builtin::BI__builtin_cabs:
6528 case Builtin::BI__builtin_cabsl:
6529 return Builtin::BI__builtin_fabsf;
6530 case Builtin::BIabs:
6531 case Builtin::BIlabs:
6532 case Builtin::BIllabs:
6533 case Builtin::BIcabsf:
6534 case Builtin::BIcabs:
6535 case Builtin::BIcabsl:
6536 return Builtin::BIfabsf;
6537 }
6538 case AVK_Complex:
6539 switch (AbsKind) {
6540 default:
6541 return 0;
6542 case Builtin::BI__builtin_abs:
6543 case Builtin::BI__builtin_labs:
6544 case Builtin::BI__builtin_llabs:
6545 case Builtin::BI__builtin_fabsf:
6546 case Builtin::BI__builtin_fabs:
6547 case Builtin::BI__builtin_fabsl:
6548 return Builtin::BI__builtin_cabsf;
6549 case Builtin::BIabs:
6550 case Builtin::BIlabs:
6551 case Builtin::BIllabs:
6552 case Builtin::BIfabsf:
6553 case Builtin::BIfabs:
6554 case Builtin::BIfabsl:
6555 return Builtin::BIcabsf;
6556 }
6557 }
6558 llvm_unreachable("Unable to convert function");
6559}
6560
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006561static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006562 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6563 if (!FnInfo)
6564 return 0;
6565
6566 switch (FDecl->getBuiltinID()) {
6567 default:
6568 return 0;
6569 case Builtin::BI__builtin_abs:
6570 case Builtin::BI__builtin_fabs:
6571 case Builtin::BI__builtin_fabsf:
6572 case Builtin::BI__builtin_fabsl:
6573 case Builtin::BI__builtin_labs:
6574 case Builtin::BI__builtin_llabs:
6575 case Builtin::BI__builtin_cabs:
6576 case Builtin::BI__builtin_cabsf:
6577 case Builtin::BI__builtin_cabsl:
6578 case Builtin::BIabs:
6579 case Builtin::BIlabs:
6580 case Builtin::BIllabs:
6581 case Builtin::BIfabs:
6582 case Builtin::BIfabsf:
6583 case Builtin::BIfabsl:
6584 case Builtin::BIcabs:
6585 case Builtin::BIcabsf:
6586 case Builtin::BIcabsl:
6587 return FDecl->getBuiltinID();
6588 }
6589 llvm_unreachable("Unknown Builtin type");
6590}
6591
6592// If the replacement is valid, emit a note with replacement function.
6593// Additionally, suggest including the proper header if not already included.
6594static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006595 unsigned AbsKind, QualType ArgType) {
6596 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006597 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006598 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006599 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6600 FunctionName = "std::abs";
6601 if (ArgType->isIntegralOrEnumerationType()) {
6602 HeaderName = "cstdlib";
6603 } else if (ArgType->isRealFloatingType()) {
6604 HeaderName = "cmath";
6605 } else {
6606 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006607 }
Richard Trieubeffb832014-04-15 23:47:53 +00006608
6609 // Lookup all std::abs
6610 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006611 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006612 R.suppressDiagnostics();
6613 S.LookupQualifiedName(R, Std);
6614
6615 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006616 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006617 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6618 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6619 } else {
6620 FDecl = dyn_cast<FunctionDecl>(I);
6621 }
6622 if (!FDecl)
6623 continue;
6624
6625 // Found std::abs(), check that they are the right ones.
6626 if (FDecl->getNumParams() != 1)
6627 continue;
6628
6629 // Check that the parameter type can handle the argument.
6630 QualType ParamType = FDecl->getParamDecl(0)->getType();
6631 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6632 S.Context.getTypeSize(ArgType) <=
6633 S.Context.getTypeSize(ParamType)) {
6634 // Found a function, don't need the header hint.
6635 EmitHeaderHint = false;
6636 break;
6637 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006638 }
Richard Trieubeffb832014-04-15 23:47:53 +00006639 }
6640 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006641 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006642 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6643
6644 if (HeaderName) {
6645 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6646 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6647 R.suppressDiagnostics();
6648 S.LookupName(R, S.getCurScope());
6649
6650 if (R.isSingleResult()) {
6651 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6652 if (FD && FD->getBuiltinID() == AbsKind) {
6653 EmitHeaderHint = false;
6654 } else {
6655 return;
6656 }
6657 } else if (!R.empty()) {
6658 return;
6659 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006660 }
6661 }
6662
6663 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006664 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006665
Richard Trieubeffb832014-04-15 23:47:53 +00006666 if (!HeaderName)
6667 return;
6668
6669 if (!EmitHeaderHint)
6670 return;
6671
Alp Toker5d96e0a2014-07-11 20:53:51 +00006672 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6673 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006674}
6675
Richard Trieua7f30b12016-12-06 01:42:28 +00006676template <std::size_t StrLen>
6677static bool IsStdFunction(const FunctionDecl *FDecl,
6678 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006679 if (!FDecl)
6680 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006681 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006682 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006683 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006684 return false;
6685
6686 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006687}
6688
6689// Warn when using the wrong abs() function.
6690void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006691 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006692 if (Call->getNumArgs() != 1)
6693 return;
6694
6695 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006696 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006697 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006698 return;
6699
6700 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6701 QualType ParamType = Call->getArg(0)->getType();
6702
Alp Toker5d96e0a2014-07-11 20:53:51 +00006703 // Unsigned types cannot be negative. Suggest removing the absolute value
6704 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006705 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006706 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006707 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006708 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6709 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006710 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006711 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6712 return;
6713 }
6714
David Majnemer7f77eb92015-11-15 03:04:34 +00006715 // Taking the absolute value of a pointer is very suspicious, they probably
6716 // wanted to index into an array, dereference a pointer, call a function, etc.
6717 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6718 unsigned DiagType = 0;
6719 if (ArgType->isFunctionType())
6720 DiagType = 1;
6721 else if (ArgType->isArrayType())
6722 DiagType = 2;
6723
6724 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6725 return;
6726 }
6727
Richard Trieubeffb832014-04-15 23:47:53 +00006728 // std::abs has overloads which prevent most of the absolute value problems
6729 // from occurring.
6730 if (IsStdAbs)
6731 return;
6732
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006733 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6734 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6735
6736 // The argument and parameter are the same kind. Check if they are the right
6737 // size.
6738 if (ArgValueKind == ParamValueKind) {
6739 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6740 return;
6741
6742 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6743 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6744 << FDecl << ArgType << ParamType;
6745
6746 if (NewAbsKind == 0)
6747 return;
6748
6749 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006750 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006751 return;
6752 }
6753
6754 // ArgValueKind != ParamValueKind
6755 // The wrong type of absolute value function was used. Attempt to find the
6756 // proper one.
6757 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6758 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6759 if (NewAbsKind == 0)
6760 return;
6761
6762 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6763 << FDecl << ParamValueKind << ArgValueKind;
6764
6765 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006766 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006767}
6768
Richard Trieu67c00712016-12-05 23:41:46 +00006769//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006770void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6771 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006772 if (!Call || !FDecl) return;
6773
6774 // Ignore template specializations and macros.
6775 if (!ActiveTemplateInstantiations.empty()) return;
6776 if (Call->getExprLoc().isMacroID()) return;
6777
6778 // Only care about the one template argument, two function parameter std::max
6779 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006780 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006781 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6782 if (!ArgList) return;
6783 if (ArgList->size() != 1) return;
6784
6785 // Check that template type argument is unsigned integer.
6786 const auto& TA = ArgList->get(0);
6787 if (TA.getKind() != TemplateArgument::Type) return;
6788 QualType ArgType = TA.getAsType();
6789 if (!ArgType->isUnsignedIntegerType()) return;
6790
6791 // See if either argument is a literal zero.
6792 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6793 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6794 if (!MTE) return false;
6795 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6796 if (!Num) return false;
6797 if (Num->getValue() != 0) return false;
6798 return true;
6799 };
6800
6801 const Expr *FirstArg = Call->getArg(0);
6802 const Expr *SecondArg = Call->getArg(1);
6803 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6804 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6805
6806 // Only warn when exactly one argument is zero.
6807 if (IsFirstArgZero == IsSecondArgZero) return;
6808
6809 SourceRange FirstRange = FirstArg->getSourceRange();
6810 SourceRange SecondRange = SecondArg->getSourceRange();
6811
6812 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6813
6814 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6815 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6816
6817 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6818 SourceRange RemovalRange;
6819 if (IsFirstArgZero) {
6820 RemovalRange = SourceRange(FirstRange.getBegin(),
6821 SecondRange.getBegin().getLocWithOffset(-1));
6822 } else {
6823 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6824 SecondRange.getEnd());
6825 }
6826
6827 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6828 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6829 << FixItHint::CreateRemoval(RemovalRange);
6830}
6831
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006832//===--- CHECK: Standard memory functions ---------------------------------===//
6833
Nico Weber0e6daef2013-12-26 23:38:39 +00006834/// \brief Takes the expression passed to the size_t parameter of functions
6835/// such as memcmp, strncat, etc and warns if it's a comparison.
6836///
6837/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6838static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6839 IdentifierInfo *FnName,
6840 SourceLocation FnLoc,
6841 SourceLocation RParenLoc) {
6842 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6843 if (!Size)
6844 return false;
6845
6846 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6847 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6848 return false;
6849
Nico Weber0e6daef2013-12-26 23:38:39 +00006850 SourceRange SizeRange = Size->getSourceRange();
6851 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6852 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006853 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006854 << FnName << FixItHint::CreateInsertion(
6855 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006856 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006857 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006858 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006859 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6860 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006861
6862 return true;
6863}
6864
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006865/// \brief Determine whether the given type is or contains a dynamic class type
6866/// (e.g., whether it has a vtable).
6867static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6868 bool &IsContained) {
6869 // Look through array types while ignoring qualifiers.
6870 const Type *Ty = T->getBaseElementTypeUnsafe();
6871 IsContained = false;
6872
6873 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6874 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006875 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006876 return nullptr;
6877
6878 if (RD->isDynamicClass())
6879 return RD;
6880
6881 // Check all the fields. If any bases were dynamic, the class is dynamic.
6882 // It's impossible for a class to transitively contain itself by value, so
6883 // infinite recursion is impossible.
6884 for (auto *FD : RD->fields()) {
6885 bool SubContained;
6886 if (const CXXRecordDecl *ContainedRD =
6887 getContainedDynamicClass(FD->getType(), SubContained)) {
6888 IsContained = true;
6889 return ContainedRD;
6890 }
6891 }
6892
6893 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006894}
6895
Chandler Carruth889ed862011-06-21 23:04:20 +00006896/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006897/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006898static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006899 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006900 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6901 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6902 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006903
Craig Topperc3ec1492014-05-26 06:22:03 +00006904 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006905}
6906
Chandler Carruth889ed862011-06-21 23:04:20 +00006907/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006908static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006909 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6910 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6911 if (SizeOf->getKind() == clang::UETT_SizeOf)
6912 return SizeOf->getTypeOfArgument();
6913
6914 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006915}
6916
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006917/// \brief Check for dangerous or invalid arguments to memset().
6918///
Chandler Carruthac687262011-06-03 06:23:57 +00006919/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006920/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6921/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006922///
6923/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006924void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006925 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006926 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006927 assert(BId != 0);
6928
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006929 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006930 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006931 unsigned ExpectedNumArgs =
6932 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006933 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006934 return;
6935
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006936 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006937 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006938 unsigned LenArg =
6939 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006940 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006941
Nico Weber0e6daef2013-12-26 23:38:39 +00006942 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6943 Call->getLocStart(), Call->getRParenLoc()))
6944 return;
6945
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006946 // We have special checking when the length is a sizeof expression.
6947 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6948 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6949 llvm::FoldingSetNodeID SizeOfArgID;
6950
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006951 // Although widely used, 'bzero' is not a standard function. Be more strict
6952 // with the argument types before allowing diagnostics and only allow the
6953 // form bzero(ptr, sizeof(...)).
6954 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6955 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6956 return;
6957
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006958 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6959 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006960 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006961
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006962 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006963 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006964 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006965 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006966
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006967 // Never warn about void type pointers. This can be used to suppress
6968 // false positives.
6969 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006970 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006971
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006972 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6973 // actually comparing the expressions for equality. Because computing the
6974 // expression IDs can be expensive, we only do this if the diagnostic is
6975 // enabled.
6976 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006977 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6978 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006979 // We only compute IDs for expressions if the warning is enabled, and
6980 // cache the sizeof arg's ID.
6981 if (SizeOfArgID == llvm::FoldingSetNodeID())
6982 SizeOfArg->Profile(SizeOfArgID, Context, true);
6983 llvm::FoldingSetNodeID DestID;
6984 Dest->Profile(DestID, Context, true);
6985 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006986 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6987 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006988 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006989 StringRef ReadableName = FnName->getName();
6990
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006991 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006992 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006993 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006994 if (!PointeeTy->isIncompleteType() &&
6995 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006996 ActionIdx = 2; // If the pointee's size is sizeof(char),
6997 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006998
6999 // If the function is defined as a builtin macro, do not show macro
7000 // expansion.
7001 SourceLocation SL = SizeOfArg->getExprLoc();
7002 SourceRange DSR = Dest->getSourceRange();
7003 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007004 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007005
7006 if (SM.isMacroArgExpansion(SL)) {
7007 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7008 SL = SM.getSpellingLoc(SL);
7009 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7010 SM.getSpellingLoc(DSR.getEnd()));
7011 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7012 SM.getSpellingLoc(SSR.getEnd()));
7013 }
7014
Anna Zaksd08d9152012-05-30 23:14:52 +00007015 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007016 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007017 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007018 << PointeeTy
7019 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007020 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007021 << SSR);
7022 DiagRuntimeBehavior(SL, SizeOfArg,
7023 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7024 << ActionIdx
7025 << SSR);
7026
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007027 break;
7028 }
7029 }
7030
7031 // Also check for cases where the sizeof argument is the exact same
7032 // type as the memory argument, and where it points to a user-defined
7033 // record type.
7034 if (SizeOfArgTy != QualType()) {
7035 if (PointeeTy->isRecordType() &&
7036 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7037 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7038 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7039 << FnName << SizeOfArgTy << ArgIdx
7040 << PointeeTy << Dest->getSourceRange()
7041 << LenExpr->getSourceRange());
7042 break;
7043 }
Nico Weberc5e73862011-06-14 16:14:58 +00007044 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007045 } else if (DestTy->isArrayType()) {
7046 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007047 }
Nico Weberc5e73862011-06-14 16:14:58 +00007048
Nico Weberc44b35e2015-03-21 17:37:46 +00007049 if (PointeeTy == QualType())
7050 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007051
Nico Weberc44b35e2015-03-21 17:37:46 +00007052 // Always complain about dynamic classes.
7053 bool IsContained;
7054 if (const CXXRecordDecl *ContainedRD =
7055 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007056
Nico Weberc44b35e2015-03-21 17:37:46 +00007057 unsigned OperationType = 0;
7058 // "overwritten" if we're warning about the destination for any call
7059 // but memcmp; otherwise a verb appropriate to the call.
7060 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7061 if (BId == Builtin::BImemcpy)
7062 OperationType = 1;
7063 else if(BId == Builtin::BImemmove)
7064 OperationType = 2;
7065 else if (BId == Builtin::BImemcmp)
7066 OperationType = 3;
7067 }
7068
John McCall31168b02011-06-15 23:02:42 +00007069 DiagRuntimeBehavior(
7070 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007071 PDiag(diag::warn_dyn_class_memaccess)
7072 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7073 << FnName << IsContained << ContainedRD << OperationType
7074 << Call->getCallee()->getSourceRange());
7075 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7076 BId != Builtin::BImemset)
7077 DiagRuntimeBehavior(
7078 Dest->getExprLoc(), Dest,
7079 PDiag(diag::warn_arc_object_memaccess)
7080 << ArgIdx << FnName << PointeeTy
7081 << Call->getCallee()->getSourceRange());
7082 else
7083 continue;
7084
7085 DiagRuntimeBehavior(
7086 Dest->getExprLoc(), Dest,
7087 PDiag(diag::note_bad_memaccess_silence)
7088 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7089 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007090 }
7091}
7092
Ted Kremenek6865f772011-08-18 20:55:45 +00007093// A little helper routine: ignore addition and subtraction of integer literals.
7094// This intentionally does not ignore all integer constant expressions because
7095// we don't want to remove sizeof().
7096static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7097 Ex = Ex->IgnoreParenCasts();
7098
7099 for (;;) {
7100 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7101 if (!BO || !BO->isAdditiveOp())
7102 break;
7103
7104 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7105 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7106
7107 if (isa<IntegerLiteral>(RHS))
7108 Ex = LHS;
7109 else if (isa<IntegerLiteral>(LHS))
7110 Ex = RHS;
7111 else
7112 break;
7113 }
7114
7115 return Ex;
7116}
7117
Anna Zaks13b08572012-08-08 21:42:23 +00007118static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7119 ASTContext &Context) {
7120 // Only handle constant-sized or VLAs, but not flexible members.
7121 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7122 // Only issue the FIXIT for arrays of size > 1.
7123 if (CAT->getSize().getSExtValue() <= 1)
7124 return false;
7125 } else if (!Ty->isVariableArrayType()) {
7126 return false;
7127 }
7128 return true;
7129}
7130
Ted Kremenek6865f772011-08-18 20:55:45 +00007131// Warn if the user has made the 'size' argument to strlcpy or strlcat
7132// be the size of the source, instead of the destination.
7133void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7134 IdentifierInfo *FnName) {
7135
7136 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007137 unsigned NumArgs = Call->getNumArgs();
7138 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007139 return;
7140
7141 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7142 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007143 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007144
7145 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7146 Call->getLocStart(), Call->getRParenLoc()))
7147 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007148
7149 // Look for 'strlcpy(dst, x, sizeof(x))'
7150 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7151 CompareWithSrc = Ex;
7152 else {
7153 // Look for 'strlcpy(dst, x, strlen(x))'
7154 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007155 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7156 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007157 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7158 }
7159 }
7160
7161 if (!CompareWithSrc)
7162 return;
7163
7164 // Determine if the argument to sizeof/strlen is equal to the source
7165 // argument. In principle there's all kinds of things you could do
7166 // here, for instance creating an == expression and evaluating it with
7167 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7168 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7169 if (!SrcArgDRE)
7170 return;
7171
7172 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7173 if (!CompareWithSrcDRE ||
7174 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7175 return;
7176
7177 const Expr *OriginalSizeArg = Call->getArg(2);
7178 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7179 << OriginalSizeArg->getSourceRange() << FnName;
7180
7181 // Output a FIXIT hint if the destination is an array (rather than a
7182 // pointer to an array). This could be enhanced to handle some
7183 // pointers if we know the actual size, like if DstArg is 'array+2'
7184 // we could say 'sizeof(array)-2'.
7185 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007186 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007187 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007188
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007189 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007190 llvm::raw_svector_ostream OS(sizeString);
7191 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007192 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007193 OS << ")";
7194
7195 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7196 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7197 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007198}
7199
Anna Zaks314cd092012-02-01 19:08:57 +00007200/// Check if two expressions refer to the same declaration.
7201static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7202 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7203 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7204 return D1->getDecl() == D2->getDecl();
7205 return false;
7206}
7207
7208static const Expr *getStrlenExprArg(const Expr *E) {
7209 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7210 const FunctionDecl *FD = CE->getDirectCallee();
7211 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007212 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007213 return CE->getArg(0)->IgnoreParenCasts();
7214 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007215 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007216}
7217
7218// Warn on anti-patterns as the 'size' argument to strncat.
7219// The correct size argument should look like following:
7220// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7221void Sema::CheckStrncatArguments(const CallExpr *CE,
7222 IdentifierInfo *FnName) {
7223 // Don't crash if the user has the wrong number of arguments.
7224 if (CE->getNumArgs() < 3)
7225 return;
7226 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7227 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7228 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7229
Nico Weber0e6daef2013-12-26 23:38:39 +00007230 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7231 CE->getRParenLoc()))
7232 return;
7233
Anna Zaks314cd092012-02-01 19:08:57 +00007234 // Identify common expressions, which are wrongly used as the size argument
7235 // to strncat and may lead to buffer overflows.
7236 unsigned PatternType = 0;
7237 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7238 // - sizeof(dst)
7239 if (referToTheSameDecl(SizeOfArg, DstArg))
7240 PatternType = 1;
7241 // - sizeof(src)
7242 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7243 PatternType = 2;
7244 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7245 if (BE->getOpcode() == BO_Sub) {
7246 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7247 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7248 // - sizeof(dst) - strlen(dst)
7249 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7250 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7251 PatternType = 1;
7252 // - sizeof(src) - (anything)
7253 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7254 PatternType = 2;
7255 }
7256 }
7257
7258 if (PatternType == 0)
7259 return;
7260
Anna Zaks5069aa32012-02-03 01:27:37 +00007261 // Generate the diagnostic.
7262 SourceLocation SL = LenArg->getLocStart();
7263 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007264 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007265
7266 // If the function is defined as a builtin macro, do not show macro expansion.
7267 if (SM.isMacroArgExpansion(SL)) {
7268 SL = SM.getSpellingLoc(SL);
7269 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7270 SM.getSpellingLoc(SR.getEnd()));
7271 }
7272
Anna Zaks13b08572012-08-08 21:42:23 +00007273 // Check if the destination is an array (rather than a pointer to an array).
7274 QualType DstTy = DstArg->getType();
7275 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7276 Context);
7277 if (!isKnownSizeArray) {
7278 if (PatternType == 1)
7279 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7280 else
7281 Diag(SL, diag::warn_strncat_src_size) << SR;
7282 return;
7283 }
7284
Anna Zaks314cd092012-02-01 19:08:57 +00007285 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007286 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007287 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007288 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007289
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007290 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007291 llvm::raw_svector_ostream OS(sizeString);
7292 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007293 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007294 OS << ") - ";
7295 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007296 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007297 OS << ") - 1";
7298
Anna Zaks5069aa32012-02-03 01:27:37 +00007299 Diag(SL, diag::note_strncat_wrong_size)
7300 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007301}
7302
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007303//===--- CHECK: Return Address of Stack Variable --------------------------===//
7304
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007305static const Expr *EvalVal(const Expr *E,
7306 SmallVectorImpl<const DeclRefExpr *> &refVars,
7307 const Decl *ParentDecl);
7308static const Expr *EvalAddr(const Expr *E,
7309 SmallVectorImpl<const DeclRefExpr *> &refVars,
7310 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007311
7312/// CheckReturnStackAddr - Check if a return statement returns the address
7313/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007314static void
7315CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7316 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007317
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007318 const Expr *stackE = nullptr;
7319 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007320
7321 // Perform checking for returned stack addresses, local blocks,
7322 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007323 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007324 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007325 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007326 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007327 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007328 }
7329
Craig Topperc3ec1492014-05-26 06:22:03 +00007330 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007331 return; // Nothing suspicious was found.
7332
Richard Trieu81b6c562016-08-05 23:24:47 +00007333 // Parameters are initalized in the calling scope, so taking the address
7334 // of a parameter reference doesn't need a warning.
7335 for (auto *DRE : refVars)
7336 if (isa<ParmVarDecl>(DRE->getDecl()))
7337 return;
7338
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007339 SourceLocation diagLoc;
7340 SourceRange diagRange;
7341 if (refVars.empty()) {
7342 diagLoc = stackE->getLocStart();
7343 diagRange = stackE->getSourceRange();
7344 } else {
7345 // We followed through a reference variable. 'stackE' contains the
7346 // problematic expression but we will warn at the return statement pointing
7347 // at the reference variable. We will later display the "trail" of
7348 // reference variables using notes.
7349 diagLoc = refVars[0]->getLocStart();
7350 diagRange = refVars[0]->getSourceRange();
7351 }
7352
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007353 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7354 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007355 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007356 << DR->getDecl()->getDeclName() << diagRange;
7357 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007358 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007359 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007360 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007361 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007362 // If there is an LValue->RValue conversion, then the value of the
7363 // reference type is used, not the reference.
7364 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7365 if (ICE->getCastKind() == CK_LValueToRValue) {
7366 return;
7367 }
7368 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007369 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7370 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007371 }
7372
7373 // Display the "trail" of reference variables that we followed until we
7374 // found the problematic expression using notes.
7375 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007376 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007377 // If this var binds to another reference var, show the range of the next
7378 // var, otherwise the var binds to the problematic expression, in which case
7379 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007380 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7381 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007382 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7383 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007384 }
7385}
7386
7387/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7388/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007389/// to a location on the stack, a local block, an address of a label, or a
7390/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007391/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007392/// encounter a subexpression that (1) clearly does not lead to one of the
7393/// above problematic expressions (2) is something we cannot determine leads to
7394/// a problematic expression based on such local checking.
7395///
7396/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7397/// the expression that they point to. Such variables are added to the
7398/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007399///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007400/// EvalAddr processes expressions that are pointers that are used as
7401/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007402/// At the base case of the recursion is a check for the above problematic
7403/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007404///
7405/// This implementation handles:
7406///
7407/// * pointer-to-pointer casts
7408/// * implicit conversions from array references to pointers
7409/// * taking the address of fields
7410/// * arbitrary interplay between "&" and "*" operators
7411/// * pointer arithmetic from an address of a stack variable
7412/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007413static const Expr *EvalAddr(const Expr *E,
7414 SmallVectorImpl<const DeclRefExpr *> &refVars,
7415 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007416 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007417 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007418
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007419 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007420 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007421 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007422 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007423 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007424
Peter Collingbourne91147592011-04-15 00:35:48 +00007425 E = E->IgnoreParens();
7426
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007427 // Our "symbolic interpreter" is just a dispatch off the currently
7428 // viewed AST node. We then recursively traverse the AST by calling
7429 // EvalAddr and EvalVal appropriately.
7430 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007431 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007432 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007433
Richard Smith40f08eb2014-01-30 22:05:38 +00007434 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007435 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007436 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007437
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007438 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007439 // If this is a reference variable, follow through to the expression that
7440 // it points to.
7441 if (V->hasLocalStorage() &&
7442 V->getType()->isReferenceType() && V->hasInit()) {
7443 // Add the reference variable to the "trail".
7444 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007445 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007446 }
7447
Craig Topperc3ec1492014-05-26 06:22:03 +00007448 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007449 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007450
Chris Lattner934edb22007-12-28 05:31:15 +00007451 case Stmt::UnaryOperatorClass: {
7452 // The only unary operator that make sense to handle here
7453 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007454 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007455
John McCalle3027922010-08-25 11:45:40 +00007456 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007457 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007458 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007459 }
Mike Stump11289f42009-09-09 15:08:12 +00007460
Chris Lattner934edb22007-12-28 05:31:15 +00007461 case Stmt::BinaryOperatorClass: {
7462 // Handle pointer arithmetic. All other binary operators are not valid
7463 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007464 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007465 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007466
John McCalle3027922010-08-25 11:45:40 +00007467 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007468 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007469
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007470 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007471
7472 // Determine which argument is the real pointer base. It could be
7473 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007474 if (!Base->getType()->isPointerType())
7475 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007476
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007477 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007478 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007479 }
Steve Naroff2752a172008-09-10 19:17:48 +00007480
Chris Lattner934edb22007-12-28 05:31:15 +00007481 // For conditional operators we need to see if either the LHS or RHS are
7482 // valid DeclRefExpr*s. If one of them is valid, we return it.
7483 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007484 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007485
Chris Lattner934edb22007-12-28 05:31:15 +00007486 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007487 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007488 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007489 // In C++, we can have a throw-expression, which has 'void' type.
7490 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007491 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007492 return LHS;
7493 }
Chris Lattner934edb22007-12-28 05:31:15 +00007494
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007495 // In C++, we can have a throw-expression, which has 'void' type.
7496 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007497 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007498
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007499 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007500 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007501
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007502 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007503 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007504 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007505 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007506
7507 case Stmt::AddrLabelExprClass:
7508 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007509
John McCall28fc7092011-11-10 05:35:25 +00007510 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007511 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7512 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007513
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007514 // For casts, we need to handle conversions from arrays to
7515 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007516 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007517 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007518 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007519 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007520 case Stmt::CXXStaticCastExprClass:
7521 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007522 case Stmt::CXXConstCastExprClass:
7523 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007524 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007525 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007526 case CK_LValueToRValue:
7527 case CK_NoOp:
7528 case CK_BaseToDerived:
7529 case CK_DerivedToBase:
7530 case CK_UncheckedDerivedToBase:
7531 case CK_Dynamic:
7532 case CK_CPointerToObjCPointerCast:
7533 case CK_BlockPointerToObjCPointerCast:
7534 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007535 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007536
7537 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007538 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007539
Richard Trieudadefde2014-07-02 04:39:38 +00007540 case CK_BitCast:
7541 if (SubExpr->getType()->isAnyPointerType() ||
7542 SubExpr->getType()->isBlockPointerType() ||
7543 SubExpr->getType()->isObjCQualifiedIdType())
7544 return EvalAddr(SubExpr, refVars, ParentDecl);
7545 else
7546 return nullptr;
7547
Eli Friedman8195ad72012-02-23 23:04:32 +00007548 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007549 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007550 }
Chris Lattner934edb22007-12-28 05:31:15 +00007551 }
Mike Stump11289f42009-09-09 15:08:12 +00007552
Douglas Gregorfe314812011-06-21 17:03:29 +00007553 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007554 if (const Expr *Result =
7555 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7556 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007557 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007558 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007559
Chris Lattner934edb22007-12-28 05:31:15 +00007560 // Everything else: we simply don't reason about them.
7561 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007562 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007563 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007564}
Mike Stump11289f42009-09-09 15:08:12 +00007565
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007566/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7567/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007568static const Expr *EvalVal(const Expr *E,
7569 SmallVectorImpl<const DeclRefExpr *> &refVars,
7570 const Decl *ParentDecl) {
7571 do {
7572 // We should only be called for evaluating non-pointer expressions, or
7573 // expressions with a pointer type that are not used as references but
7574 // instead
7575 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007576
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007577 // Our "symbolic interpreter" is just a dispatch off the currently
7578 // viewed AST node. We then recursively traverse the AST by calling
7579 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007580
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007581 E = E->IgnoreParens();
7582 switch (E->getStmtClass()) {
7583 case Stmt::ImplicitCastExprClass: {
7584 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7585 if (IE->getValueKind() == VK_LValue) {
7586 E = IE->getSubExpr();
7587 continue;
7588 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007589 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007590 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007591
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007592 case Stmt::ExprWithCleanupsClass:
7593 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7594 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007595
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007596 case Stmt::DeclRefExprClass: {
7597 // When we hit a DeclRefExpr we are looking at code that refers to a
7598 // variable's name. If it's not a reference variable we check if it has
7599 // local storage within the function, and if so, return the expression.
7600 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7601
7602 // If we leave the immediate function, the lifetime isn't about to end.
7603 if (DR->refersToEnclosingVariableOrCapture())
7604 return nullptr;
7605
7606 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7607 // Check if it refers to itself, e.g. "int& i = i;".
7608 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007609 return DR;
7610
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007611 if (V->hasLocalStorage()) {
7612 if (!V->getType()->isReferenceType())
7613 return DR;
7614
7615 // Reference variable, follow through to the expression that
7616 // it points to.
7617 if (V->hasInit()) {
7618 // Add the reference variable to the "trail".
7619 refVars.push_back(DR);
7620 return EvalVal(V->getInit(), refVars, V);
7621 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007622 }
7623 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007624
7625 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007626 }
Mike Stump11289f42009-09-09 15:08:12 +00007627
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007628 case Stmt::UnaryOperatorClass: {
7629 // The only unary operator that make sense to handle here
7630 // is Deref. All others don't resolve to a "name." This includes
7631 // handling all sorts of rvalues passed to a unary operator.
7632 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007633
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007634 if (U->getOpcode() == UO_Deref)
7635 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007636
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007637 return nullptr;
7638 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007639
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007640 case Stmt::ArraySubscriptExprClass: {
7641 // Array subscripts are potential references to data on the stack. We
7642 // retrieve the DeclRefExpr* for the array variable if it indeed
7643 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007644 const auto *ASE = cast<ArraySubscriptExpr>(E);
7645 if (ASE->isTypeDependent())
7646 return nullptr;
7647 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007648 }
Mike Stump11289f42009-09-09 15:08:12 +00007649
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007650 case Stmt::OMPArraySectionExprClass: {
7651 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7652 ParentDecl);
7653 }
Mike Stump11289f42009-09-09 15:08:12 +00007654
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007655 case Stmt::ConditionalOperatorClass: {
7656 // For conditional operators we need to see if either the LHS or RHS are
7657 // non-NULL Expr's. If one is non-NULL, we return it.
7658 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007659
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007660 // Handle the GNU extension for missing LHS.
7661 if (const Expr *LHSExpr = C->getLHS()) {
7662 // In C++, we can have a throw-expression, which has 'void' type.
7663 if (!LHSExpr->getType()->isVoidType())
7664 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7665 return LHS;
7666 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007667
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007668 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007669 if (C->getRHS()->getType()->isVoidType())
7670 return nullptr;
7671
7672 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007673 }
7674
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007675 // Accesses to members are potential references to data on the stack.
7676 case Stmt::MemberExprClass: {
7677 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007678
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007679 // Check for indirect access. We only want direct field accesses.
7680 if (M->isArrow())
7681 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007682
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007683 // Check whether the member type is itself a reference, in which case
7684 // we're not going to refer to the member, but to what the member refers
7685 // to.
7686 if (M->getMemberDecl()->getType()->isReferenceType())
7687 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007688
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007689 return EvalVal(M->getBase(), refVars, ParentDecl);
7690 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007691
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007692 case Stmt::MaterializeTemporaryExprClass:
7693 if (const Expr *Result =
7694 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7695 refVars, ParentDecl))
7696 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007697 return E;
7698
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007699 default:
7700 // Check that we don't return or take the address of a reference to a
7701 // temporary. This is only useful in C++.
7702 if (!E->isTypeDependent() && E->isRValue())
7703 return E;
7704
7705 // Everything else: we simply don't reason about them.
7706 return nullptr;
7707 }
7708 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007709}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007710
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007711void
7712Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7713 SourceLocation ReturnLoc,
7714 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007715 const AttrVec *Attrs,
7716 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007717 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7718
7719 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007720 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7721 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007722 CheckNonNullExpr(*this, RetValExp))
7723 Diag(ReturnLoc, diag::warn_null_ret)
7724 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007725
7726 // C++11 [basic.stc.dynamic.allocation]p4:
7727 // If an allocation function declared with a non-throwing
7728 // exception-specification fails to allocate storage, it shall return
7729 // a null pointer. Any other allocation function that fails to allocate
7730 // storage shall indicate failure only by throwing an exception [...]
7731 if (FD) {
7732 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7733 if (Op == OO_New || Op == OO_Array_New) {
7734 const FunctionProtoType *Proto
7735 = FD->getType()->castAs<FunctionProtoType>();
7736 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7737 CheckNonNullExpr(*this, RetValExp))
7738 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7739 << FD << getLangOpts().CPlusPlus11;
7740 }
7741 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007742}
7743
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007744//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7745
7746/// Check for comparisons of floating point operands using != and ==.
7747/// Issue a warning if these are no self-comparisons, as they are not likely
7748/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007749void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007750 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7751 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007752
7753 // Special case: check for x == x (which is OK).
7754 // Do not emit warnings for such cases.
7755 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7756 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7757 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007758 return;
Mike Stump11289f42009-09-09 15:08:12 +00007759
Ted Kremenekeda40e22007-11-29 00:59:04 +00007760 // Special case: check for comparisons against literals that can be exactly
7761 // represented by APFloat. In such cases, do not emit a warning. This
7762 // is a heuristic: often comparison against such literals are used to
7763 // detect if a value in a variable has not changed. This clearly can
7764 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007765 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7766 if (FLL->isExact())
7767 return;
7768 } else
7769 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7770 if (FLR->isExact())
7771 return;
Mike Stump11289f42009-09-09 15:08:12 +00007772
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007773 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007774 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007775 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007776 return;
Mike Stump11289f42009-09-09 15:08:12 +00007777
David Blaikie1f4ff152012-07-16 20:47:22 +00007778 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007779 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007780 return;
Mike Stump11289f42009-09-09 15:08:12 +00007781
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007782 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007783 Diag(Loc, diag::warn_floatingpoint_eq)
7784 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007785}
John McCallca01b222010-01-04 23:21:16 +00007786
John McCall70aa5392010-01-06 05:24:50 +00007787//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7788//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007789
John McCall70aa5392010-01-06 05:24:50 +00007790namespace {
John McCallca01b222010-01-04 23:21:16 +00007791
John McCall70aa5392010-01-06 05:24:50 +00007792/// Structure recording the 'active' range of an integer-valued
7793/// expression.
7794struct IntRange {
7795 /// The number of bits active in the int.
7796 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007797
John McCall70aa5392010-01-06 05:24:50 +00007798 /// True if the int is known not to have negative values.
7799 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007800
John McCall70aa5392010-01-06 05:24:50 +00007801 IntRange(unsigned Width, bool NonNegative)
7802 : Width(Width), NonNegative(NonNegative)
7803 {}
John McCallca01b222010-01-04 23:21:16 +00007804
John McCall817d4af2010-11-10 23:38:19 +00007805 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007806 static IntRange forBoolType() {
7807 return IntRange(1, true);
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 the given integral type.
7811 static IntRange forValueOfType(ASTContext &C, QualType T) {
7812 return forValueOfCanonicalType(C,
7813 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007814 }
7815
John McCall817d4af2010-11-10 23:38:19 +00007816 /// Returns the range of an opaque value of a canonical integral type.
7817 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007818 assert(T->isCanonicalUnqualified());
7819
7820 if (const VectorType *VT = dyn_cast<VectorType>(T))
7821 T = VT->getElementType().getTypePtr();
7822 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7823 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007824 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7825 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007826
David Majnemer6a426652013-06-07 22:07:20 +00007827 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007828 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007829 EnumDecl *Enum = ET->getDecl();
7830 if (!Enum->isCompleteDefinition())
7831 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007832
David Majnemer6a426652013-06-07 22:07:20 +00007833 unsigned NumPositive = Enum->getNumPositiveBits();
7834 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007835
David Majnemer6a426652013-06-07 22:07:20 +00007836 if (NumNegative == 0)
7837 return IntRange(NumPositive, true/*NonNegative*/);
7838 else
7839 return IntRange(std::max(NumPositive + 1, NumNegative),
7840 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007841 }
John McCall70aa5392010-01-06 05:24:50 +00007842
7843 const BuiltinType *BT = cast<BuiltinType>(T);
7844 assert(BT->isInteger());
7845
7846 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7847 }
7848
John McCall817d4af2010-11-10 23:38:19 +00007849 /// Returns the "target" range of a canonical integral type, i.e.
7850 /// the range of values expressible in the type.
7851 ///
7852 /// This matches forValueOfCanonicalType except that enums have the
7853 /// full range of their type, not the range of their enumerators.
7854 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7855 assert(T->isCanonicalUnqualified());
7856
7857 if (const VectorType *VT = dyn_cast<VectorType>(T))
7858 T = VT->getElementType().getTypePtr();
7859 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7860 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007861 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7862 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007863 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007864 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007865
7866 const BuiltinType *BT = cast<BuiltinType>(T);
7867 assert(BT->isInteger());
7868
7869 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7870 }
7871
7872 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007873 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007874 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007875 L.NonNegative && R.NonNegative);
7876 }
7877
John McCall817d4af2010-11-10 23:38:19 +00007878 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007879 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007880 return IntRange(std::min(L.Width, R.Width),
7881 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007882 }
7883};
7884
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007885IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007886 if (value.isSigned() && value.isNegative())
7887 return IntRange(value.getMinSignedBits(), false);
7888
7889 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007890 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007891
7892 // isNonNegative() just checks the sign bit without considering
7893 // signedness.
7894 return IntRange(value.getActiveBits(), true);
7895}
7896
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007897IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7898 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007899 if (result.isInt())
7900 return GetValueRange(C, result.getInt(), MaxWidth);
7901
7902 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007903 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7904 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7905 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7906 R = IntRange::join(R, El);
7907 }
John McCall70aa5392010-01-06 05:24:50 +00007908 return R;
7909 }
7910
7911 if (result.isComplexInt()) {
7912 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7913 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7914 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007915 }
7916
7917 // This can happen with lossless casts to intptr_t of "based" lvalues.
7918 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007919 // FIXME: The only reason we need to pass the type in here is to get
7920 // the sign right on this one case. It would be nice if APValue
7921 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007922 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007923 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007924}
John McCall70aa5392010-01-06 05:24:50 +00007925
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007926QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007927 QualType Ty = E->getType();
7928 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7929 Ty = AtomicRHS->getValueType();
7930 return Ty;
7931}
7932
John McCall70aa5392010-01-06 05:24:50 +00007933/// Pseudo-evaluate the given integer expression, estimating the
7934/// range of values it might take.
7935///
7936/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007937IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007938 E = E->IgnoreParens();
7939
7940 // Try a full evaluation first.
7941 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007942 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007943 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007944
7945 // I think we only want to look through implicit casts here; if the
7946 // user has an explicit widening cast, we should treat the value as
7947 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007948 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007949 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007950 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7951
Eli Friedmane6d33952013-07-08 20:20:06 +00007952 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007953
George Burgess IVdf1ed002016-01-13 01:52:39 +00007954 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7955 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007956
John McCall70aa5392010-01-06 05:24:50 +00007957 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007958 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007959 return OutputTypeRange;
7960
7961 IntRange SubRange
7962 = GetExprRange(C, CE->getSubExpr(),
7963 std::min(MaxWidth, OutputTypeRange.Width));
7964
7965 // Bail out if the subexpr's range is as wide as the cast type.
7966 if (SubRange.Width >= OutputTypeRange.Width)
7967 return OutputTypeRange;
7968
7969 // Otherwise, we take the smaller width, and we're non-negative if
7970 // either the output type or the subexpr is.
7971 return IntRange(SubRange.Width,
7972 SubRange.NonNegative || OutputTypeRange.NonNegative);
7973 }
7974
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007975 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007976 // If we can fold the condition, just take that operand.
7977 bool CondResult;
7978 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7979 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7980 : CO->getFalseExpr(),
7981 MaxWidth);
7982
7983 // Otherwise, conservatively merge.
7984 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7985 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7986 return IntRange::join(L, R);
7987 }
7988
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007989 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007990 switch (BO->getOpcode()) {
7991
7992 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007993 case BO_LAnd:
7994 case BO_LOr:
7995 case BO_LT:
7996 case BO_GT:
7997 case BO_LE:
7998 case BO_GE:
7999 case BO_EQ:
8000 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008001 return IntRange::forBoolType();
8002
John McCallc3688382011-07-13 06:35:24 +00008003 // The type of the assignments is the type of the LHS, so the RHS
8004 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008005 case BO_MulAssign:
8006 case BO_DivAssign:
8007 case BO_RemAssign:
8008 case BO_AddAssign:
8009 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008010 case BO_XorAssign:
8011 case BO_OrAssign:
8012 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008013 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008014
John McCallc3688382011-07-13 06:35:24 +00008015 // Simple assignments just pass through the RHS, which will have
8016 // been coerced to the LHS type.
8017 case BO_Assign:
8018 // TODO: bitfields?
8019 return GetExprRange(C, BO->getRHS(), MaxWidth);
8020
John McCall70aa5392010-01-06 05:24:50 +00008021 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008022 case BO_PtrMemD:
8023 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008024 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008025
John McCall2ce81ad2010-01-06 22:07:33 +00008026 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008027 case BO_And:
8028 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008029 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8030 GetExprRange(C, BO->getRHS(), MaxWidth));
8031
John McCall70aa5392010-01-06 05:24:50 +00008032 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008033 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008034 // ...except that we want to treat '1 << (blah)' as logically
8035 // positive. It's an important idiom.
8036 if (IntegerLiteral *I
8037 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8038 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008039 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008040 return IntRange(R.Width, /*NonNegative*/ true);
8041 }
8042 }
8043 // fallthrough
8044
John McCalle3027922010-08-25 11:45:40 +00008045 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008046 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008047
John McCall2ce81ad2010-01-06 22:07:33 +00008048 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008049 case BO_Shr:
8050 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008051 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8052
8053 // If the shift amount is a positive constant, drop the width by
8054 // that much.
8055 llvm::APSInt shift;
8056 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8057 shift.isNonNegative()) {
8058 unsigned zext = shift.getZExtValue();
8059 if (zext >= L.Width)
8060 L.Width = (L.NonNegative ? 0 : 1);
8061 else
8062 L.Width -= zext;
8063 }
8064
8065 return L;
8066 }
8067
8068 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008069 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008070 return GetExprRange(C, BO->getRHS(), MaxWidth);
8071
John McCall2ce81ad2010-01-06 22:07:33 +00008072 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008073 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008074 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008075 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008076 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008077
John McCall51431812011-07-14 22:39:48 +00008078 // The width of a division result is mostly determined by the size
8079 // of the LHS.
8080 case BO_Div: {
8081 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008082 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008083 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8084
8085 // If the divisor is constant, use that.
8086 llvm::APSInt divisor;
8087 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8088 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8089 if (log2 >= L.Width)
8090 L.Width = (L.NonNegative ? 0 : 1);
8091 else
8092 L.Width = std::min(L.Width - log2, MaxWidth);
8093 return L;
8094 }
8095
8096 // Otherwise, just use the LHS's width.
8097 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8098 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8099 }
8100
8101 // The result of a remainder can't be larger than the result of
8102 // either side.
8103 case BO_Rem: {
8104 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008105 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008106 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8107 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8108
8109 IntRange meet = IntRange::meet(L, R);
8110 meet.Width = std::min(meet.Width, MaxWidth);
8111 return meet;
8112 }
8113
8114 // The default behavior is okay for these.
8115 case BO_Mul:
8116 case BO_Add:
8117 case BO_Xor:
8118 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008119 break;
8120 }
8121
John McCall51431812011-07-14 22:39:48 +00008122 // The default case is to treat the operation as if it were closed
8123 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008124 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8125 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8126 return IntRange::join(L, R);
8127 }
8128
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008129 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008130 switch (UO->getOpcode()) {
8131 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008132 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008133 return IntRange::forBoolType();
8134
8135 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008136 case UO_Deref:
8137 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008138 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008139
8140 default:
8141 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8142 }
8143 }
8144
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008145 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008146 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8147
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008148 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008149 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008150 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008151
Eli Friedmane6d33952013-07-08 20:20:06 +00008152 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008153}
John McCall263a48b2010-01-04 23:31:57 +00008154
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008155IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008156 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008157}
8158
John McCall263a48b2010-01-04 23:31:57 +00008159/// Checks whether the given value, which currently has the given
8160/// source semantics, has the same value when coerced through the
8161/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008162bool IsSameFloatAfterCast(const llvm::APFloat &value,
8163 const llvm::fltSemantics &Src,
8164 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008165 llvm::APFloat truncated = value;
8166
8167 bool ignored;
8168 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8169 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8170
8171 return truncated.bitwiseIsEqual(value);
8172}
8173
8174/// Checks whether the given value, which currently has the given
8175/// source semantics, has the same value when coerced through the
8176/// target semantics.
8177///
8178/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008179bool IsSameFloatAfterCast(const APValue &value,
8180 const llvm::fltSemantics &Src,
8181 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008182 if (value.isFloat())
8183 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8184
8185 if (value.isVector()) {
8186 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8187 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8188 return false;
8189 return true;
8190 }
8191
8192 assert(value.isComplexFloat());
8193 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8194 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8195}
8196
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008197void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008198
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008199bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008200 // Suppress cases where we are comparing against an enum constant.
8201 if (const DeclRefExpr *DR =
8202 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8203 if (isa<EnumConstantDecl>(DR->getDecl()))
8204 return false;
8205
8206 // Suppress cases where the '0' value is expanded from a macro.
8207 if (E->getLocStart().isMacroID())
8208 return false;
8209
John McCallcc7e5bf2010-05-06 08:58:33 +00008210 llvm::APSInt Value;
8211 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8212}
8213
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008214bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008215 // Strip off implicit integral promotions.
8216 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008217 if (ICE->getCastKind() != CK_IntegralCast &&
8218 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008219 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008220 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008221 }
8222
8223 return E->getType()->isEnumeralType();
8224}
8225
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008226void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008227 // Disable warning in template instantiations.
8228 if (!S.ActiveTemplateInstantiations.empty())
8229 return;
8230
John McCalle3027922010-08-25 11:45:40 +00008231 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008232 if (E->isValueDependent())
8233 return;
8234
John McCalle3027922010-08-25 11:45:40 +00008235 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008236 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008237 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008238 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008239 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008240 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008241 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008242 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008243 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008244 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008245 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008246 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008247 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008248 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008249 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008250 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8251 }
8252}
8253
Benjamin Kramer7320b992016-06-15 14:20:56 +00008254void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8255 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008256 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008257 // Disable warning in template instantiations.
8258 if (!S.ActiveTemplateInstantiations.empty())
8259 return;
8260
Richard Trieu0f097742014-04-04 04:13:47 +00008261 // TODO: Investigate using GetExprRange() to get tighter bounds
8262 // on the bit ranges.
8263 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008264 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008265 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008266 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8267 unsigned OtherWidth = OtherRange.Width;
8268
8269 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8270
Richard Trieu560910c2012-11-14 22:50:24 +00008271 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008272 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008273 return;
8274
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008275 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008276 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008277
Richard Trieu0f097742014-04-04 04:13:47 +00008278 // Used for diagnostic printout.
8279 enum {
8280 LiteralConstant = 0,
8281 CXXBoolLiteralTrue,
8282 CXXBoolLiteralFalse
8283 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008284
Richard Trieu0f097742014-04-04 04:13:47 +00008285 if (!OtherIsBooleanType) {
8286 QualType ConstantT = Constant->getType();
8287 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008288
Richard Trieu0f097742014-04-04 04:13:47 +00008289 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8290 return;
8291 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8292 "comparison with non-integer type");
8293
8294 bool ConstantSigned = ConstantT->isSignedIntegerType();
8295 bool CommonSigned = CommonT->isSignedIntegerType();
8296
8297 bool EqualityOnly = false;
8298
8299 if (CommonSigned) {
8300 // The common type is signed, therefore no signed to unsigned conversion.
8301 if (!OtherRange.NonNegative) {
8302 // Check that the constant is representable in type OtherT.
8303 if (ConstantSigned) {
8304 if (OtherWidth >= Value.getMinSignedBits())
8305 return;
8306 } else { // !ConstantSigned
8307 if (OtherWidth >= Value.getActiveBits() + 1)
8308 return;
8309 }
8310 } else { // !OtherSigned
8311 // Check that the constant is representable in type OtherT.
8312 // Negative values are out of range.
8313 if (ConstantSigned) {
8314 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8315 return;
8316 } else { // !ConstantSigned
8317 if (OtherWidth >= Value.getActiveBits())
8318 return;
8319 }
Richard Trieu560910c2012-11-14 22:50:24 +00008320 }
Richard Trieu0f097742014-04-04 04:13:47 +00008321 } else { // !CommonSigned
8322 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008323 if (OtherWidth >= Value.getActiveBits())
8324 return;
Craig Toppercf360162014-06-18 05:13:11 +00008325 } else { // OtherSigned
8326 assert(!ConstantSigned &&
8327 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008328 // Check to see if the constant is representable in OtherT.
8329 if (OtherWidth > Value.getActiveBits())
8330 return;
8331 // Check to see if the constant is equivalent to a negative value
8332 // cast to CommonT.
8333 if (S.Context.getIntWidth(ConstantT) ==
8334 S.Context.getIntWidth(CommonT) &&
8335 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8336 return;
8337 // The constant value rests between values that OtherT can represent
8338 // after conversion. Relational comparison still works, but equality
8339 // comparisons will be tautological.
8340 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008341 }
8342 }
Richard Trieu0f097742014-04-04 04:13:47 +00008343
8344 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8345
8346 if (op == BO_EQ || op == BO_NE) {
8347 IsTrue = op == BO_NE;
8348 } else if (EqualityOnly) {
8349 return;
8350 } else if (RhsConstant) {
8351 if (op == BO_GT || op == BO_GE)
8352 IsTrue = !PositiveConstant;
8353 else // op == BO_LT || op == BO_LE
8354 IsTrue = PositiveConstant;
8355 } else {
8356 if (op == BO_LT || op == BO_LE)
8357 IsTrue = !PositiveConstant;
8358 else // op == BO_GT || op == BO_GE
8359 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008360 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008361 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008362 // Other isKnownToHaveBooleanValue
8363 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8364 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8365 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8366
8367 static const struct LinkedConditions {
8368 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8369 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8370 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8371 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8372 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8373 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8374
8375 } TruthTable = {
8376 // Constant on LHS. | Constant on RHS. |
8377 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8378 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8379 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8380 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8381 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8382 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8383 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8384 };
8385
8386 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8387
8388 enum ConstantValue ConstVal = Zero;
8389 if (Value.isUnsigned() || Value.isNonNegative()) {
8390 if (Value == 0) {
8391 LiteralOrBoolConstant =
8392 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8393 ConstVal = Zero;
8394 } else if (Value == 1) {
8395 LiteralOrBoolConstant =
8396 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8397 ConstVal = One;
8398 } else {
8399 LiteralOrBoolConstant = LiteralConstant;
8400 ConstVal = GT_One;
8401 }
8402 } else {
8403 ConstVal = LT_Zero;
8404 }
8405
8406 CompareBoolWithConstantResult CmpRes;
8407
8408 switch (op) {
8409 case BO_LT:
8410 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8411 break;
8412 case BO_GT:
8413 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8414 break;
8415 case BO_LE:
8416 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8417 break;
8418 case BO_GE:
8419 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8420 break;
8421 case BO_EQ:
8422 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8423 break;
8424 case BO_NE:
8425 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8426 break;
8427 default:
8428 CmpRes = Unkwn;
8429 break;
8430 }
8431
8432 if (CmpRes == AFals) {
8433 IsTrue = false;
8434 } else if (CmpRes == ATrue) {
8435 IsTrue = true;
8436 } else {
8437 return;
8438 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008439 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008440
8441 // If this is a comparison to an enum constant, include that
8442 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008443 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008444 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8445 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8446
8447 SmallString<64> PrettySourceValue;
8448 llvm::raw_svector_ostream OS(PrettySourceValue);
8449 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008450 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008451 else
8452 OS << Value;
8453
Richard Trieu0f097742014-04-04 04:13:47 +00008454 S.DiagRuntimeBehavior(
8455 E->getOperatorLoc(), E,
8456 S.PDiag(diag::warn_out_of_range_compare)
8457 << OS.str() << LiteralOrBoolConstant
8458 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8459 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008460}
8461
John McCallcc7e5bf2010-05-06 08:58:33 +00008462/// Analyze the operands of the given comparison. Implements the
8463/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008464void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008465 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8466 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008467}
John McCall263a48b2010-01-04 23:31:57 +00008468
John McCallca01b222010-01-04 23:21:16 +00008469/// \brief Implements -Wsign-compare.
8470///
Richard Trieu82402a02011-09-15 21:56:47 +00008471/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008472void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008473 // The type the comparison is being performed in.
8474 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008475
8476 // Only analyze comparison operators where both sides have been converted to
8477 // the same type.
8478 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8479 return AnalyzeImpConvsInComparison(S, E);
8480
8481 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008482 if (E->isValueDependent())
8483 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008484
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008485 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8486 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008487
8488 bool IsComparisonConstant = false;
8489
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008490 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008491 // of 'true' or 'false'.
8492 if (T->isIntegralType(S.Context)) {
8493 llvm::APSInt RHSValue;
8494 bool IsRHSIntegralLiteral =
8495 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8496 llvm::APSInt LHSValue;
8497 bool IsLHSIntegralLiteral =
8498 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8499 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8500 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8501 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8502 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8503 else
8504 IsComparisonConstant =
8505 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008506 } else if (!T->hasUnsignedIntegerRepresentation())
8507 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008508
John McCallcc7e5bf2010-05-06 08:58:33 +00008509 // We don't do anything special if this isn't an unsigned integral
8510 // comparison: we're only interested in integral comparisons, and
8511 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008512 //
8513 // We also don't care about value-dependent expressions or expressions
8514 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008515 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008516 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008517
John McCallcc7e5bf2010-05-06 08:58:33 +00008518 // Check to see if one of the (unmodified) operands is of different
8519 // signedness.
8520 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008521 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8522 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008523 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008524 signedOperand = LHS;
8525 unsignedOperand = RHS;
8526 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8527 signedOperand = RHS;
8528 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008529 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008530 CheckTrivialUnsignedComparison(S, E);
8531 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008532 }
8533
John McCallcc7e5bf2010-05-06 08:58:33 +00008534 // Otherwise, calculate the effective range of the signed operand.
8535 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008536
John McCallcc7e5bf2010-05-06 08:58:33 +00008537 // Go ahead and analyze implicit conversions in the operands. Note
8538 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008539 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8540 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008541
John McCallcc7e5bf2010-05-06 08:58:33 +00008542 // If the signed range is non-negative, -Wsign-compare won't fire,
8543 // but we should still check for comparisons which are always true
8544 // or false.
8545 if (signedRange.NonNegative)
8546 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008547
8548 // For (in)equality comparisons, if the unsigned operand is a
8549 // constant which cannot collide with a overflowed signed operand,
8550 // then reinterpreting the signed operand as unsigned will not
8551 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008552 if (E->isEqualityOp()) {
8553 unsigned comparisonWidth = S.Context.getIntWidth(T);
8554 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008555
John McCallcc7e5bf2010-05-06 08:58:33 +00008556 // We should never be unable to prove that the unsigned operand is
8557 // non-negative.
8558 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8559
8560 if (unsignedRange.Width < comparisonWidth)
8561 return;
8562 }
8563
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008564 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8565 S.PDiag(diag::warn_mixed_sign_comparison)
8566 << LHS->getType() << RHS->getType()
8567 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008568}
8569
John McCall1f425642010-11-11 03:21:53 +00008570/// Analyzes an attempt to assign the given value to a bitfield.
8571///
8572/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008573bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8574 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008575 assert(Bitfield->isBitField());
8576 if (Bitfield->isInvalidDecl())
8577 return false;
8578
John McCalldeebbcf2010-11-11 05:33:51 +00008579 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008580 QualType BitfieldType = Bitfield->getType();
8581 if (BitfieldType->isBooleanType())
8582 return false;
8583
8584 if (BitfieldType->isEnumeralType()) {
8585 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8586 // If the underlying enum type was not explicitly specified as an unsigned
8587 // type and the enum contain only positive values, MSVC++ will cause an
8588 // inconsistency by storing this as a signed type.
8589 if (S.getLangOpts().CPlusPlus11 &&
8590 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8591 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8592 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8593 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8594 << BitfieldEnumDecl->getNameAsString();
8595 }
8596 }
8597
John McCalldeebbcf2010-11-11 05:33:51 +00008598 if (Bitfield->getType()->isBooleanType())
8599 return false;
8600
Douglas Gregor789adec2011-02-04 13:09:01 +00008601 // Ignore value- or type-dependent expressions.
8602 if (Bitfield->getBitWidth()->isValueDependent() ||
8603 Bitfield->getBitWidth()->isTypeDependent() ||
8604 Init->isValueDependent() ||
8605 Init->isTypeDependent())
8606 return false;
8607
John McCall1f425642010-11-11 03:21:53 +00008608 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8609
Richard Smith5fab0c92011-12-28 19:48:30 +00008610 llvm::APSInt Value;
8611 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008612 return false;
8613
John McCall1f425642010-11-11 03:21:53 +00008614 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008615 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008616
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008617 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008618 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008619 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8620 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008621
John McCall1f425642010-11-11 03:21:53 +00008622 if (OriginalWidth <= FieldWidth)
8623 return false;
8624
Eli Friedmanc267a322012-01-26 23:11:39 +00008625 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008626 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008627 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008628
Eli Friedmanc267a322012-01-26 23:11:39 +00008629 // Check whether the stored value is equal to the original value.
8630 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008631 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008632 return false;
8633
Eli Friedmanc267a322012-01-26 23:11:39 +00008634 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008635 // therefore don't strictly fit into a signed bitfield of width 1.
8636 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008637 return false;
8638
John McCall1f425642010-11-11 03:21:53 +00008639 std::string PrettyValue = Value.toString(10);
8640 std::string PrettyTrunc = TruncatedValue.toString(10);
8641
8642 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8643 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8644 << Init->getSourceRange();
8645
8646 return true;
8647}
8648
John McCalld2a53122010-11-09 23:24:47 +00008649/// Analyze the given simple or compound assignment for warning-worthy
8650/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008651void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008652 // Just recurse on the LHS.
8653 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8654
8655 // We want to recurse on the RHS as normal unless we're assigning to
8656 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008657 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008658 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008659 E->getOperatorLoc())) {
8660 // Recurse, ignoring any implicit conversions on the RHS.
8661 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8662 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008663 }
8664 }
8665
8666 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8667}
8668
John McCall263a48b2010-01-04 23:31:57 +00008669/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008670void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8671 SourceLocation CContext, unsigned diag,
8672 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008673 if (pruneControlFlow) {
8674 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8675 S.PDiag(diag)
8676 << SourceType << T << E->getSourceRange()
8677 << SourceRange(CContext));
8678 return;
8679 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008680 S.Diag(E->getExprLoc(), diag)
8681 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8682}
8683
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008684/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008685void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8686 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008687 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008688}
8689
Richard Trieube234c32016-04-21 21:04:55 +00008690
8691/// Diagnose an implicit cast from a floating point value to an integer value.
8692void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8693
8694 SourceLocation CContext) {
8695 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8696 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8697
8698 Expr *InnerE = E->IgnoreParenImpCasts();
8699 // We also want to warn on, e.g., "int i = -1.234"
8700 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8701 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8702 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8703
8704 const bool IsLiteral =
8705 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8706
8707 llvm::APFloat Value(0.0);
8708 bool IsConstant =
8709 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8710 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008711 return DiagnoseImpCast(S, E, T, CContext,
8712 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008713 }
8714
Chandler Carruth016ef402011-04-10 08:36:24 +00008715 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008716
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008717 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8718 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008719 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8720 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008721 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008722 if (IsLiteral) return;
8723 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8724 PruneWarnings);
8725 }
8726
8727 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008728 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008729 // Warn on floating point literal to integer.
8730 DiagID = diag::warn_impcast_literal_float_to_integer;
8731 } else if (IntegerValue == 0) {
8732 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8733 return DiagnoseImpCast(S, E, T, CContext,
8734 diag::warn_impcast_float_integer, PruneWarnings);
8735 }
8736 // Warn on non-zero to zero conversion.
8737 DiagID = diag::warn_impcast_float_to_integer_zero;
8738 } else {
8739 if (IntegerValue.isUnsigned()) {
8740 if (!IntegerValue.isMaxValue()) {
8741 return DiagnoseImpCast(S, E, T, CContext,
8742 diag::warn_impcast_float_integer, PruneWarnings);
8743 }
8744 } else { // IntegerValue.isSigned()
8745 if (!IntegerValue.isMaxSignedValue() &&
8746 !IntegerValue.isMinSignedValue()) {
8747 return DiagnoseImpCast(S, E, T, CContext,
8748 diag::warn_impcast_float_integer, PruneWarnings);
8749 }
8750 }
8751 // Warn on evaluatable floating point expression to integer conversion.
8752 DiagID = diag::warn_impcast_float_to_integer;
8753 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008754
Eli Friedman07185912013-08-29 23:44:43 +00008755 // FIXME: Force the precision of the source value down so we don't print
8756 // digits which are usually useless (we don't really care here if we
8757 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8758 // would automatically print the shortest representation, but it's a bit
8759 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008760 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008761 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8762 precision = (precision * 59 + 195) / 196;
8763 Value.toString(PrettySourceValue, precision);
8764
David Blaikie9b88cc02012-05-15 17:18:27 +00008765 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008766 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008767 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008768 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008769 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008770
Richard Trieube234c32016-04-21 21:04:55 +00008771 if (PruneWarnings) {
8772 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8773 S.PDiag(DiagID)
8774 << E->getType() << T.getUnqualifiedType()
8775 << PrettySourceValue << PrettyTargetValue
8776 << E->getSourceRange() << SourceRange(CContext));
8777 } else {
8778 S.Diag(E->getExprLoc(), DiagID)
8779 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8780 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8781 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008782}
8783
John McCall18a2c2c2010-11-09 22:22:12 +00008784std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8785 if (!Range.Width) return "0";
8786
8787 llvm::APSInt ValueInRange = Value;
8788 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008789 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008790 return ValueInRange.toString(10);
8791}
8792
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008793bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008794 if (!isa<ImplicitCastExpr>(Ex))
8795 return false;
8796
8797 Expr *InnerE = Ex->IgnoreParenImpCasts();
8798 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8799 const Type *Source =
8800 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8801 if (Target->isDependentType())
8802 return false;
8803
8804 const BuiltinType *FloatCandidateBT =
8805 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8806 const Type *BoolCandidateType = ToBool ? Target : Source;
8807
8808 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8809 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8810}
8811
8812void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8813 SourceLocation CC) {
8814 unsigned NumArgs = TheCall->getNumArgs();
8815 for (unsigned i = 0; i < NumArgs; ++i) {
8816 Expr *CurrA = TheCall->getArg(i);
8817 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8818 continue;
8819
8820 bool IsSwapped = ((i > 0) &&
8821 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8822 IsSwapped |= ((i < (NumArgs - 1)) &&
8823 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8824 if (IsSwapped) {
8825 // Warn on this floating-point to bool conversion.
8826 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8827 CurrA->getType(), CC,
8828 diag::warn_impcast_floating_point_to_bool);
8829 }
8830 }
8831}
8832
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008833void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008834 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8835 E->getExprLoc()))
8836 return;
8837
Richard Trieu09d6b802016-01-08 23:35:06 +00008838 // Don't warn on functions which have return type nullptr_t.
8839 if (isa<CallExpr>(E))
8840 return;
8841
Richard Trieu5b993502014-10-15 03:42:06 +00008842 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8843 const Expr::NullPointerConstantKind NullKind =
8844 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8845 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8846 return;
8847
8848 // Return if target type is a safe conversion.
8849 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8850 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8851 return;
8852
8853 SourceLocation Loc = E->getSourceRange().getBegin();
8854
Richard Trieu0a5e1662016-02-13 00:58:53 +00008855 // Venture through the macro stacks to get to the source of macro arguments.
8856 // The new location is a better location than the complete location that was
8857 // passed in.
8858 while (S.SourceMgr.isMacroArgExpansion(Loc))
8859 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8860
8861 while (S.SourceMgr.isMacroArgExpansion(CC))
8862 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8863
Richard Trieu5b993502014-10-15 03:42:06 +00008864 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008865 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8866 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8867 Loc, S.SourceMgr, S.getLangOpts());
8868 if (MacroName == "NULL")
8869 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008870 }
8871
8872 // Only warn if the null and context location are in the same macro expansion.
8873 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8874 return;
8875
8876 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8877 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8878 << FixItHint::CreateReplacement(Loc,
8879 S.getFixItZeroLiteralForType(T, Loc));
8880}
8881
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008882void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8883 ObjCArrayLiteral *ArrayLiteral);
8884void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8885 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008886
8887/// Check a single element within a collection literal against the
8888/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008889void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8890 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008891 // Skip a bitcast to 'id' or qualified 'id'.
8892 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8893 if (ICE->getCastKind() == CK_BitCast &&
8894 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8895 Element = ICE->getSubExpr();
8896 }
8897
8898 QualType ElementType = Element->getType();
8899 ExprResult ElementResult(Element);
8900 if (ElementType->getAs<ObjCObjectPointerType>() &&
8901 S.CheckSingleAssignmentConstraints(TargetElementType,
8902 ElementResult,
8903 false, false)
8904 != Sema::Compatible) {
8905 S.Diag(Element->getLocStart(),
8906 diag::warn_objc_collection_literal_element)
8907 << ElementType << ElementKind << TargetElementType
8908 << Element->getSourceRange();
8909 }
8910
8911 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8912 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8913 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8914 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8915}
8916
8917/// Check an Objective-C array literal being converted to the given
8918/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008919void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8920 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008921 if (!S.NSArrayDecl)
8922 return;
8923
8924 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8925 if (!TargetObjCPtr)
8926 return;
8927
8928 if (TargetObjCPtr->isUnspecialized() ||
8929 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8930 != S.NSArrayDecl->getCanonicalDecl())
8931 return;
8932
8933 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8934 if (TypeArgs.size() != 1)
8935 return;
8936
8937 QualType TargetElementType = TypeArgs[0];
8938 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8939 checkObjCCollectionLiteralElement(S, TargetElementType,
8940 ArrayLiteral->getElement(I),
8941 0);
8942 }
8943}
8944
8945/// Check an Objective-C dictionary literal being converted to the given
8946/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008947void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8948 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008949 if (!S.NSDictionaryDecl)
8950 return;
8951
8952 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8953 if (!TargetObjCPtr)
8954 return;
8955
8956 if (TargetObjCPtr->isUnspecialized() ||
8957 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8958 != S.NSDictionaryDecl->getCanonicalDecl())
8959 return;
8960
8961 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8962 if (TypeArgs.size() != 2)
8963 return;
8964
8965 QualType TargetKeyType = TypeArgs[0];
8966 QualType TargetObjectType = TypeArgs[1];
8967 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8968 auto Element = DictionaryLiteral->getKeyValueElement(I);
8969 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8970 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8971 }
8972}
8973
Richard Trieufc404c72016-02-05 23:02:38 +00008974// Helper function to filter out cases for constant width constant conversion.
8975// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008976bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8977 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008978 // If initializing from a constant, and the constant starts with '0',
8979 // then it is a binary, octal, or hexadecimal. Allow these constants
8980 // to fill all the bits, even if there is a sign change.
8981 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8982 const char FirstLiteralCharacter =
8983 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8984 if (FirstLiteralCharacter == '0')
8985 return false;
8986 }
8987
8988 // If the CC location points to a '{', and the type is char, then assume
8989 // assume it is an array initialization.
8990 if (CC.isValid() && T->isCharType()) {
8991 const char FirstContextCharacter =
8992 S.getSourceManager().getCharacterData(CC)[0];
8993 if (FirstContextCharacter == '{')
8994 return false;
8995 }
8996
8997 return true;
8998}
8999
John McCallcc7e5bf2010-05-06 08:58:33 +00009000void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009001 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009002 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009003
John McCallcc7e5bf2010-05-06 08:58:33 +00009004 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9005 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9006 if (Source == Target) return;
9007 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009008
Chandler Carruthc22845a2011-07-26 05:40:03 +00009009 // If the conversion context location is invalid don't complain. We also
9010 // don't want to emit a warning if the issue occurs from the expansion of
9011 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9012 // delay this check as long as possible. Once we detect we are in that
9013 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009014 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009015 return;
9016
Richard Trieu021baa32011-09-23 20:10:00 +00009017 // Diagnose implicit casts to bool.
9018 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9019 if (isa<StringLiteral>(E))
9020 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009021 // and expressions, for instance, assert(0 && "error here"), are
9022 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009023 return DiagnoseImpCast(S, E, T, CC,
9024 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009025 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9026 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9027 // This covers the literal expressions that evaluate to Objective-C
9028 // objects.
9029 return DiagnoseImpCast(S, E, T, CC,
9030 diag::warn_impcast_objective_c_literal_to_bool);
9031 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009032 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9033 // Warn on pointer to bool conversion that is always true.
9034 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9035 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009036 }
Richard Trieu021baa32011-09-23 20:10:00 +00009037 }
John McCall263a48b2010-01-04 23:31:57 +00009038
Douglas Gregor5054cb02015-07-07 03:58:22 +00009039 // Check implicit casts from Objective-C collection literals to specialized
9040 // collection types, e.g., NSArray<NSString *> *.
9041 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9042 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9043 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9044 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9045
John McCall263a48b2010-01-04 23:31:57 +00009046 // Strip vector types.
9047 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009048 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009049 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009050 return;
John McCallacf0ee52010-10-08 02:01:28 +00009051 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009052 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009053
9054 // If the vector cast is cast between two vectors of the same size, it is
9055 // a bitcast, not a conversion.
9056 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9057 return;
John McCall263a48b2010-01-04 23:31:57 +00009058
9059 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9060 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9061 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009062 if (auto VecTy = dyn_cast<VectorType>(Target))
9063 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009064
9065 // Strip complex types.
9066 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009067 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009068 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009069 return;
9070
John McCallacf0ee52010-10-08 02:01:28 +00009071 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009072 }
John McCall263a48b2010-01-04 23:31:57 +00009073
9074 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9075 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9076 }
9077
9078 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9079 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9080
9081 // If the source is floating point...
9082 if (SourceBT && SourceBT->isFloatingPoint()) {
9083 // ...and the target is floating point...
9084 if (TargetBT && TargetBT->isFloatingPoint()) {
9085 // ...then warn if we're dropping FP rank.
9086
9087 // Builtin FP kinds are ordered by increasing FP rank.
9088 if (SourceBT->getKind() > TargetBT->getKind()) {
9089 // Don't warn about float constants that are precisely
9090 // representable in the target type.
9091 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009092 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009093 // Value might be a float, a float vector, or a float complex.
9094 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009095 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9096 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009097 return;
9098 }
9099
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009100 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009101 return;
9102
John McCallacf0ee52010-10-08 02:01:28 +00009103 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009104 }
9105 // ... or possibly if we're increasing rank, too
9106 else if (TargetBT->getKind() > SourceBT->getKind()) {
9107 if (S.SourceMgr.isInSystemMacro(CC))
9108 return;
9109
9110 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009111 }
9112 return;
9113 }
9114
Richard Trieube234c32016-04-21 21:04:55 +00009115 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009116 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009117 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009118 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009119
Richard Trieube234c32016-04-21 21:04:55 +00009120 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009121 }
John McCall263a48b2010-01-04 23:31:57 +00009122
Richard Smith54894fd2015-12-30 01:06:52 +00009123 // Detect the case where a call result is converted from floating-point to
9124 // to bool, and the final argument to the call is converted from bool, to
9125 // discover this typo:
9126 //
9127 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9128 //
9129 // FIXME: This is an incredibly special case; is there some more general
9130 // way to detect this class of misplaced-parentheses bug?
9131 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009132 // Check last argument of function call to see if it is an
9133 // implicit cast from a type matching the type the result
9134 // is being cast to.
9135 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009136 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009137 Expr *LastA = CEx->getArg(NumArgs - 1);
9138 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009139 if (isa<ImplicitCastExpr>(LastA) &&
9140 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009141 // Warn on this floating-point to bool conversion
9142 DiagnoseImpCast(S, E, T, CC,
9143 diag::warn_impcast_floating_point_to_bool);
9144 }
9145 }
9146 }
John McCall263a48b2010-01-04 23:31:57 +00009147 return;
9148 }
9149
Richard Trieu5b993502014-10-15 03:42:06 +00009150 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009151
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009152 S.DiscardMisalignedMemberAddress(Target, E);
9153
David Blaikie9366d2b2012-06-19 21:19:06 +00009154 if (!Source->isIntegerType() || !Target->isIntegerType())
9155 return;
9156
David Blaikie7555b6a2012-05-15 16:56:36 +00009157 // TODO: remove this early return once the false positives for constant->bool
9158 // in templates, macros, etc, are reduced or removed.
9159 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9160 return;
9161
John McCallcc7e5bf2010-05-06 08:58:33 +00009162 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009163 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009164
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009165 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009166 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009167 // TODO: this should happen for bitfield stores, too.
9168 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009169 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009170 if (S.SourceMgr.isInSystemMacro(CC))
9171 return;
9172
John McCall18a2c2c2010-11-09 22:22:12 +00009173 std::string PrettySourceValue = Value.toString(10);
9174 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009175
Ted Kremenek33ba9952011-10-22 02:37:33 +00009176 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9177 S.PDiag(diag::warn_impcast_integer_precision_constant)
9178 << PrettySourceValue << PrettyTargetValue
9179 << E->getType() << T << E->getSourceRange()
9180 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009181 return;
9182 }
9183
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009184 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9185 if (S.SourceMgr.isInSystemMacro(CC))
9186 return;
9187
David Blaikie9455da02012-04-12 22:40:54 +00009188 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009189 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9190 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009191 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009192 }
9193
Richard Trieudcb55572016-01-29 23:51:16 +00009194 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9195 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9196 // Warn when doing a signed to signed conversion, warn if the positive
9197 // source value is exactly the width of the target type, which will
9198 // cause a negative value to be stored.
9199
9200 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009201 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9202 !S.SourceMgr.isInSystemMacro(CC)) {
9203 if (isSameWidthConstantConversion(S, E, T, CC)) {
9204 std::string PrettySourceValue = Value.toString(10);
9205 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009206
Richard Trieufc404c72016-02-05 23:02:38 +00009207 S.DiagRuntimeBehavior(
9208 E->getExprLoc(), E,
9209 S.PDiag(diag::warn_impcast_integer_precision_constant)
9210 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9211 << E->getSourceRange() << clang::SourceRange(CC));
9212 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009213 }
9214 }
Richard Trieufc404c72016-02-05 23:02:38 +00009215
Richard Trieudcb55572016-01-29 23:51:16 +00009216 // Fall through for non-constants to give a sign conversion warning.
9217 }
9218
John McCallcc7e5bf2010-05-06 08:58:33 +00009219 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9220 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9221 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009222 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009223 return;
9224
John McCallcc7e5bf2010-05-06 08:58:33 +00009225 unsigned DiagID = diag::warn_impcast_integer_sign;
9226
9227 // Traditionally, gcc has warned about this under -Wsign-compare.
9228 // We also want to warn about it in -Wconversion.
9229 // So if -Wconversion is off, use a completely identical diagnostic
9230 // in the sign-compare group.
9231 // The conditional-checking code will
9232 if (ICContext) {
9233 DiagID = diag::warn_impcast_integer_sign_conditional;
9234 *ICContext = true;
9235 }
9236
John McCallacf0ee52010-10-08 02:01:28 +00009237 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009238 }
9239
Douglas Gregora78f1932011-02-22 02:45:07 +00009240 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009241 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9242 // type, to give us better diagnostics.
9243 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009244 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009245 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9246 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9247 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9248 SourceType = S.Context.getTypeDeclType(Enum);
9249 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9250 }
9251 }
9252
Douglas Gregora78f1932011-02-22 02:45:07 +00009253 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9254 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009255 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9256 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009257 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009258 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009259 return;
9260
Douglas Gregor364f7db2011-03-12 00:14:31 +00009261 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009262 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009263 }
John McCall263a48b2010-01-04 23:31:57 +00009264}
9265
David Blaikie18e9ac72012-05-15 21:57:38 +00009266void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9267 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009268
9269void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009270 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009271 E = E->IgnoreParenImpCasts();
9272
9273 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009274 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009275
John McCallacf0ee52010-10-08 02:01:28 +00009276 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009277 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009278 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009279}
9280
David Blaikie18e9ac72012-05-15 21:57:38 +00009281void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9282 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009283 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009284
9285 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009286 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9287 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009288
9289 // If -Wconversion would have warned about either of the candidates
9290 // for a signedness conversion to the context type...
9291 if (!Suspicious) return;
9292
9293 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009294 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009295 return;
9296
John McCallcc7e5bf2010-05-06 08:58:33 +00009297 // ...then check whether it would have warned about either of the
9298 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009299 if (E->getType() == T) return;
9300
9301 Suspicious = false;
9302 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9303 E->getType(), CC, &Suspicious);
9304 if (!Suspicious)
9305 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009306 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009307}
9308
Richard Trieu65724892014-11-15 06:37:39 +00009309/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9310/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009311void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009312 if (S.getLangOpts().Bool)
9313 return;
9314 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9315}
9316
John McCallcc7e5bf2010-05-06 08:58:33 +00009317/// AnalyzeImplicitConversions - Find and report any interesting
9318/// implicit conversions in the given expression. There are a couple
9319/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009320void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009321 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009322 Expr *E = OrigE->IgnoreParenImpCasts();
9323
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009324 if (E->isTypeDependent() || E->isValueDependent())
9325 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009326
John McCallcc7e5bf2010-05-06 08:58:33 +00009327 // For conditional operators, we analyze the arguments as if they
9328 // were being fed directly into the output.
9329 if (isa<ConditionalOperator>(E)) {
9330 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009331 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009332 return;
9333 }
9334
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009335 // Check implicit argument conversions for function calls.
9336 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9337 CheckImplicitArgumentConversions(S, Call, CC);
9338
John McCallcc7e5bf2010-05-06 08:58:33 +00009339 // Go ahead and check any implicit conversions we might have skipped.
9340 // The non-canonical typecheck is just an optimization;
9341 // CheckImplicitConversion will filter out dead implicit conversions.
9342 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009343 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009344
9345 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009346
9347 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9348 // The bound subexpressions in a PseudoObjectExpr are not reachable
9349 // as transitive children.
9350 // FIXME: Use a more uniform representation for this.
9351 for (auto *SE : POE->semantics())
9352 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9353 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009354 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009355
John McCallcc7e5bf2010-05-06 08:58:33 +00009356 // Skip past explicit casts.
9357 if (isa<ExplicitCastExpr>(E)) {
9358 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009359 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009360 }
9361
John McCalld2a53122010-11-09 23:24:47 +00009362 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9363 // Do a somewhat different check with comparison operators.
9364 if (BO->isComparisonOp())
9365 return AnalyzeComparison(S, BO);
9366
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009367 // And with simple assignments.
9368 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009369 return AnalyzeAssignment(S, BO);
9370 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009371
9372 // These break the otherwise-useful invariant below. Fortunately,
9373 // we don't really need to recurse into them, because any internal
9374 // expressions should have been analyzed already when they were
9375 // built into statements.
9376 if (isa<StmtExpr>(E)) return;
9377
9378 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009379 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009380
9381 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009382 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009383 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009384 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009385 for (Stmt *SubStmt : E->children()) {
9386 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009387 if (!ChildExpr)
9388 continue;
9389
Richard Trieu955231d2014-01-25 01:10:35 +00009390 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009391 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009392 // Ignore checking string literals that are in logical and operators.
9393 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009394 continue;
9395 AnalyzeImplicitConversions(S, ChildExpr, CC);
9396 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009397
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009398 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009399 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9400 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009401 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009402
9403 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9404 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009405 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009406 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009407
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009408 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9409 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009410 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009411}
9412
9413} // end anonymous namespace
9414
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009415/// Diagnose integer type and any valid implicit convertion to it.
9416static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9417 // Taking into account implicit conversions,
9418 // allow any integer.
9419 if (!E->getType()->isIntegerType()) {
9420 S.Diag(E->getLocStart(),
9421 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9422 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009423 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009424 // Potentially emit standard warnings for implicit conversions if enabled
9425 // using -Wconversion.
9426 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9427 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009428}
9429
Richard Trieuc1888e02014-06-28 23:25:37 +00009430// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9431// Returns true when emitting a warning about taking the address of a reference.
9432static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009433 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009434 E = E->IgnoreParenImpCasts();
9435
9436 const FunctionDecl *FD = nullptr;
9437
9438 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9439 if (!DRE->getDecl()->getType()->isReferenceType())
9440 return false;
9441 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9442 if (!M->getMemberDecl()->getType()->isReferenceType())
9443 return false;
9444 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009445 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009446 return false;
9447 FD = Call->getDirectCallee();
9448 } else {
9449 return false;
9450 }
9451
9452 SemaRef.Diag(E->getExprLoc(), PD);
9453
9454 // If possible, point to location of function.
9455 if (FD) {
9456 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9457 }
9458
9459 return true;
9460}
9461
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009462// Returns true if the SourceLocation is expanded from any macro body.
9463// Returns false if the SourceLocation is invalid, is from not in a macro
9464// expansion, or is from expanded from a top-level macro argument.
9465static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9466 if (Loc.isInvalid())
9467 return false;
9468
9469 while (Loc.isMacroID()) {
9470 if (SM.isMacroBodyExpansion(Loc))
9471 return true;
9472 Loc = SM.getImmediateMacroCallerLoc(Loc);
9473 }
9474
9475 return false;
9476}
9477
Richard Trieu3bb8b562014-02-26 02:36:06 +00009478/// \brief Diagnose pointers that are always non-null.
9479/// \param E the expression containing the pointer
9480/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9481/// compared to a null pointer
9482/// \param IsEqual True when the comparison is equal to a null pointer
9483/// \param Range Extra SourceRange to highlight in the diagnostic
9484void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9485 Expr::NullPointerConstantKind NullKind,
9486 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009487 if (!E)
9488 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009489
9490 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009491 if (E->getExprLoc().isMacroID()) {
9492 const SourceManager &SM = getSourceManager();
9493 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9494 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009495 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009496 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009497 E = E->IgnoreImpCasts();
9498
9499 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9500
Richard Trieuf7432752014-06-06 21:39:26 +00009501 if (isa<CXXThisExpr>(E)) {
9502 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9503 : diag::warn_this_bool_conversion;
9504 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9505 return;
9506 }
9507
Richard Trieu3bb8b562014-02-26 02:36:06 +00009508 bool IsAddressOf = false;
9509
9510 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9511 if (UO->getOpcode() != UO_AddrOf)
9512 return;
9513 IsAddressOf = true;
9514 E = UO->getSubExpr();
9515 }
9516
Richard Trieuc1888e02014-06-28 23:25:37 +00009517 if (IsAddressOf) {
9518 unsigned DiagID = IsCompare
9519 ? diag::warn_address_of_reference_null_compare
9520 : diag::warn_address_of_reference_bool_conversion;
9521 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9522 << IsEqual;
9523 if (CheckForReference(*this, E, PD)) {
9524 return;
9525 }
9526 }
9527
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009528 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9529 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009530 std::string Str;
9531 llvm::raw_string_ostream S(Str);
9532 E->printPretty(S, nullptr, getPrintingPolicy());
9533 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9534 : diag::warn_cast_nonnull_to_bool;
9535 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9536 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009537 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009538 };
9539
9540 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9541 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9542 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009543 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9544 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009545 return;
9546 }
9547 }
9548 }
9549
Richard Trieu3bb8b562014-02-26 02:36:06 +00009550 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009551 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009552 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9553 D = R->getDecl();
9554 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9555 D = M->getMemberDecl();
9556 }
9557
9558 // Weak Decls can be null.
9559 if (!D || D->isWeak())
9560 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009561
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009562 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009563 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9564 if (getCurFunction() &&
9565 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009566 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9567 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009568 return;
9569 }
9570
9571 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009572 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009573 assert(ParamIter != FD->param_end());
9574 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9575
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009576 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9577 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009578 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009579 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009580 }
George Burgess IV850269a2015-12-08 22:02:00 +00009581
9582 for (unsigned ArgNo : NonNull->args()) {
9583 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009584 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009585 return;
9586 }
George Burgess IV850269a2015-12-08 22:02:00 +00009587 }
9588 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009589 }
9590 }
George Burgess IV850269a2015-12-08 22:02:00 +00009591 }
9592
Richard Trieu3bb8b562014-02-26 02:36:06 +00009593 QualType T = D->getType();
9594 const bool IsArray = T->isArrayType();
9595 const bool IsFunction = T->isFunctionType();
9596
Richard Trieuc1888e02014-06-28 23:25:37 +00009597 // Address of function is used to silence the function warning.
9598 if (IsAddressOf && IsFunction) {
9599 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009600 }
9601
9602 // Found nothing.
9603 if (!IsAddressOf && !IsFunction && !IsArray)
9604 return;
9605
9606 // Pretty print the expression for the diagnostic.
9607 std::string Str;
9608 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009609 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009610
9611 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9612 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009613 enum {
9614 AddressOf,
9615 FunctionPointer,
9616 ArrayPointer
9617 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009618 if (IsAddressOf)
9619 DiagType = AddressOf;
9620 else if (IsFunction)
9621 DiagType = FunctionPointer;
9622 else if (IsArray)
9623 DiagType = ArrayPointer;
9624 else
9625 llvm_unreachable("Could not determine diagnostic.");
9626 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9627 << Range << IsEqual;
9628
9629 if (!IsFunction)
9630 return;
9631
9632 // Suggest '&' to silence the function warning.
9633 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9634 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9635
9636 // Check to see if '()' fixit should be emitted.
9637 QualType ReturnType;
9638 UnresolvedSet<4> NonTemplateOverloads;
9639 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9640 if (ReturnType.isNull())
9641 return;
9642
9643 if (IsCompare) {
9644 // There are two cases here. If there is null constant, the only suggest
9645 // for a pointer return type. If the null is 0, then suggest if the return
9646 // type is a pointer or an integer type.
9647 if (!ReturnType->isPointerType()) {
9648 if (NullKind == Expr::NPCK_ZeroExpression ||
9649 NullKind == Expr::NPCK_ZeroLiteral) {
9650 if (!ReturnType->isIntegerType())
9651 return;
9652 } else {
9653 return;
9654 }
9655 }
9656 } else { // !IsCompare
9657 // For function to bool, only suggest if the function pointer has bool
9658 // return type.
9659 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9660 return;
9661 }
9662 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009663 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009664}
9665
John McCallcc7e5bf2010-05-06 08:58:33 +00009666/// Diagnoses "dangerous" implicit conversions within the given
9667/// expression (which is a full expression). Implements -Wconversion
9668/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009669///
9670/// \param CC the "context" location of the implicit conversion, i.e.
9671/// the most location of the syntactic entity requiring the implicit
9672/// conversion
9673void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009674 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009675 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009676 return;
9677
9678 // Don't diagnose for value- or type-dependent expressions.
9679 if (E->isTypeDependent() || E->isValueDependent())
9680 return;
9681
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009682 // Check for array bounds violations in cases where the check isn't triggered
9683 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9684 // ArraySubscriptExpr is on the RHS of a variable initialization.
9685 CheckArrayAccess(E);
9686
John McCallacf0ee52010-10-08 02:01:28 +00009687 // This is not the right CC for (e.g.) a variable initialization.
9688 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009689}
9690
Richard Trieu65724892014-11-15 06:37:39 +00009691/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9692/// Input argument E is a logical expression.
9693void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9694 ::CheckBoolLikeConversion(*this, E, CC);
9695}
9696
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009697/// Diagnose when expression is an integer constant expression and its evaluation
9698/// results in integer overflow
9699void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009700 // Use a work list to deal with nested struct initializers.
9701 SmallVector<Expr *, 2> Exprs(1, E);
9702
9703 do {
9704 Expr *E = Exprs.pop_back_val();
9705
9706 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9707 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9708 continue;
9709 }
9710
9711 if (auto InitList = dyn_cast<InitListExpr>(E))
9712 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9713 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009714}
9715
Richard Smithc406cb72013-01-17 01:17:56 +00009716namespace {
9717/// \brief Visitor for expressions which looks for unsequenced operations on the
9718/// same object.
9719class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009720 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9721
Richard Smithc406cb72013-01-17 01:17:56 +00009722 /// \brief A tree of sequenced regions within an expression. Two regions are
9723 /// unsequenced if one is an ancestor or a descendent of the other. When we
9724 /// finish processing an expression with sequencing, such as a comma
9725 /// expression, we fold its tree nodes into its parent, since they are
9726 /// unsequenced with respect to nodes we will visit later.
9727 class SequenceTree {
9728 struct Value {
9729 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9730 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009731 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009732 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009733 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009734
9735 public:
9736 /// \brief A region within an expression which may be sequenced with respect
9737 /// to some other region.
9738 class Seq {
9739 explicit Seq(unsigned N) : Index(N) {}
9740 unsigned Index;
9741 friend class SequenceTree;
9742 public:
9743 Seq() : Index(0) {}
9744 };
9745
9746 SequenceTree() { Values.push_back(Value(0)); }
9747 Seq root() const { return Seq(0); }
9748
9749 /// \brief Create a new sequence of operations, which is an unsequenced
9750 /// subset of \p Parent. This sequence of operations is sequenced with
9751 /// respect to other children of \p Parent.
9752 Seq allocate(Seq Parent) {
9753 Values.push_back(Value(Parent.Index));
9754 return Seq(Values.size() - 1);
9755 }
9756
9757 /// \brief Merge a sequence of operations into its parent.
9758 void merge(Seq S) {
9759 Values[S.Index].Merged = true;
9760 }
9761
9762 /// \brief Determine whether two operations are unsequenced. This operation
9763 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9764 /// should have been merged into its parent as appropriate.
9765 bool isUnsequenced(Seq Cur, Seq Old) {
9766 unsigned C = representative(Cur.Index);
9767 unsigned Target = representative(Old.Index);
9768 while (C >= Target) {
9769 if (C == Target)
9770 return true;
9771 C = Values[C].Parent;
9772 }
9773 return false;
9774 }
9775
9776 private:
9777 /// \brief Pick a representative for a sequence.
9778 unsigned representative(unsigned K) {
9779 if (Values[K].Merged)
9780 // Perform path compression as we go.
9781 return Values[K].Parent = representative(Values[K].Parent);
9782 return K;
9783 }
9784 };
9785
9786 /// An object for which we can track unsequenced uses.
9787 typedef NamedDecl *Object;
9788
9789 /// Different flavors of object usage which we track. We only track the
9790 /// least-sequenced usage of each kind.
9791 enum UsageKind {
9792 /// A read of an object. Multiple unsequenced reads are OK.
9793 UK_Use,
9794 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009795 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009796 UK_ModAsValue,
9797 /// A modification of an object which is not sequenced before the value
9798 /// computation of the expression, such as n++.
9799 UK_ModAsSideEffect,
9800
9801 UK_Count = UK_ModAsSideEffect + 1
9802 };
9803
9804 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009805 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009806 Expr *Use;
9807 SequenceTree::Seq Seq;
9808 };
9809
9810 struct UsageInfo {
9811 UsageInfo() : Diagnosed(false) {}
9812 Usage Uses[UK_Count];
9813 /// Have we issued a diagnostic for this variable already?
9814 bool Diagnosed;
9815 };
9816 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9817
9818 Sema &SemaRef;
9819 /// Sequenced regions within the expression.
9820 SequenceTree Tree;
9821 /// Declaration modifications and references which we have seen.
9822 UsageInfoMap UsageMap;
9823 /// The region we are currently within.
9824 SequenceTree::Seq Region;
9825 /// Filled in with declarations which were modified as a side-effect
9826 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009827 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009828 /// Expressions to check later. We defer checking these to reduce
9829 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009830 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009831
9832 /// RAII object wrapping the visitation of a sequenced subexpression of an
9833 /// expression. At the end of this process, the side-effects of the evaluation
9834 /// become sequenced with respect to the value computation of the result, so
9835 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9836 /// UK_ModAsValue.
9837 struct SequencedSubexpression {
9838 SequencedSubexpression(SequenceChecker &Self)
9839 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9840 Self.ModAsSideEffect = &ModAsSideEffect;
9841 }
9842 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009843 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9844 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009845 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009846 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9847 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009848 }
9849 Self.ModAsSideEffect = OldModAsSideEffect;
9850 }
9851
9852 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009853 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9854 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009855 };
9856
Richard Smith40238f02013-06-20 22:21:56 +00009857 /// RAII object wrapping the visitation of a subexpression which we might
9858 /// choose to evaluate as a constant. If any subexpression is evaluated and
9859 /// found to be non-constant, this allows us to suppress the evaluation of
9860 /// the outer expression.
9861 class EvaluationTracker {
9862 public:
9863 EvaluationTracker(SequenceChecker &Self)
9864 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9865 Self.EvalTracker = this;
9866 }
9867 ~EvaluationTracker() {
9868 Self.EvalTracker = Prev;
9869 if (Prev)
9870 Prev->EvalOK &= EvalOK;
9871 }
9872
9873 bool evaluate(const Expr *E, bool &Result) {
9874 if (!EvalOK || E->isValueDependent())
9875 return false;
9876 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9877 return EvalOK;
9878 }
9879
9880 private:
9881 SequenceChecker &Self;
9882 EvaluationTracker *Prev;
9883 bool EvalOK;
9884 } *EvalTracker;
9885
Richard Smithc406cb72013-01-17 01:17:56 +00009886 /// \brief Find the object which is produced by the specified expression,
9887 /// if any.
9888 Object getObject(Expr *E, bool Mod) const {
9889 E = E->IgnoreParenCasts();
9890 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9891 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9892 return getObject(UO->getSubExpr(), Mod);
9893 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9894 if (BO->getOpcode() == BO_Comma)
9895 return getObject(BO->getRHS(), Mod);
9896 if (Mod && BO->isAssignmentOp())
9897 return getObject(BO->getLHS(), Mod);
9898 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9899 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9900 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9901 return ME->getMemberDecl();
9902 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9903 // FIXME: If this is a reference, map through to its value.
9904 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009905 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009906 }
9907
9908 /// \brief Note that an object was modified or used by an expression.
9909 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9910 Usage &U = UI.Uses[UK];
9911 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9912 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9913 ModAsSideEffect->push_back(std::make_pair(O, U));
9914 U.Use = Ref;
9915 U.Seq = Region;
9916 }
9917 }
9918 /// \brief Check whether a modification or use conflicts with a prior usage.
9919 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9920 bool IsModMod) {
9921 if (UI.Diagnosed)
9922 return;
9923
9924 const Usage &U = UI.Uses[OtherKind];
9925 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9926 return;
9927
9928 Expr *Mod = U.Use;
9929 Expr *ModOrUse = Ref;
9930 if (OtherKind == UK_Use)
9931 std::swap(Mod, ModOrUse);
9932
9933 SemaRef.Diag(Mod->getExprLoc(),
9934 IsModMod ? diag::warn_unsequenced_mod_mod
9935 : diag::warn_unsequenced_mod_use)
9936 << O << SourceRange(ModOrUse->getExprLoc());
9937 UI.Diagnosed = true;
9938 }
9939
9940 void notePreUse(Object O, Expr *Use) {
9941 UsageInfo &U = UsageMap[O];
9942 // Uses conflict with other modifications.
9943 checkUsage(O, U, Use, UK_ModAsValue, false);
9944 }
9945 void notePostUse(Object O, Expr *Use) {
9946 UsageInfo &U = UsageMap[O];
9947 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9948 addUsage(U, O, Use, UK_Use);
9949 }
9950
9951 void notePreMod(Object O, Expr *Mod) {
9952 UsageInfo &U = UsageMap[O];
9953 // Modifications conflict with other modifications and with uses.
9954 checkUsage(O, U, Mod, UK_ModAsValue, true);
9955 checkUsage(O, U, Mod, UK_Use, false);
9956 }
9957 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9958 UsageInfo &U = UsageMap[O];
9959 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9960 addUsage(U, O, Use, UK);
9961 }
9962
9963public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009964 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009965 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9966 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009967 Visit(E);
9968 }
9969
9970 void VisitStmt(Stmt *S) {
9971 // Skip all statements which aren't expressions for now.
9972 }
9973
9974 void VisitExpr(Expr *E) {
9975 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009976 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009977 }
9978
9979 void VisitCastExpr(CastExpr *E) {
9980 Object O = Object();
9981 if (E->getCastKind() == CK_LValueToRValue)
9982 O = getObject(E->getSubExpr(), false);
9983
9984 if (O)
9985 notePreUse(O, E);
9986 VisitExpr(E);
9987 if (O)
9988 notePostUse(O, E);
9989 }
9990
9991 void VisitBinComma(BinaryOperator *BO) {
9992 // C++11 [expr.comma]p1:
9993 // Every value computation and side effect associated with the left
9994 // expression is sequenced before every value computation and side
9995 // effect associated with the right expression.
9996 SequenceTree::Seq LHS = Tree.allocate(Region);
9997 SequenceTree::Seq RHS = Tree.allocate(Region);
9998 SequenceTree::Seq OldRegion = Region;
9999
10000 {
10001 SequencedSubexpression SeqLHS(*this);
10002 Region = LHS;
10003 Visit(BO->getLHS());
10004 }
10005
10006 Region = RHS;
10007 Visit(BO->getRHS());
10008
10009 Region = OldRegion;
10010
10011 // Forget that LHS and RHS are sequenced. They are both unsequenced
10012 // with respect to other stuff.
10013 Tree.merge(LHS);
10014 Tree.merge(RHS);
10015 }
10016
10017 void VisitBinAssign(BinaryOperator *BO) {
10018 // The modification is sequenced after the value computation of the LHS
10019 // and RHS, so check it before inspecting the operands and update the
10020 // map afterwards.
10021 Object O = getObject(BO->getLHS(), true);
10022 if (!O)
10023 return VisitExpr(BO);
10024
10025 notePreMod(O, BO);
10026
10027 // C++11 [expr.ass]p7:
10028 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10029 // only once.
10030 //
10031 // Therefore, for a compound assignment operator, O is considered used
10032 // everywhere except within the evaluation of E1 itself.
10033 if (isa<CompoundAssignOperator>(BO))
10034 notePreUse(O, BO);
10035
10036 Visit(BO->getLHS());
10037
10038 if (isa<CompoundAssignOperator>(BO))
10039 notePostUse(O, BO);
10040
10041 Visit(BO->getRHS());
10042
Richard Smith83e37bee2013-06-26 23:16:51 +000010043 // C++11 [expr.ass]p1:
10044 // the assignment is sequenced [...] before the value computation of the
10045 // assignment expression.
10046 // C11 6.5.16/3 has no such rule.
10047 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10048 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010049 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010050
Richard Smithc406cb72013-01-17 01:17:56 +000010051 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10052 VisitBinAssign(CAO);
10053 }
10054
10055 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10056 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10057 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10058 Object O = getObject(UO->getSubExpr(), true);
10059 if (!O)
10060 return VisitExpr(UO);
10061
10062 notePreMod(O, UO);
10063 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010064 // C++11 [expr.pre.incr]p1:
10065 // the expression ++x is equivalent to x+=1
10066 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10067 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010068 }
10069
10070 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10071 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10072 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10073 Object O = getObject(UO->getSubExpr(), true);
10074 if (!O)
10075 return VisitExpr(UO);
10076
10077 notePreMod(O, UO);
10078 Visit(UO->getSubExpr());
10079 notePostMod(O, UO, UK_ModAsSideEffect);
10080 }
10081
10082 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10083 void VisitBinLOr(BinaryOperator *BO) {
10084 // The side-effects of the LHS of an '&&' are sequenced before the
10085 // value computation of the RHS, and hence before the value computation
10086 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10087 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010088 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010089 {
10090 SequencedSubexpression Sequenced(*this);
10091 Visit(BO->getLHS());
10092 }
10093
10094 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010095 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010096 if (!Result)
10097 Visit(BO->getRHS());
10098 } else {
10099 // Check for unsequenced operations in the RHS, treating it as an
10100 // entirely separate evaluation.
10101 //
10102 // FIXME: If there are operations in the RHS which are unsequenced
10103 // with respect to operations outside the RHS, and those operations
10104 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010105 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010106 }
Richard Smithc406cb72013-01-17 01:17:56 +000010107 }
10108 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010109 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010110 {
10111 SequencedSubexpression Sequenced(*this);
10112 Visit(BO->getLHS());
10113 }
10114
10115 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010116 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010117 if (Result)
10118 Visit(BO->getRHS());
10119 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010120 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010121 }
Richard Smithc406cb72013-01-17 01:17:56 +000010122 }
10123
10124 // Only visit the condition, unless we can be sure which subexpression will
10125 // be chosen.
10126 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010127 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010128 {
10129 SequencedSubexpression Sequenced(*this);
10130 Visit(CO->getCond());
10131 }
Richard Smithc406cb72013-01-17 01:17:56 +000010132
10133 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010134 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010135 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010136 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010137 WorkList.push_back(CO->getTrueExpr());
10138 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010139 }
Richard Smithc406cb72013-01-17 01:17:56 +000010140 }
10141
Richard Smithe3dbfe02013-06-30 10:40:20 +000010142 void VisitCallExpr(CallExpr *CE) {
10143 // C++11 [intro.execution]p15:
10144 // When calling a function [...], every value computation and side effect
10145 // associated with any argument expression, or with the postfix expression
10146 // designating the called function, is sequenced before execution of every
10147 // expression or statement in the body of the function [and thus before
10148 // the value computation of its result].
10149 SequencedSubexpression Sequenced(*this);
10150 Base::VisitCallExpr(CE);
10151
10152 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10153 }
10154
Richard Smithc406cb72013-01-17 01:17:56 +000010155 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010156 // This is a call, so all subexpressions are sequenced before the result.
10157 SequencedSubexpression Sequenced(*this);
10158
Richard Smithc406cb72013-01-17 01:17:56 +000010159 if (!CCE->isListInitialization())
10160 return VisitExpr(CCE);
10161
10162 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010163 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010164 SequenceTree::Seq Parent = Region;
10165 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10166 E = CCE->arg_end();
10167 I != E; ++I) {
10168 Region = Tree.allocate(Parent);
10169 Elts.push_back(Region);
10170 Visit(*I);
10171 }
10172
10173 // Forget that the initializers are sequenced.
10174 Region = Parent;
10175 for (unsigned I = 0; I < Elts.size(); ++I)
10176 Tree.merge(Elts[I]);
10177 }
10178
10179 void VisitInitListExpr(InitListExpr *ILE) {
10180 if (!SemaRef.getLangOpts().CPlusPlus11)
10181 return VisitExpr(ILE);
10182
10183 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010184 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010185 SequenceTree::Seq Parent = Region;
10186 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10187 Expr *E = ILE->getInit(I);
10188 if (!E) continue;
10189 Region = Tree.allocate(Parent);
10190 Elts.push_back(Region);
10191 Visit(E);
10192 }
10193
10194 // Forget that the initializers are sequenced.
10195 Region = Parent;
10196 for (unsigned I = 0; I < Elts.size(); ++I)
10197 Tree.merge(Elts[I]);
10198 }
10199};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010200} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010201
10202void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010203 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010204 WorkList.push_back(E);
10205 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010206 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010207 SequenceChecker(*this, Item, WorkList);
10208 }
Richard Smithc406cb72013-01-17 01:17:56 +000010209}
10210
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010211void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10212 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010213 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010214 if (!E->isInstantiationDependent())
10215 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010216 if (!IsConstexpr && !E->isValueDependent())
10217 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010218 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010219}
10220
John McCall1f425642010-11-11 03:21:53 +000010221void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10222 FieldDecl *BitField,
10223 Expr *Init) {
10224 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10225}
10226
David Majnemer61a5bbf2015-04-07 22:08:51 +000010227static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10228 SourceLocation Loc) {
10229 if (!PType->isVariablyModifiedType())
10230 return;
10231 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10232 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10233 return;
10234 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010235 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10236 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10237 return;
10238 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010239 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10240 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10241 return;
10242 }
10243
10244 const ArrayType *AT = S.Context.getAsArrayType(PType);
10245 if (!AT)
10246 return;
10247
10248 if (AT->getSizeModifier() != ArrayType::Star) {
10249 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10250 return;
10251 }
10252
10253 S.Diag(Loc, diag::err_array_star_in_function_definition);
10254}
10255
Mike Stump0c2ec772010-01-21 03:59:47 +000010256/// CheckParmsForFunctionDef - Check that the parameters of the given
10257/// function are appropriate for the definition of a function. This
10258/// takes care of any checks that cannot be performed on the
10259/// declaration itself, e.g., that the types of each of the function
10260/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010261bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010262 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010263 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010264 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010265 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10266 // function declarator that is part of a function definition of
10267 // that function shall not have incomplete type.
10268 //
10269 // This is also C++ [dcl.fct]p6.
10270 if (!Param->isInvalidDecl() &&
10271 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010272 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010273 Param->setInvalidDecl();
10274 HasInvalidParm = true;
10275 }
10276
10277 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10278 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010279 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010280 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010281 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010282 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010283 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010284
10285 // C99 6.7.5.3p12:
10286 // If the function declarator is not part of a definition of that
10287 // function, parameters may have incomplete type and may use the [*]
10288 // notation in their sequences of declarator specifiers to specify
10289 // variable length array types.
10290 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010291 // FIXME: This diagnostic should point the '[*]' if source-location
10292 // information is added for it.
10293 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010294
10295 // MSVC destroys objects passed by value in the callee. Therefore a
10296 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010297 // object's destructor. However, we don't perform any direct access check
10298 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010299 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10300 .getCXXABI()
10301 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010302 if (!Param->isInvalidDecl()) {
10303 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10304 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10305 if (!ClassDecl->isInvalidDecl() &&
10306 !ClassDecl->hasIrrelevantDestructor() &&
10307 !ClassDecl->isDependentContext()) {
10308 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10309 MarkFunctionReferenced(Param->getLocation(), Destructor);
10310 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10311 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010312 }
10313 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010314 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010315
10316 // Parameters with the pass_object_size attribute only need to be marked
10317 // constant at function definitions. Because we lack information about
10318 // whether we're on a declaration or definition when we're instantiating the
10319 // attribute, we need to check for constness here.
10320 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10321 if (!Param->getType().isConstQualified())
10322 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10323 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010324 }
10325
10326 return HasInvalidParm;
10327}
John McCall2b5c1b22010-08-12 21:44:57 +000010328
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010329/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10330/// or MemberExpr.
10331static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10332 ASTContext &Context) {
10333 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10334 return Context.getDeclAlign(DRE->getDecl());
10335
10336 if (const auto *ME = dyn_cast<MemberExpr>(E))
10337 return Context.getDeclAlign(ME->getMemberDecl());
10338
10339 return TypeAlign;
10340}
10341
John McCall2b5c1b22010-08-12 21:44:57 +000010342/// CheckCastAlign - Implements -Wcast-align, which warns when a
10343/// pointer cast increases the alignment requirements.
10344void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10345 // This is actually a lot of work to potentially be doing on every
10346 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010347 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010348 return;
10349
10350 // Ignore dependent types.
10351 if (T->isDependentType() || Op->getType()->isDependentType())
10352 return;
10353
10354 // Require that the destination be a pointer type.
10355 const PointerType *DestPtr = T->getAs<PointerType>();
10356 if (!DestPtr) return;
10357
10358 // If the destination has alignment 1, we're done.
10359 QualType DestPointee = DestPtr->getPointeeType();
10360 if (DestPointee->isIncompleteType()) return;
10361 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10362 if (DestAlign.isOne()) return;
10363
10364 // Require that the source be a pointer type.
10365 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10366 if (!SrcPtr) return;
10367 QualType SrcPointee = SrcPtr->getPointeeType();
10368
10369 // Whitelist casts from cv void*. We already implicitly
10370 // whitelisted casts to cv void*, since they have alignment 1.
10371 // Also whitelist casts involving incomplete types, which implicitly
10372 // includes 'void'.
10373 if (SrcPointee->isIncompleteType()) return;
10374
10375 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010376
10377 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10378 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10379 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10380 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10381 if (UO->getOpcode() == UO_AddrOf)
10382 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10383 }
10384
John McCall2b5c1b22010-08-12 21:44:57 +000010385 if (SrcAlign >= DestAlign) return;
10386
10387 Diag(TRange.getBegin(), diag::warn_cast_align)
10388 << Op->getType() << T
10389 << static_cast<unsigned>(SrcAlign.getQuantity())
10390 << static_cast<unsigned>(DestAlign.getQuantity())
10391 << TRange << Op->getSourceRange();
10392}
10393
Chandler Carruth28389f02011-08-05 09:10:50 +000010394/// \brief Check whether this array fits the idiom of a size-one tail padded
10395/// array member of a struct.
10396///
10397/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10398/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010399static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010400 const NamedDecl *ND) {
10401 if (Size != 1 || !ND) return false;
10402
10403 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10404 if (!FD) return false;
10405
10406 // Don't consider sizes resulting from macro expansions or template argument
10407 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010408
10409 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010410 while (TInfo) {
10411 TypeLoc TL = TInfo->getTypeLoc();
10412 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010413 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10414 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010415 TInfo = TDL->getTypeSourceInfo();
10416 continue;
10417 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010418 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10419 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010420 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10421 return false;
10422 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010423 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010424 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010425
10426 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010427 if (!RD) return false;
10428 if (RD->isUnion()) return false;
10429 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10430 if (!CRD->isStandardLayout()) return false;
10431 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010432
Benjamin Kramer8c543672011-08-06 03:04:42 +000010433 // See if this is the last field decl in the record.
10434 const Decl *D = FD;
10435 while ((D = D->getNextDeclInContext()))
10436 if (isa<FieldDecl>(D))
10437 return false;
10438 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010439}
10440
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010441void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010442 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010443 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010444 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010445 if (IndexExpr->isValueDependent())
10446 return;
10447
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010448 const Type *EffectiveType =
10449 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010450 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010451 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010452 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010453 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010454 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010455
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010456 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010457 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010458 return;
Richard Smith13f67182011-12-16 19:31:14 +000010459 if (IndexNegated)
10460 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010461
Craig Topperc3ec1492014-05-26 06:22:03 +000010462 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010463 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10464 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010465 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010466 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010467
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010468 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010469 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010470 if (!size.isStrictlyPositive())
10471 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010472
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010473 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010474 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010475 // Make sure we're comparing apples to apples when comparing index to size
10476 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10477 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010478 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010479 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010480 if (ptrarith_typesize != array_typesize) {
10481 // There's a cast to a different size type involved
10482 uint64_t ratio = array_typesize / ptrarith_typesize;
10483 // TODO: Be smarter about handling cases where array_typesize is not a
10484 // multiple of ptrarith_typesize
10485 if (ptrarith_typesize * ratio == array_typesize)
10486 size *= llvm::APInt(size.getBitWidth(), ratio);
10487 }
10488 }
10489
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010490 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010491 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010492 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010493 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010494
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010495 // For array subscripting the index must be less than size, but for pointer
10496 // arithmetic also allow the index (offset) to be equal to size since
10497 // computing the next address after the end of the array is legal and
10498 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010499 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010500 return;
10501
10502 // Also don't warn for arrays of size 1 which are members of some
10503 // structure. These are often used to approximate flexible arrays in C89
10504 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010505 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010506 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010507
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010508 // Suppress the warning if the subscript expression (as identified by the
10509 // ']' location) and the index expression are both from macro expansions
10510 // within a system header.
10511 if (ASE) {
10512 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10513 ASE->getRBracketLoc());
10514 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10515 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10516 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010517 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010518 return;
10519 }
10520 }
10521
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010522 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010523 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010524 DiagID = diag::warn_array_index_exceeds_bounds;
10525
10526 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10527 PDiag(DiagID) << index.toString(10, true)
10528 << size.toString(10, true)
10529 << (unsigned)size.getLimitedValue(~0U)
10530 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010531 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010532 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010533 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010534 DiagID = diag::warn_ptr_arith_precedes_bounds;
10535 if (index.isNegative()) index = -index;
10536 }
10537
10538 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10539 PDiag(DiagID) << index.toString(10, true)
10540 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010541 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010542
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010543 if (!ND) {
10544 // Try harder to find a NamedDecl to point at in the note.
10545 while (const ArraySubscriptExpr *ASE =
10546 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10547 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10549 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10550 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10551 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10552 }
10553
Chandler Carruth1af88f12011-02-17 21:10:52 +000010554 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010555 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10556 PDiag(diag::note_array_index_out_of_bounds)
10557 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010558}
10559
Ted Kremenekdf26df72011-03-01 18:41:00 +000010560void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010561 int AllowOnePastEnd = 0;
10562 while (expr) {
10563 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010564 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010565 case Stmt::ArraySubscriptExprClass: {
10566 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010567 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010568 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010569 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010570 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010571 case Stmt::OMPArraySectionExprClass: {
10572 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10573 if (ASE->getLowerBound())
10574 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10575 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10576 return;
10577 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010578 case Stmt::UnaryOperatorClass: {
10579 // Only unwrap the * and & unary operators
10580 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10581 expr = UO->getSubExpr();
10582 switch (UO->getOpcode()) {
10583 case UO_AddrOf:
10584 AllowOnePastEnd++;
10585 break;
10586 case UO_Deref:
10587 AllowOnePastEnd--;
10588 break;
10589 default:
10590 return;
10591 }
10592 break;
10593 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010594 case Stmt::ConditionalOperatorClass: {
10595 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10596 if (const Expr *lhs = cond->getLHS())
10597 CheckArrayAccess(lhs);
10598 if (const Expr *rhs = cond->getRHS())
10599 CheckArrayAccess(rhs);
10600 return;
10601 }
10602 default:
10603 return;
10604 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010605 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010606}
John McCall31168b02011-06-15 23:02:42 +000010607
10608//===--- CHECK: Objective-C retain cycles ----------------------------------//
10609
10610namespace {
10611 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010612 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010613 VarDecl *Variable;
10614 SourceRange Range;
10615 SourceLocation Loc;
10616 bool Indirect;
10617
10618 void setLocsFrom(Expr *e) {
10619 Loc = e->getExprLoc();
10620 Range = e->getSourceRange();
10621 }
10622 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010623} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010624
10625/// Consider whether capturing the given variable can possibly lead to
10626/// a retain cycle.
10627static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010628 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010629 // lifetime. In MRR, it's captured strongly if the variable is
10630 // __block and has an appropriate type.
10631 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10632 return false;
10633
10634 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010635 if (ref)
10636 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010637 return true;
10638}
10639
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010640static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010641 while (true) {
10642 e = e->IgnoreParens();
10643 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10644 switch (cast->getCastKind()) {
10645 case CK_BitCast:
10646 case CK_LValueBitCast:
10647 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010648 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010649 e = cast->getSubExpr();
10650 continue;
10651
John McCall31168b02011-06-15 23:02:42 +000010652 default:
10653 return false;
10654 }
10655 }
10656
10657 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10658 ObjCIvarDecl *ivar = ref->getDecl();
10659 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10660 return false;
10661
10662 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010663 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010664 return false;
10665
10666 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10667 owner.Indirect = true;
10668 return true;
10669 }
10670
10671 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10672 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10673 if (!var) return false;
10674 return considerVariable(var, ref, owner);
10675 }
10676
John McCall31168b02011-06-15 23:02:42 +000010677 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10678 if (member->isArrow()) return false;
10679
10680 // Don't count this as an indirect ownership.
10681 e = member->getBase();
10682 continue;
10683 }
10684
John McCallfe96e0b2011-11-06 09:01:30 +000010685 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10686 // Only pay attention to pseudo-objects on property references.
10687 ObjCPropertyRefExpr *pre
10688 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10689 ->IgnoreParens());
10690 if (!pre) return false;
10691 if (pre->isImplicitProperty()) return false;
10692 ObjCPropertyDecl *property = pre->getExplicitProperty();
10693 if (!property->isRetaining() &&
10694 !(property->getPropertyIvarDecl() &&
10695 property->getPropertyIvarDecl()->getType()
10696 .getObjCLifetime() == Qualifiers::OCL_Strong))
10697 return false;
10698
10699 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010700 if (pre->isSuperReceiver()) {
10701 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10702 if (!owner.Variable)
10703 return false;
10704 owner.Loc = pre->getLocation();
10705 owner.Range = pre->getSourceRange();
10706 return true;
10707 }
John McCallfe96e0b2011-11-06 09:01:30 +000010708 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10709 ->getSourceExpr());
10710 continue;
10711 }
10712
John McCall31168b02011-06-15 23:02:42 +000010713 // Array ivars?
10714
10715 return false;
10716 }
10717}
10718
10719namespace {
10720 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10721 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10722 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010723 Context(Context), Variable(variable), Capturer(nullptr),
10724 VarWillBeReased(false) {}
10725 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010726 VarDecl *Variable;
10727 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010728 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010729
10730 void VisitDeclRefExpr(DeclRefExpr *ref) {
10731 if (ref->getDecl() == Variable && !Capturer)
10732 Capturer = ref;
10733 }
10734
John McCall31168b02011-06-15 23:02:42 +000010735 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10736 if (Capturer) return;
10737 Visit(ref->getBase());
10738 if (Capturer && ref->isFreeIvar())
10739 Capturer = ref;
10740 }
10741
10742 void VisitBlockExpr(BlockExpr *block) {
10743 // Look inside nested blocks
10744 if (block->getBlockDecl()->capturesVariable(Variable))
10745 Visit(block->getBlockDecl()->getBody());
10746 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010747
10748 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10749 if (Capturer) return;
10750 if (OVE->getSourceExpr())
10751 Visit(OVE->getSourceExpr());
10752 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010753 void VisitBinaryOperator(BinaryOperator *BinOp) {
10754 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10755 return;
10756 Expr *LHS = BinOp->getLHS();
10757 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10758 if (DRE->getDecl() != Variable)
10759 return;
10760 if (Expr *RHS = BinOp->getRHS()) {
10761 RHS = RHS->IgnoreParenCasts();
10762 llvm::APSInt Value;
10763 VarWillBeReased =
10764 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10765 }
10766 }
10767 }
John McCall31168b02011-06-15 23:02:42 +000010768 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010769} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010770
10771/// Check whether the given argument is a block which captures a
10772/// variable.
10773static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10774 assert(owner.Variable && owner.Loc.isValid());
10775
10776 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010777
10778 // Look through [^{...} copy] and Block_copy(^{...}).
10779 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10780 Selector Cmd = ME->getSelector();
10781 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10782 e = ME->getInstanceReceiver();
10783 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010784 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010785 e = e->IgnoreParenCasts();
10786 }
10787 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10788 if (CE->getNumArgs() == 1) {
10789 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010790 if (Fn) {
10791 const IdentifierInfo *FnI = Fn->getIdentifier();
10792 if (FnI && FnI->isStr("_Block_copy")) {
10793 e = CE->getArg(0)->IgnoreParenCasts();
10794 }
10795 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010796 }
10797 }
10798
John McCall31168b02011-06-15 23:02:42 +000010799 BlockExpr *block = dyn_cast<BlockExpr>(e);
10800 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010801 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010802
10803 FindCaptureVisitor visitor(S.Context, owner.Variable);
10804 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010805 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010806}
10807
10808static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10809 RetainCycleOwner &owner) {
10810 assert(capturer);
10811 assert(owner.Variable && owner.Loc.isValid());
10812
10813 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10814 << owner.Variable << capturer->getSourceRange();
10815 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10816 << owner.Indirect << owner.Range;
10817}
10818
10819/// Check for a keyword selector that starts with the word 'add' or
10820/// 'set'.
10821static bool isSetterLikeSelector(Selector sel) {
10822 if (sel.isUnarySelector()) return false;
10823
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010824 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010825 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010826 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010827 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010828 else if (str.startswith("add")) {
10829 // Specially whitelist 'addOperationWithBlock:'.
10830 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10831 return false;
10832 str = str.substr(3);
10833 }
John McCall31168b02011-06-15 23:02:42 +000010834 else
10835 return false;
10836
10837 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010838 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010839}
10840
Benjamin Kramer3a743452015-03-09 15:03:32 +000010841static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10842 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010843 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10844 Message->getReceiverInterface(),
10845 NSAPI::ClassId_NSMutableArray);
10846 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010847 return None;
10848 }
10849
10850 Selector Sel = Message->getSelector();
10851
10852 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10853 S.NSAPIObj->getNSArrayMethodKind(Sel);
10854 if (!MKOpt) {
10855 return None;
10856 }
10857
10858 NSAPI::NSArrayMethodKind MK = *MKOpt;
10859
10860 switch (MK) {
10861 case NSAPI::NSMutableArr_addObject:
10862 case NSAPI::NSMutableArr_insertObjectAtIndex:
10863 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10864 return 0;
10865 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10866 return 1;
10867
10868 default:
10869 return None;
10870 }
10871
10872 return None;
10873}
10874
10875static
10876Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10877 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010878 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10879 Message->getReceiverInterface(),
10880 NSAPI::ClassId_NSMutableDictionary);
10881 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010882 return None;
10883 }
10884
10885 Selector Sel = Message->getSelector();
10886
10887 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10888 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10889 if (!MKOpt) {
10890 return None;
10891 }
10892
10893 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10894
10895 switch (MK) {
10896 case NSAPI::NSMutableDict_setObjectForKey:
10897 case NSAPI::NSMutableDict_setValueForKey:
10898 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10899 return 0;
10900
10901 default:
10902 return None;
10903 }
10904
10905 return None;
10906}
10907
10908static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010909 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10910 Message->getReceiverInterface(),
10911 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010912
Alex Denisov5dfac812015-08-06 04:51:14 +000010913 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10914 Message->getReceiverInterface(),
10915 NSAPI::ClassId_NSMutableOrderedSet);
10916 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010917 return None;
10918 }
10919
10920 Selector Sel = Message->getSelector();
10921
10922 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10923 if (!MKOpt) {
10924 return None;
10925 }
10926
10927 NSAPI::NSSetMethodKind MK = *MKOpt;
10928
10929 switch (MK) {
10930 case NSAPI::NSMutableSet_addObject:
10931 case NSAPI::NSOrderedSet_setObjectAtIndex:
10932 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10933 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10934 return 0;
10935 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10936 return 1;
10937 }
10938
10939 return None;
10940}
10941
10942void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10943 if (!Message->isInstanceMessage()) {
10944 return;
10945 }
10946
10947 Optional<int> ArgOpt;
10948
10949 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10950 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10951 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10952 return;
10953 }
10954
10955 int ArgIndex = *ArgOpt;
10956
Alex Denisove1d882c2015-03-04 17:55:52 +000010957 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10958 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10959 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10960 }
10961
Alex Denisov5dfac812015-08-06 04:51:14 +000010962 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010963 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010964 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010965 Diag(Message->getSourceRange().getBegin(),
10966 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010967 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010968 }
10969 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010970 } else {
10971 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10972
10973 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10974 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10975 }
10976
10977 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10978 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10979 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10980 ValueDecl *Decl = ReceiverRE->getDecl();
10981 Diag(Message->getSourceRange().getBegin(),
10982 diag::warn_objc_circular_container)
10983 << Decl->getName() << Decl->getName();
10984 if (!ArgRE->isObjCSelfExpr()) {
10985 Diag(Decl->getLocation(),
10986 diag::note_objc_circular_container_declared_here)
10987 << Decl->getName();
10988 }
10989 }
10990 }
10991 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10992 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10993 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10994 ObjCIvarDecl *Decl = IvarRE->getDecl();
10995 Diag(Message->getSourceRange().getBegin(),
10996 diag::warn_objc_circular_container)
10997 << Decl->getName() << Decl->getName();
10998 Diag(Decl->getLocation(),
10999 diag::note_objc_circular_container_declared_here)
11000 << Decl->getName();
11001 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011002 }
11003 }
11004 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011005}
11006
John McCall31168b02011-06-15 23:02:42 +000011007/// Check a message send to see if it's likely to cause a retain cycle.
11008void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11009 // Only check instance methods whose selector looks like a setter.
11010 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11011 return;
11012
11013 // Try to find a variable that the receiver is strongly owned by.
11014 RetainCycleOwner owner;
11015 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011016 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011017 return;
11018 } else {
11019 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11020 owner.Variable = getCurMethodDecl()->getSelfDecl();
11021 owner.Loc = msg->getSuperLoc();
11022 owner.Range = msg->getSuperLoc();
11023 }
11024
11025 // Check whether the receiver is captured by any of the arguments.
11026 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11027 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11028 return diagnoseRetainCycle(*this, capturer, owner);
11029}
11030
11031/// Check a property assign to see if it's likely to cause a retain cycle.
11032void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11033 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011034 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011035 return;
11036
11037 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11038 diagnoseRetainCycle(*this, capturer, owner);
11039}
11040
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011041void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11042 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011043 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011044 return;
11045
11046 // Because we don't have an expression for the variable, we have to set the
11047 // location explicitly here.
11048 Owner.Loc = Var->getLocation();
11049 Owner.Range = Var->getSourceRange();
11050
11051 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11052 diagnoseRetainCycle(*this, Capturer, Owner);
11053}
11054
Ted Kremenek9304da92012-12-21 08:04:28 +000011055static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11056 Expr *RHS, bool isProperty) {
11057 // Check if RHS is an Objective-C object literal, which also can get
11058 // immediately zapped in a weak reference. Note that we explicitly
11059 // allow ObjCStringLiterals, since those are designed to never really die.
11060 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011061
Ted Kremenek64873352012-12-21 22:46:35 +000011062 // This enum needs to match with the 'select' in
11063 // warn_objc_arc_literal_assign (off-by-1).
11064 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11065 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11066 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011067
11068 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011069 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011070 << (isProperty ? 0 : 1)
11071 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011072
11073 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011074}
11075
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011076static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11077 Qualifiers::ObjCLifetime LT,
11078 Expr *RHS, bool isProperty) {
11079 // Strip off any implicit cast added to get to the one ARC-specific.
11080 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11081 if (cast->getCastKind() == CK_ARCConsumeObject) {
11082 S.Diag(Loc, diag::warn_arc_retained_assign)
11083 << (LT == Qualifiers::OCL_ExplicitNone)
11084 << (isProperty ? 0 : 1)
11085 << RHS->getSourceRange();
11086 return true;
11087 }
11088 RHS = cast->getSubExpr();
11089 }
11090
11091 if (LT == Qualifiers::OCL_Weak &&
11092 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11093 return true;
11094
11095 return false;
11096}
11097
Ted Kremenekb36234d2012-12-21 08:04:20 +000011098bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11099 QualType LHS, Expr *RHS) {
11100 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11101
11102 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11103 return false;
11104
11105 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11106 return true;
11107
11108 return false;
11109}
11110
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011111void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11112 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011113 QualType LHSType;
11114 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011115 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011116 ObjCPropertyRefExpr *PRE
11117 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11118 if (PRE && !PRE->isImplicitProperty()) {
11119 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11120 if (PD)
11121 LHSType = PD->getType();
11122 }
11123
11124 if (LHSType.isNull())
11125 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011126
11127 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11128
11129 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011130 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011131 getCurFunction()->markSafeWeakUse(LHS);
11132 }
11133
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011134 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11135 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011136
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011137 // FIXME. Check for other life times.
11138 if (LT != Qualifiers::OCL_None)
11139 return;
11140
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011141 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011142 if (PRE->isImplicitProperty())
11143 return;
11144 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11145 if (!PD)
11146 return;
11147
Bill Wendling44426052012-12-20 19:22:21 +000011148 unsigned Attributes = PD->getPropertyAttributes();
11149 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011150 // when 'assign' attribute was not explicitly specified
11151 // by user, ignore it and rely on property type itself
11152 // for lifetime info.
11153 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11154 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11155 LHSType->isObjCRetainableType())
11156 return;
11157
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011158 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011159 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011160 Diag(Loc, diag::warn_arc_retained_property_assign)
11161 << RHS->getSourceRange();
11162 return;
11163 }
11164 RHS = cast->getSubExpr();
11165 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011166 }
Bill Wendling44426052012-12-20 19:22:21 +000011167 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011168 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11169 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011170 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011171 }
11172}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011173
11174//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11175
11176namespace {
11177bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11178 SourceLocation StmtLoc,
11179 const NullStmt *Body) {
11180 // Do not warn if the body is a macro that expands to nothing, e.g:
11181 //
11182 // #define CALL(x)
11183 // if (condition)
11184 // CALL(0);
11185 //
11186 if (Body->hasLeadingEmptyMacro())
11187 return false;
11188
11189 // Get line numbers of statement and body.
11190 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011191 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011192 &StmtLineInvalid);
11193 if (StmtLineInvalid)
11194 return false;
11195
11196 bool BodyLineInvalid;
11197 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11198 &BodyLineInvalid);
11199 if (BodyLineInvalid)
11200 return false;
11201
11202 // Warn if null statement and body are on the same line.
11203 if (StmtLine != BodyLine)
11204 return false;
11205
11206 return true;
11207}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011208} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011209
11210void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11211 const Stmt *Body,
11212 unsigned DiagID) {
11213 // Since this is a syntactic check, don't emit diagnostic for template
11214 // instantiations, this just adds noise.
11215 if (CurrentInstantiationScope)
11216 return;
11217
11218 // The body should be a null statement.
11219 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11220 if (!NBody)
11221 return;
11222
11223 // Do the usual checks.
11224 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11225 return;
11226
11227 Diag(NBody->getSemiLoc(), DiagID);
11228 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11229}
11230
11231void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11232 const Stmt *PossibleBody) {
11233 assert(!CurrentInstantiationScope); // Ensured by caller
11234
11235 SourceLocation StmtLoc;
11236 const Stmt *Body;
11237 unsigned DiagID;
11238 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11239 StmtLoc = FS->getRParenLoc();
11240 Body = FS->getBody();
11241 DiagID = diag::warn_empty_for_body;
11242 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11243 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11244 Body = WS->getBody();
11245 DiagID = diag::warn_empty_while_body;
11246 } else
11247 return; // Neither `for' nor `while'.
11248
11249 // The body should be a null statement.
11250 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11251 if (!NBody)
11252 return;
11253
11254 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011255 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011256 return;
11257
11258 // Do the usual checks.
11259 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11260 return;
11261
11262 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11263 // noise level low, emit diagnostics only if for/while is followed by a
11264 // CompoundStmt, e.g.:
11265 // for (int i = 0; i < n; i++);
11266 // {
11267 // a(i);
11268 // }
11269 // or if for/while is followed by a statement with more indentation
11270 // than for/while itself:
11271 // for (int i = 0; i < n; i++);
11272 // a(i);
11273 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11274 if (!ProbableTypo) {
11275 bool BodyColInvalid;
11276 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11277 PossibleBody->getLocStart(),
11278 &BodyColInvalid);
11279 if (BodyColInvalid)
11280 return;
11281
11282 bool StmtColInvalid;
11283 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11284 S->getLocStart(),
11285 &StmtColInvalid);
11286 if (StmtColInvalid)
11287 return;
11288
11289 if (BodyCol > StmtCol)
11290 ProbableTypo = true;
11291 }
11292
11293 if (ProbableTypo) {
11294 Diag(NBody->getSemiLoc(), DiagID);
11295 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11296 }
11297}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011298
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011299//===--- CHECK: Warn on self move with std::move. -------------------------===//
11300
11301/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11302void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11303 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011304 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11305 return;
11306
11307 if (!ActiveTemplateInstantiations.empty())
11308 return;
11309
11310 // Strip parens and casts away.
11311 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11312 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11313
11314 // Check for a call expression
11315 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11316 if (!CE || CE->getNumArgs() != 1)
11317 return;
11318
11319 // Check for a call to std::move
11320 const FunctionDecl *FD = CE->getDirectCallee();
11321 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11322 !FD->getIdentifier()->isStr("move"))
11323 return;
11324
11325 // Get argument from std::move
11326 RHSExpr = CE->getArg(0);
11327
11328 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11329 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11330
11331 // Two DeclRefExpr's, check that the decls are the same.
11332 if (LHSDeclRef && RHSDeclRef) {
11333 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11334 return;
11335 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11336 RHSDeclRef->getDecl()->getCanonicalDecl())
11337 return;
11338
11339 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11340 << LHSExpr->getSourceRange()
11341 << RHSExpr->getSourceRange();
11342 return;
11343 }
11344
11345 // Member variables require a different approach to check for self moves.
11346 // MemberExpr's are the same if every nested MemberExpr refers to the same
11347 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11348 // the base Expr's are CXXThisExpr's.
11349 const Expr *LHSBase = LHSExpr;
11350 const Expr *RHSBase = RHSExpr;
11351 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11352 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11353 if (!LHSME || !RHSME)
11354 return;
11355
11356 while (LHSME && RHSME) {
11357 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11358 RHSME->getMemberDecl()->getCanonicalDecl())
11359 return;
11360
11361 LHSBase = LHSME->getBase();
11362 RHSBase = RHSME->getBase();
11363 LHSME = dyn_cast<MemberExpr>(LHSBase);
11364 RHSME = dyn_cast<MemberExpr>(RHSBase);
11365 }
11366
11367 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11368 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11369 if (LHSDeclRef && RHSDeclRef) {
11370 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11371 return;
11372 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11373 RHSDeclRef->getDecl()->getCanonicalDecl())
11374 return;
11375
11376 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11377 << LHSExpr->getSourceRange()
11378 << RHSExpr->getSourceRange();
11379 return;
11380 }
11381
11382 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11383 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11384 << LHSExpr->getSourceRange()
11385 << RHSExpr->getSourceRange();
11386}
11387
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011388//===--- Layout compatibility ----------------------------------------------//
11389
11390namespace {
11391
11392bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11393
11394/// \brief Check if two enumeration types are layout-compatible.
11395bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11396 // C++11 [dcl.enum] p8:
11397 // Two enumeration types are layout-compatible if they have the same
11398 // underlying type.
11399 return ED1->isComplete() && ED2->isComplete() &&
11400 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11401}
11402
11403/// \brief Check if two fields are layout-compatible.
11404bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11405 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11406 return false;
11407
11408 if (Field1->isBitField() != Field2->isBitField())
11409 return false;
11410
11411 if (Field1->isBitField()) {
11412 // Make sure that the bit-fields are the same length.
11413 unsigned Bits1 = Field1->getBitWidthValue(C);
11414 unsigned Bits2 = Field2->getBitWidthValue(C);
11415
11416 if (Bits1 != Bits2)
11417 return false;
11418 }
11419
11420 return true;
11421}
11422
11423/// \brief Check if two standard-layout structs are layout-compatible.
11424/// (C++11 [class.mem] p17)
11425bool isLayoutCompatibleStruct(ASTContext &C,
11426 RecordDecl *RD1,
11427 RecordDecl *RD2) {
11428 // If both records are C++ classes, check that base classes match.
11429 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11430 // If one of records is a CXXRecordDecl we are in C++ mode,
11431 // thus the other one is a CXXRecordDecl, too.
11432 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11433 // Check number of base classes.
11434 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11435 return false;
11436
11437 // Check the base classes.
11438 for (CXXRecordDecl::base_class_const_iterator
11439 Base1 = D1CXX->bases_begin(),
11440 BaseEnd1 = D1CXX->bases_end(),
11441 Base2 = D2CXX->bases_begin();
11442 Base1 != BaseEnd1;
11443 ++Base1, ++Base2) {
11444 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11445 return false;
11446 }
11447 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11448 // If only RD2 is a C++ class, it should have zero base classes.
11449 if (D2CXX->getNumBases() > 0)
11450 return false;
11451 }
11452
11453 // Check the fields.
11454 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11455 Field2End = RD2->field_end(),
11456 Field1 = RD1->field_begin(),
11457 Field1End = RD1->field_end();
11458 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11459 if (!isLayoutCompatible(C, *Field1, *Field2))
11460 return false;
11461 }
11462 if (Field1 != Field1End || Field2 != Field2End)
11463 return false;
11464
11465 return true;
11466}
11467
11468/// \brief Check if two standard-layout unions are layout-compatible.
11469/// (C++11 [class.mem] p18)
11470bool isLayoutCompatibleUnion(ASTContext &C,
11471 RecordDecl *RD1,
11472 RecordDecl *RD2) {
11473 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011474 for (auto *Field2 : RD2->fields())
11475 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011476
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011477 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011478 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11479 I = UnmatchedFields.begin(),
11480 E = UnmatchedFields.end();
11481
11482 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011483 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011484 bool Result = UnmatchedFields.erase(*I);
11485 (void) Result;
11486 assert(Result);
11487 break;
11488 }
11489 }
11490 if (I == E)
11491 return false;
11492 }
11493
11494 return UnmatchedFields.empty();
11495}
11496
11497bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11498 if (RD1->isUnion() != RD2->isUnion())
11499 return false;
11500
11501 if (RD1->isUnion())
11502 return isLayoutCompatibleUnion(C, RD1, RD2);
11503 else
11504 return isLayoutCompatibleStruct(C, RD1, RD2);
11505}
11506
11507/// \brief Check if two types are layout-compatible in C++11 sense.
11508bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11509 if (T1.isNull() || T2.isNull())
11510 return false;
11511
11512 // C++11 [basic.types] p11:
11513 // If two types T1 and T2 are the same type, then T1 and T2 are
11514 // layout-compatible types.
11515 if (C.hasSameType(T1, T2))
11516 return true;
11517
11518 T1 = T1.getCanonicalType().getUnqualifiedType();
11519 T2 = T2.getCanonicalType().getUnqualifiedType();
11520
11521 const Type::TypeClass TC1 = T1->getTypeClass();
11522 const Type::TypeClass TC2 = T2->getTypeClass();
11523
11524 if (TC1 != TC2)
11525 return false;
11526
11527 if (TC1 == Type::Enum) {
11528 return isLayoutCompatible(C,
11529 cast<EnumType>(T1)->getDecl(),
11530 cast<EnumType>(T2)->getDecl());
11531 } else if (TC1 == Type::Record) {
11532 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11533 return false;
11534
11535 return isLayoutCompatible(C,
11536 cast<RecordType>(T1)->getDecl(),
11537 cast<RecordType>(T2)->getDecl());
11538 }
11539
11540 return false;
11541}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011542} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011543
11544//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11545
11546namespace {
11547/// \brief Given a type tag expression find the type tag itself.
11548///
11549/// \param TypeExpr Type tag expression, as it appears in user's code.
11550///
11551/// \param VD Declaration of an identifier that appears in a type tag.
11552///
11553/// \param MagicValue Type tag magic value.
11554bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11555 const ValueDecl **VD, uint64_t *MagicValue) {
11556 while(true) {
11557 if (!TypeExpr)
11558 return false;
11559
11560 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11561
11562 switch (TypeExpr->getStmtClass()) {
11563 case Stmt::UnaryOperatorClass: {
11564 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11565 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11566 TypeExpr = UO->getSubExpr();
11567 continue;
11568 }
11569 return false;
11570 }
11571
11572 case Stmt::DeclRefExprClass: {
11573 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11574 *VD = DRE->getDecl();
11575 return true;
11576 }
11577
11578 case Stmt::IntegerLiteralClass: {
11579 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11580 llvm::APInt MagicValueAPInt = IL->getValue();
11581 if (MagicValueAPInt.getActiveBits() <= 64) {
11582 *MagicValue = MagicValueAPInt.getZExtValue();
11583 return true;
11584 } else
11585 return false;
11586 }
11587
11588 case Stmt::BinaryConditionalOperatorClass:
11589 case Stmt::ConditionalOperatorClass: {
11590 const AbstractConditionalOperator *ACO =
11591 cast<AbstractConditionalOperator>(TypeExpr);
11592 bool Result;
11593 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11594 if (Result)
11595 TypeExpr = ACO->getTrueExpr();
11596 else
11597 TypeExpr = ACO->getFalseExpr();
11598 continue;
11599 }
11600 return false;
11601 }
11602
11603 case Stmt::BinaryOperatorClass: {
11604 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11605 if (BO->getOpcode() == BO_Comma) {
11606 TypeExpr = BO->getRHS();
11607 continue;
11608 }
11609 return false;
11610 }
11611
11612 default:
11613 return false;
11614 }
11615 }
11616}
11617
11618/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11619///
11620/// \param TypeExpr Expression that specifies a type tag.
11621///
11622/// \param MagicValues Registered magic values.
11623///
11624/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11625/// kind.
11626///
11627/// \param TypeInfo Information about the corresponding C type.
11628///
11629/// \returns true if the corresponding C type was found.
11630bool GetMatchingCType(
11631 const IdentifierInfo *ArgumentKind,
11632 const Expr *TypeExpr, const ASTContext &Ctx,
11633 const llvm::DenseMap<Sema::TypeTagMagicValue,
11634 Sema::TypeTagData> *MagicValues,
11635 bool &FoundWrongKind,
11636 Sema::TypeTagData &TypeInfo) {
11637 FoundWrongKind = false;
11638
11639 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011640 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011641
11642 uint64_t MagicValue;
11643
11644 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11645 return false;
11646
11647 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011648 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011649 if (I->getArgumentKind() != ArgumentKind) {
11650 FoundWrongKind = true;
11651 return false;
11652 }
11653 TypeInfo.Type = I->getMatchingCType();
11654 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11655 TypeInfo.MustBeNull = I->getMustBeNull();
11656 return true;
11657 }
11658 return false;
11659 }
11660
11661 if (!MagicValues)
11662 return false;
11663
11664 llvm::DenseMap<Sema::TypeTagMagicValue,
11665 Sema::TypeTagData>::const_iterator I =
11666 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11667 if (I == MagicValues->end())
11668 return false;
11669
11670 TypeInfo = I->second;
11671 return true;
11672}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011673} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011674
11675void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11676 uint64_t MagicValue, QualType Type,
11677 bool LayoutCompatible,
11678 bool MustBeNull) {
11679 if (!TypeTagForDatatypeMagicValues)
11680 TypeTagForDatatypeMagicValues.reset(
11681 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11682
11683 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11684 (*TypeTagForDatatypeMagicValues)[Magic] =
11685 TypeTagData(Type, LayoutCompatible, MustBeNull);
11686}
11687
11688namespace {
11689bool IsSameCharType(QualType T1, QualType T2) {
11690 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11691 if (!BT1)
11692 return false;
11693
11694 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11695 if (!BT2)
11696 return false;
11697
11698 BuiltinType::Kind T1Kind = BT1->getKind();
11699 BuiltinType::Kind T2Kind = BT2->getKind();
11700
11701 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11702 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11703 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11704 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11705}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011706} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011707
11708void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11709 const Expr * const *ExprArgs) {
11710 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11711 bool IsPointerAttr = Attr->getIsPointer();
11712
11713 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11714 bool FoundWrongKind;
11715 TypeTagData TypeInfo;
11716 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11717 TypeTagForDatatypeMagicValues.get(),
11718 FoundWrongKind, TypeInfo)) {
11719 if (FoundWrongKind)
11720 Diag(TypeTagExpr->getExprLoc(),
11721 diag::warn_type_tag_for_datatype_wrong_kind)
11722 << TypeTagExpr->getSourceRange();
11723 return;
11724 }
11725
11726 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11727 if (IsPointerAttr) {
11728 // Skip implicit cast of pointer to `void *' (as a function argument).
11729 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011730 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011731 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011732 ArgumentExpr = ICE->getSubExpr();
11733 }
11734 QualType ArgumentType = ArgumentExpr->getType();
11735
11736 // Passing a `void*' pointer shouldn't trigger a warning.
11737 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11738 return;
11739
11740 if (TypeInfo.MustBeNull) {
11741 // Type tag with matching void type requires a null pointer.
11742 if (!ArgumentExpr->isNullPointerConstant(Context,
11743 Expr::NPC_ValueDependentIsNotNull)) {
11744 Diag(ArgumentExpr->getExprLoc(),
11745 diag::warn_type_safety_null_pointer_required)
11746 << ArgumentKind->getName()
11747 << ArgumentExpr->getSourceRange()
11748 << TypeTagExpr->getSourceRange();
11749 }
11750 return;
11751 }
11752
11753 QualType RequiredType = TypeInfo.Type;
11754 if (IsPointerAttr)
11755 RequiredType = Context.getPointerType(RequiredType);
11756
11757 bool mismatch = false;
11758 if (!TypeInfo.LayoutCompatible) {
11759 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11760
11761 // C++11 [basic.fundamental] p1:
11762 // Plain char, signed char, and unsigned char are three distinct types.
11763 //
11764 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11765 // char' depending on the current char signedness mode.
11766 if (mismatch)
11767 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11768 RequiredType->getPointeeType())) ||
11769 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11770 mismatch = false;
11771 } else
11772 if (IsPointerAttr)
11773 mismatch = !isLayoutCompatible(Context,
11774 ArgumentType->getPointeeType(),
11775 RequiredType->getPointeeType());
11776 else
11777 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11778
11779 if (mismatch)
11780 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011781 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011782 << TypeInfo.LayoutCompatible << RequiredType
11783 << ArgumentExpr->getSourceRange()
11784 << TypeTagExpr->getSourceRange();
11785}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011786
11787void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11788 CharUnits Alignment) {
11789 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11790}
11791
11792void Sema::DiagnoseMisalignedMembers() {
11793 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011794 const NamedDecl *ND = m.RD;
11795 if (ND->getName().empty()) {
11796 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11797 ND = TD;
11798 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011799 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011800 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011801 }
11802 MisalignedMembers.clear();
11803}
11804
11805void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011806 E = E->IgnoreParens();
11807 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011808 return;
11809 if (isa<UnaryOperator>(E) &&
11810 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11811 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11812 if (isa<MemberExpr>(Op)) {
11813 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11814 MisalignedMember(Op));
11815 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011816 (T->isIntegerType() ||
11817 (T->isPointerType() &&
11818 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011819 MisalignedMembers.erase(MA);
11820 }
11821 }
11822}
11823
11824void Sema::RefersToMemberWithReducedAlignment(
11825 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000011826 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11827 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011828 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011829 if (!ME)
11830 return;
11831
11832 // For a chain of MemberExpr like "a.b.c.d" this list
11833 // will keep FieldDecl's like [d, c, b].
11834 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11835 const MemberExpr *TopME = nullptr;
11836 bool AnyIsPacked = false;
11837 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011838 QualType BaseType = ME->getBase()->getType();
11839 if (ME->isArrow())
11840 BaseType = BaseType->getPointeeType();
11841 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11842
11843 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011844 auto *FD = dyn_cast<FieldDecl>(MD);
11845 // We do not care about non-data members.
11846 if (!FD || FD->isInvalidDecl())
11847 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011848
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011849 AnyIsPacked =
11850 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11851 ReverseMemberChain.push_back(FD);
11852
11853 TopME = ME;
11854 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11855 } while (ME);
11856 assert(TopME && "We did not compute a topmost MemberExpr!");
11857
11858 // Not the scope of this diagnostic.
11859 if (!AnyIsPacked)
11860 return;
11861
11862 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11863 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11864 // TODO: The innermost base of the member expression may be too complicated.
11865 // For now, just disregard these cases. This is left for future
11866 // improvement.
11867 if (!DRE && !isa<CXXThisExpr>(TopBase))
11868 return;
11869
11870 // Alignment expected by the whole expression.
11871 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11872
11873 // No need to do anything else with this case.
11874 if (ExpectedAlignment.isOne())
11875 return;
11876
11877 // Synthesize offset of the whole access.
11878 CharUnits Offset;
11879 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11880 I++) {
11881 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11882 }
11883
11884 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11885 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11886 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11887
11888 // The base expression of the innermost MemberExpr may give
11889 // stronger guarantees than the class containing the member.
11890 if (DRE && !TopME->isArrow()) {
11891 const ValueDecl *VD = DRE->getDecl();
11892 if (!VD->getType()->isReferenceType())
11893 CompleteObjectAlignment =
11894 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11895 }
11896
11897 // Check if the synthesized offset fulfills the alignment.
11898 if (Offset % ExpectedAlignment != 0 ||
11899 // It may fulfill the offset it but the effective alignment may still be
11900 // lower than the expected expression alignment.
11901 CompleteObjectAlignment < ExpectedAlignment) {
11902 // If this happens, we want to determine a sensible culprit of this.
11903 // Intuitively, watching the chain of member expressions from right to
11904 // left, we start with the required alignment (as required by the field
11905 // type) but some packed attribute in that chain has reduced the alignment.
11906 // It may happen that another packed structure increases it again. But if
11907 // we are here such increase has not been enough. So pointing the first
11908 // FieldDecl that either is packed or else its RecordDecl is,
11909 // seems reasonable.
11910 FieldDecl *FD = nullptr;
11911 CharUnits Alignment;
11912 for (FieldDecl *FDI : ReverseMemberChain) {
11913 if (FDI->hasAttr<PackedAttr>() ||
11914 FDI->getParent()->hasAttr<PackedAttr>()) {
11915 FD = FDI;
11916 Alignment = std::min(
11917 Context.getTypeAlignInChars(FD->getType()),
11918 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11919 break;
11920 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011921 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011922 assert(FD && "We did not find a packed FieldDecl!");
11923 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011924 }
11925}
11926
11927void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11928 using namespace std::placeholders;
11929 RefersToMemberWithReducedAlignment(
11930 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11931 _2, _3, _4));
11932}
11933