blob: b34a1c146fc1d4540094876d259f12016919333e [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.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000247 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000248 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.
Anastasia Stulova58984e72017-02-16 12:27:47 +0000411 if (Arg2->getType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000412 S.Diag(TheCall->getArg(2)->getLocStart(),
413 diag::err_opencl_enqueue_kernel_expected_type)
Anastasia Stulova58984e72017-02-16 12:27:47 +0000414 << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000415 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;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1629 // These intrinsics take an unsigned 2 bit immediate.
1630 case Mips::BI__builtin_msa_copy_s_w:
1631 case Mips::BI__builtin_msa_copy_u_w:
1632 case Mips::BI__builtin_msa_insve_w:
1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1635 // These intrinsics take an unsigned 1 bit immediate.
1636 case Mips::BI__builtin_msa_copy_s_d:
1637 case Mips::BI__builtin_msa_copy_u_d:
1638 case Mips::BI__builtin_msa_insve_d:
1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1641 // Memory offsets and immediate loads.
1642 // These intrinsics take a signed 10 bit immediate.
1643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1644 case Mips::BI__builtin_msa_ldi_h:
1645 case Mips::BI__builtin_msa_ldi_w:
1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001655 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001656
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001657 if (!m)
1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1659
1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1661 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001662}
1663
Kit Bartone50adcb2015-03-30 19:40:59 +00001664bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1665 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1667 BuiltinID == PPC::BI__builtin_divdeu ||
1668 BuiltinID == PPC::BI__builtin_bpermd;
1669 bool IsTarget64Bit = Context.getTargetInfo()
1670 .getTypeWidth(Context
1671 .getTargetInfo()
1672 .getIntPtrType()) == 64;
1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1674 BuiltinID == PPC::BI__builtin_divweu ||
1675 BuiltinID == PPC::BI__builtin_divde ||
1676 BuiltinID == PPC::BI__builtin_divdeu;
1677
1678 if (Is64BitBltin && !IsTarget64Bit)
1679 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1680 << TheCall->getSourceRange();
1681
1682 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1683 (BuiltinID == PPC::BI__builtin_bpermd &&
1684 !Context.getTargetInfo().hasFeature("bpermd")))
1685 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1686 << TheCall->getSourceRange();
1687
Kit Bartone50adcb2015-03-30 19:40:59 +00001688 switch (BuiltinID) {
1689 default: return false;
1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1691 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1694 case PPC::BI__builtin_tbegin:
1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1697 case PPC::BI__builtin_tabortwc:
1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1699 case PPC::BI__builtin_tabortwci:
1700 case PPC::BI__builtin_tabortdci:
1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1703 }
1704 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1705}
1706
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001707bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1708 CallExpr *TheCall) {
1709 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1710 Expr *Arg = TheCall->getArg(0);
1711 llvm::APSInt AbortCode(32);
1712 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1713 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1714 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1715 << Arg->getSourceRange();
1716 }
1717
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001718 // For intrinsics which take an immediate value as part of the instruction,
1719 // range check them here.
1720 unsigned i = 0, l = 0, u = 0;
1721 switch (BuiltinID) {
1722 default: return false;
1723 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1724 case SystemZ::BI__builtin_s390_verimb:
1725 case SystemZ::BI__builtin_s390_verimh:
1726 case SystemZ::BI__builtin_s390_verimf:
1727 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1728 case SystemZ::BI__builtin_s390_vfaeb:
1729 case SystemZ::BI__builtin_s390_vfaeh:
1730 case SystemZ::BI__builtin_s390_vfaef:
1731 case SystemZ::BI__builtin_s390_vfaebs:
1732 case SystemZ::BI__builtin_s390_vfaehs:
1733 case SystemZ::BI__builtin_s390_vfaefs:
1734 case SystemZ::BI__builtin_s390_vfaezb:
1735 case SystemZ::BI__builtin_s390_vfaezh:
1736 case SystemZ::BI__builtin_s390_vfaezf:
1737 case SystemZ::BI__builtin_s390_vfaezbs:
1738 case SystemZ::BI__builtin_s390_vfaezhs:
1739 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1740 case SystemZ::BI__builtin_s390_vfidb:
1741 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1742 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1743 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1744 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1745 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1746 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1747 case SystemZ::BI__builtin_s390_vstrcb:
1748 case SystemZ::BI__builtin_s390_vstrch:
1749 case SystemZ::BI__builtin_s390_vstrcf:
1750 case SystemZ::BI__builtin_s390_vstrczb:
1751 case SystemZ::BI__builtin_s390_vstrczh:
1752 case SystemZ::BI__builtin_s390_vstrczf:
1753 case SystemZ::BI__builtin_s390_vstrcbs:
1754 case SystemZ::BI__builtin_s390_vstrchs:
1755 case SystemZ::BI__builtin_s390_vstrcfs:
1756 case SystemZ::BI__builtin_s390_vstrczbs:
1757 case SystemZ::BI__builtin_s390_vstrczhs:
1758 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1759 }
1760 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001761}
1762
Craig Topper5ba2c502015-11-07 08:08:31 +00001763/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1764/// This checks that the target supports __builtin_cpu_supports and
1765/// that the string argument is constant and valid.
1766static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1767 Expr *Arg = TheCall->getArg(0);
1768
1769 // Check if the argument is a string literal.
1770 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1771 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1772 << Arg->getSourceRange();
1773
1774 // Check the contents of the string.
1775 StringRef Feature =
1776 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1777 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1778 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1779 << Arg->getSourceRange();
1780 return false;
1781}
1782
Craig Toppera7e253e2016-09-23 04:48:31 +00001783// Check if the rounding mode is legal.
1784bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1785 // Indicates if this instruction has rounding control or just SAE.
1786 bool HasRC = false;
1787
1788 unsigned ArgNum = 0;
1789 switch (BuiltinID) {
1790 default:
1791 return false;
1792 case X86::BI__builtin_ia32_vcvttsd2si32:
1793 case X86::BI__builtin_ia32_vcvttsd2si64:
1794 case X86::BI__builtin_ia32_vcvttsd2usi32:
1795 case X86::BI__builtin_ia32_vcvttsd2usi64:
1796 case X86::BI__builtin_ia32_vcvttss2si32:
1797 case X86::BI__builtin_ia32_vcvttss2si64:
1798 case X86::BI__builtin_ia32_vcvttss2usi32:
1799 case X86::BI__builtin_ia32_vcvttss2usi64:
1800 ArgNum = 1;
1801 break;
1802 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1803 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1804 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1805 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1807 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1808 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1809 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1811 case X86::BI__builtin_ia32_exp2pd_mask:
1812 case X86::BI__builtin_ia32_exp2ps_mask:
1813 case X86::BI__builtin_ia32_getexppd512_mask:
1814 case X86::BI__builtin_ia32_getexpps512_mask:
1815 case X86::BI__builtin_ia32_rcp28pd_mask:
1816 case X86::BI__builtin_ia32_rcp28ps_mask:
1817 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1818 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1819 case X86::BI__builtin_ia32_vcomisd:
1820 case X86::BI__builtin_ia32_vcomiss:
1821 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1822 ArgNum = 3;
1823 break;
1824 case X86::BI__builtin_ia32_cmppd512_mask:
1825 case X86::BI__builtin_ia32_cmpps512_mask:
1826 case X86::BI__builtin_ia32_cmpsd_mask:
1827 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001828 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001829 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1830 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001831 case X86::BI__builtin_ia32_maxpd512_mask:
1832 case X86::BI__builtin_ia32_maxps512_mask:
1833 case X86::BI__builtin_ia32_maxsd_round_mask:
1834 case X86::BI__builtin_ia32_maxss_round_mask:
1835 case X86::BI__builtin_ia32_minpd512_mask:
1836 case X86::BI__builtin_ia32_minps512_mask:
1837 case X86::BI__builtin_ia32_minsd_round_mask:
1838 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001839 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1840 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1841 case X86::BI__builtin_ia32_reducepd512_mask:
1842 case X86::BI__builtin_ia32_reduceps512_mask:
1843 case X86::BI__builtin_ia32_rndscalepd_mask:
1844 case X86::BI__builtin_ia32_rndscaleps_mask:
1845 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1846 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1847 ArgNum = 4;
1848 break;
1849 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001850 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001851 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001852 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001853 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001857 case X86::BI__builtin_ia32_rangepd512_mask:
1858 case X86::BI__builtin_ia32_rangeps512_mask:
1859 case X86::BI__builtin_ia32_rangesd128_round_mask:
1860 case X86::BI__builtin_ia32_rangess128_round_mask:
1861 case X86::BI__builtin_ia32_reducesd_mask:
1862 case X86::BI__builtin_ia32_reducess_mask:
1863 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1864 case X86::BI__builtin_ia32_rndscaless_round_mask:
1865 ArgNum = 5;
1866 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001867 case X86::BI__builtin_ia32_vcvtsd2si64:
1868 case X86::BI__builtin_ia32_vcvtsd2si32:
1869 case X86::BI__builtin_ia32_vcvtsd2usi32:
1870 case X86::BI__builtin_ia32_vcvtsd2usi64:
1871 case X86::BI__builtin_ia32_vcvtss2si32:
1872 case X86::BI__builtin_ia32_vcvtss2si64:
1873 case X86::BI__builtin_ia32_vcvtss2usi32:
1874 case X86::BI__builtin_ia32_vcvtss2usi64:
1875 ArgNum = 1;
1876 HasRC = true;
1877 break;
Craig Topper8e066312016-11-07 07:01:09 +00001878 case X86::BI__builtin_ia32_cvtsi2sd64:
1879 case X86::BI__builtin_ia32_cvtsi2ss32:
1880 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001881 case X86::BI__builtin_ia32_cvtusi2sd64:
1882 case X86::BI__builtin_ia32_cvtusi2ss32:
1883 case X86::BI__builtin_ia32_cvtusi2ss64:
1884 ArgNum = 2;
1885 HasRC = true;
1886 break;
1887 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1888 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1889 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1890 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1891 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1892 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1893 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1894 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1895 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1896 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1897 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001898 case X86::BI__builtin_ia32_sqrtpd512_mask:
1899 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001900 ArgNum = 3;
1901 HasRC = true;
1902 break;
1903 case X86::BI__builtin_ia32_addpd512_mask:
1904 case X86::BI__builtin_ia32_addps512_mask:
1905 case X86::BI__builtin_ia32_divpd512_mask:
1906 case X86::BI__builtin_ia32_divps512_mask:
1907 case X86::BI__builtin_ia32_mulpd512_mask:
1908 case X86::BI__builtin_ia32_mulps512_mask:
1909 case X86::BI__builtin_ia32_subpd512_mask:
1910 case X86::BI__builtin_ia32_subps512_mask:
1911 case X86::BI__builtin_ia32_addss_round_mask:
1912 case X86::BI__builtin_ia32_addsd_round_mask:
1913 case X86::BI__builtin_ia32_divss_round_mask:
1914 case X86::BI__builtin_ia32_divsd_round_mask:
1915 case X86::BI__builtin_ia32_mulss_round_mask:
1916 case X86::BI__builtin_ia32_mulsd_round_mask:
1917 case X86::BI__builtin_ia32_subss_round_mask:
1918 case X86::BI__builtin_ia32_subsd_round_mask:
1919 case X86::BI__builtin_ia32_scalefpd512_mask:
1920 case X86::BI__builtin_ia32_scalefps512_mask:
1921 case X86::BI__builtin_ia32_scalefsd_round_mask:
1922 case X86::BI__builtin_ia32_scalefss_round_mask:
1923 case X86::BI__builtin_ia32_getmantpd512_mask:
1924 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001925 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1926 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1927 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001928 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1929 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1930 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1931 case X86::BI__builtin_ia32_vfmaddps512_mask:
1932 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1933 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1934 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1935 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1936 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1937 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1938 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1940 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1941 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1942 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1943 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1944 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1945 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1946 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1947 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1948 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1950 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1951 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1952 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1953 case X86::BI__builtin_ia32_vfmaddss3_mask:
1954 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1955 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1956 ArgNum = 4;
1957 HasRC = true;
1958 break;
1959 case X86::BI__builtin_ia32_getmantsd_round_mask:
1960 case X86::BI__builtin_ia32_getmantss_round_mask:
1961 ArgNum = 5;
1962 HasRC = true;
1963 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001964 }
1965
1966 llvm::APSInt Result;
1967
1968 // We can't check the value of a dependent argument.
1969 Expr *Arg = TheCall->getArg(ArgNum);
1970 if (Arg->isTypeDependent() || Arg->isValueDependent())
1971 return false;
1972
1973 // Check constant-ness first.
1974 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1975 return true;
1976
1977 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1978 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1979 // combined with ROUND_NO_EXC.
1980 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1981 Result == 8/*ROUND_NO_EXC*/ ||
1982 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1983 return false;
1984
1985 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1986 << Arg->getSourceRange();
1987}
1988
Craig Topperf0ddc892016-09-23 04:48:27 +00001989bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1990 if (BuiltinID == X86::BI__builtin_cpu_supports)
1991 return SemaBuiltinCpuSupports(*this, TheCall);
1992
1993 if (BuiltinID == X86::BI__builtin_ms_va_start)
1994 return SemaBuiltinMSVAStart(TheCall);
1995
Craig Toppera7e253e2016-09-23 04:48:31 +00001996 // If the intrinsic has rounding or SAE make sure its valid.
1997 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1998 return true;
1999
Craig Topperf0ddc892016-09-23 04:48:27 +00002000 // For intrinsics which take an immediate value as part of the instruction,
2001 // range check them here.
2002 int i = 0, l = 0, u = 0;
2003 switch (BuiltinID) {
2004 default:
2005 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002006 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002007 i = 1; l = 0; u = 3;
2008 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002009 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002010 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2011 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2012 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2013 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002014 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002015 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002016 case X86::BI__builtin_ia32_vpermil2pd:
2017 case X86::BI__builtin_ia32_vpermil2pd256:
2018 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002019 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002020 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002021 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002022 case X86::BI__builtin_ia32_cmpb128_mask:
2023 case X86::BI__builtin_ia32_cmpw128_mask:
2024 case X86::BI__builtin_ia32_cmpd128_mask:
2025 case X86::BI__builtin_ia32_cmpq128_mask:
2026 case X86::BI__builtin_ia32_cmpb256_mask:
2027 case X86::BI__builtin_ia32_cmpw256_mask:
2028 case X86::BI__builtin_ia32_cmpd256_mask:
2029 case X86::BI__builtin_ia32_cmpq256_mask:
2030 case X86::BI__builtin_ia32_cmpb512_mask:
2031 case X86::BI__builtin_ia32_cmpw512_mask:
2032 case X86::BI__builtin_ia32_cmpd512_mask:
2033 case X86::BI__builtin_ia32_cmpq512_mask:
2034 case X86::BI__builtin_ia32_ucmpb128_mask:
2035 case X86::BI__builtin_ia32_ucmpw128_mask:
2036 case X86::BI__builtin_ia32_ucmpd128_mask:
2037 case X86::BI__builtin_ia32_ucmpq128_mask:
2038 case X86::BI__builtin_ia32_ucmpb256_mask:
2039 case X86::BI__builtin_ia32_ucmpw256_mask:
2040 case X86::BI__builtin_ia32_ucmpd256_mask:
2041 case X86::BI__builtin_ia32_ucmpq256_mask:
2042 case X86::BI__builtin_ia32_ucmpb512_mask:
2043 case X86::BI__builtin_ia32_ucmpw512_mask:
2044 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002045 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002046 case X86::BI__builtin_ia32_vpcomub:
2047 case X86::BI__builtin_ia32_vpcomuw:
2048 case X86::BI__builtin_ia32_vpcomud:
2049 case X86::BI__builtin_ia32_vpcomuq:
2050 case X86::BI__builtin_ia32_vpcomb:
2051 case X86::BI__builtin_ia32_vpcomw:
2052 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002053 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002054 i = 2; l = 0; u = 7;
2055 break;
2056 case X86::BI__builtin_ia32_roundps:
2057 case X86::BI__builtin_ia32_roundpd:
2058 case X86::BI__builtin_ia32_roundps256:
2059 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002060 i = 1; l = 0; u = 15;
2061 break;
2062 case X86::BI__builtin_ia32_roundss:
2063 case X86::BI__builtin_ia32_roundsd:
2064 case X86::BI__builtin_ia32_rangepd128_mask:
2065 case X86::BI__builtin_ia32_rangepd256_mask:
2066 case X86::BI__builtin_ia32_rangepd512_mask:
2067 case X86::BI__builtin_ia32_rangeps128_mask:
2068 case X86::BI__builtin_ia32_rangeps256_mask:
2069 case X86::BI__builtin_ia32_rangeps512_mask:
2070 case X86::BI__builtin_ia32_getmantsd_round_mask:
2071 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002072 i = 2; l = 0; u = 15;
2073 break;
2074 case X86::BI__builtin_ia32_cmpps:
2075 case X86::BI__builtin_ia32_cmpss:
2076 case X86::BI__builtin_ia32_cmppd:
2077 case X86::BI__builtin_ia32_cmpsd:
2078 case X86::BI__builtin_ia32_cmpps256:
2079 case X86::BI__builtin_ia32_cmppd256:
2080 case X86::BI__builtin_ia32_cmpps128_mask:
2081 case X86::BI__builtin_ia32_cmppd128_mask:
2082 case X86::BI__builtin_ia32_cmpps256_mask:
2083 case X86::BI__builtin_ia32_cmppd256_mask:
2084 case X86::BI__builtin_ia32_cmpps512_mask:
2085 case X86::BI__builtin_ia32_cmppd512_mask:
2086 case X86::BI__builtin_ia32_cmpsd_mask:
2087 case X86::BI__builtin_ia32_cmpss_mask:
2088 i = 2; l = 0; u = 31;
2089 break;
2090 case X86::BI__builtin_ia32_xabort:
2091 i = 0; l = -128; u = 255;
2092 break;
2093 case X86::BI__builtin_ia32_pshufw:
2094 case X86::BI__builtin_ia32_aeskeygenassist128:
2095 i = 1; l = -128; u = 255;
2096 break;
2097 case X86::BI__builtin_ia32_vcvtps2ph:
2098 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002099 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2100 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2101 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2102 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2103 case X86::BI__builtin_ia32_rndscaleps_mask:
2104 case X86::BI__builtin_ia32_rndscalepd_mask:
2105 case X86::BI__builtin_ia32_reducepd128_mask:
2106 case X86::BI__builtin_ia32_reducepd256_mask:
2107 case X86::BI__builtin_ia32_reducepd512_mask:
2108 case X86::BI__builtin_ia32_reduceps128_mask:
2109 case X86::BI__builtin_ia32_reduceps256_mask:
2110 case X86::BI__builtin_ia32_reduceps512_mask:
2111 case X86::BI__builtin_ia32_prold512_mask:
2112 case X86::BI__builtin_ia32_prolq512_mask:
2113 case X86::BI__builtin_ia32_prold128_mask:
2114 case X86::BI__builtin_ia32_prold256_mask:
2115 case X86::BI__builtin_ia32_prolq128_mask:
2116 case X86::BI__builtin_ia32_prolq256_mask:
2117 case X86::BI__builtin_ia32_prord128_mask:
2118 case X86::BI__builtin_ia32_prord256_mask:
2119 case X86::BI__builtin_ia32_prorq128_mask:
2120 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002121 case X86::BI__builtin_ia32_fpclasspd128_mask:
2122 case X86::BI__builtin_ia32_fpclasspd256_mask:
2123 case X86::BI__builtin_ia32_fpclassps128_mask:
2124 case X86::BI__builtin_ia32_fpclassps256_mask:
2125 case X86::BI__builtin_ia32_fpclassps512_mask:
2126 case X86::BI__builtin_ia32_fpclasspd512_mask:
2127 case X86::BI__builtin_ia32_fpclasssd_mask:
2128 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002129 i = 1; l = 0; u = 255;
2130 break;
2131 case X86::BI__builtin_ia32_palignr:
2132 case X86::BI__builtin_ia32_insertps128:
2133 case X86::BI__builtin_ia32_dpps:
2134 case X86::BI__builtin_ia32_dppd:
2135 case X86::BI__builtin_ia32_dpps256:
2136 case X86::BI__builtin_ia32_mpsadbw128:
2137 case X86::BI__builtin_ia32_mpsadbw256:
2138 case X86::BI__builtin_ia32_pcmpistrm128:
2139 case X86::BI__builtin_ia32_pcmpistri128:
2140 case X86::BI__builtin_ia32_pcmpistria128:
2141 case X86::BI__builtin_ia32_pcmpistric128:
2142 case X86::BI__builtin_ia32_pcmpistrio128:
2143 case X86::BI__builtin_ia32_pcmpistris128:
2144 case X86::BI__builtin_ia32_pcmpistriz128:
2145 case X86::BI__builtin_ia32_pclmulqdq128:
2146 case X86::BI__builtin_ia32_vperm2f128_pd256:
2147 case X86::BI__builtin_ia32_vperm2f128_ps256:
2148 case X86::BI__builtin_ia32_vperm2f128_si256:
2149 case X86::BI__builtin_ia32_permti256:
2150 i = 2; l = -128; u = 255;
2151 break;
2152 case X86::BI__builtin_ia32_palignr128:
2153 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002154 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002155 case X86::BI__builtin_ia32_vcomisd:
2156 case X86::BI__builtin_ia32_vcomiss:
2157 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2158 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2159 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2160 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002161 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2162 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2163 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2164 i = 2; l = 0; u = 255;
2165 break;
2166 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2167 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2168 case X86::BI__builtin_ia32_fixupimmps512_mask:
2169 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2170 case X86::BI__builtin_ia32_fixupimmsd_mask:
2171 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2172 case X86::BI__builtin_ia32_fixupimmss_mask:
2173 case X86::BI__builtin_ia32_fixupimmss_maskz:
2174 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2175 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2176 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2177 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2178 case X86::BI__builtin_ia32_fixupimmps128_mask:
2179 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2180 case X86::BI__builtin_ia32_fixupimmps256_mask:
2181 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2182 case X86::BI__builtin_ia32_pternlogd512_mask:
2183 case X86::BI__builtin_ia32_pternlogd512_maskz:
2184 case X86::BI__builtin_ia32_pternlogq512_mask:
2185 case X86::BI__builtin_ia32_pternlogq512_maskz:
2186 case X86::BI__builtin_ia32_pternlogd128_mask:
2187 case X86::BI__builtin_ia32_pternlogd128_maskz:
2188 case X86::BI__builtin_ia32_pternlogd256_mask:
2189 case X86::BI__builtin_ia32_pternlogd256_maskz:
2190 case X86::BI__builtin_ia32_pternlogq128_mask:
2191 case X86::BI__builtin_ia32_pternlogq128_maskz:
2192 case X86::BI__builtin_ia32_pternlogq256_mask:
2193 case X86::BI__builtin_ia32_pternlogq256_maskz:
2194 i = 3; l = 0; u = 255;
2195 break;
Craig Topper9625db02017-03-12 22:19:10 +00002196 case X86::BI__builtin_ia32_gatherpfdpd:
2197 case X86::BI__builtin_ia32_gatherpfdps:
2198 case X86::BI__builtin_ia32_gatherpfqpd:
2199 case X86::BI__builtin_ia32_gatherpfqps:
2200 case X86::BI__builtin_ia32_scatterpfdpd:
2201 case X86::BI__builtin_ia32_scatterpfdps:
2202 case X86::BI__builtin_ia32_scatterpfqpd:
2203 case X86::BI__builtin_ia32_scatterpfqps:
2204 i = 4; l = 1; u = 2;
2205 break;
Craig Topper39c87102016-05-18 03:18:12 +00002206 case X86::BI__builtin_ia32_pcmpestrm128:
2207 case X86::BI__builtin_ia32_pcmpestri128:
2208 case X86::BI__builtin_ia32_pcmpestria128:
2209 case X86::BI__builtin_ia32_pcmpestric128:
2210 case X86::BI__builtin_ia32_pcmpestrio128:
2211 case X86::BI__builtin_ia32_pcmpestris128:
2212 case X86::BI__builtin_ia32_pcmpestriz128:
2213 i = 4; l = -128; u = 255;
2214 break;
2215 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2216 case X86::BI__builtin_ia32_rndscaless_round_mask:
2217 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002218 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002219 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002220 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002221}
2222
Richard Smith55ce3522012-06-25 20:30:08 +00002223/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2224/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2225/// Returns true when the format fits the function and the FormatStringInfo has
2226/// been populated.
2227bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2228 FormatStringInfo *FSI) {
2229 FSI->HasVAListArg = Format->getFirstArg() == 0;
2230 FSI->FormatIdx = Format->getFormatIdx() - 1;
2231 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002232
Richard Smith55ce3522012-06-25 20:30:08 +00002233 // The way the format attribute works in GCC, the implicit this argument
2234 // of member functions is counted. However, it doesn't appear in our own
2235 // lists, so decrement format_idx in that case.
2236 if (IsCXXMember) {
2237 if(FSI->FormatIdx == 0)
2238 return false;
2239 --FSI->FormatIdx;
2240 if (FSI->FirstDataArg != 0)
2241 --FSI->FirstDataArg;
2242 }
2243 return true;
2244}
Mike Stump11289f42009-09-09 15:08:12 +00002245
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002246/// Checks if a the given expression evaluates to null.
2247///
2248/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002249static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002250 // If the expression has non-null type, it doesn't evaluate to null.
2251 if (auto nullability
2252 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2253 if (*nullability == NullabilityKind::NonNull)
2254 return false;
2255 }
2256
Ted Kremeneka146db32014-01-17 06:24:47 +00002257 // As a special case, transparent unions initialized with zero are
2258 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002259 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002260 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2261 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002262 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002263 if (const InitListExpr *ILE =
2264 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002265 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002266 }
2267
2268 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002269 return (!Expr->isValueDependent() &&
2270 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2271 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002272}
2273
2274static void CheckNonNullArgument(Sema &S,
2275 const Expr *ArgExpr,
2276 SourceLocation CallSiteLoc) {
2277 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002278 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2279 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002280}
2281
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002282bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2283 FormatStringInfo FSI;
2284 if ((GetFormatStringType(Format) == FST_NSString) &&
2285 getFormatStringInfo(Format, false, &FSI)) {
2286 Idx = FSI.FormatIdx;
2287 return true;
2288 }
2289 return false;
2290}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002291/// \brief Diagnose use of %s directive in an NSString which is being passed
2292/// as formatting string to formatting method.
2293static void
2294DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2295 const NamedDecl *FDecl,
2296 Expr **Args,
2297 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002298 unsigned Idx = 0;
2299 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002300 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2301 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002302 Idx = 2;
2303 Format = true;
2304 }
2305 else
2306 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2307 if (S.GetFormatNSStringIdx(I, Idx)) {
2308 Format = true;
2309 break;
2310 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002311 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002312 if (!Format || NumArgs <= Idx)
2313 return;
2314 const Expr *FormatExpr = Args[Idx];
2315 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2316 FormatExpr = CSCE->getSubExpr();
2317 const StringLiteral *FormatString;
2318 if (const ObjCStringLiteral *OSL =
2319 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2320 FormatString = OSL->getString();
2321 else
2322 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2323 if (!FormatString)
2324 return;
2325 if (S.FormatStringHasSArg(FormatString)) {
2326 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2327 << "%s" << 1 << 1;
2328 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2329 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002330 }
2331}
2332
Douglas Gregorb4866e82015-06-19 18:13:19 +00002333/// Determine whether the given type has a non-null nullability annotation.
2334static bool isNonNullType(ASTContext &ctx, QualType type) {
2335 if (auto nullability = type->getNullability(ctx))
2336 return *nullability == NullabilityKind::NonNull;
2337
2338 return false;
2339}
2340
Ted Kremenek2bc73332014-01-17 06:24:43 +00002341static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002342 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002343 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002344 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002345 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002346 assert((FDecl || Proto) && "Need a function declaration or prototype");
2347
Ted Kremenek9aedc152014-01-17 06:24:56 +00002348 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002349 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002350 if (FDecl) {
2351 // Handle the nonnull attribute on the function/method declaration itself.
2352 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2353 if (!NonNull->args_size()) {
2354 // Easy case: all pointer arguments are nonnull.
2355 for (const auto *Arg : Args)
2356 if (S.isValidPointerAttrType(Arg->getType()))
2357 CheckNonNullArgument(S, Arg, CallSiteLoc);
2358 return;
2359 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002360
Douglas Gregorb4866e82015-06-19 18:13:19 +00002361 for (unsigned Val : NonNull->args()) {
2362 if (Val >= Args.size())
2363 continue;
2364 if (NonNullArgs.empty())
2365 NonNullArgs.resize(Args.size());
2366 NonNullArgs.set(Val);
2367 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002368 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002369 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002370
Douglas Gregorb4866e82015-06-19 18:13:19 +00002371 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2372 // Handle the nonnull attribute on the parameters of the
2373 // function/method.
2374 ArrayRef<ParmVarDecl*> parms;
2375 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2376 parms = FD->parameters();
2377 else
2378 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2379
2380 unsigned ParamIndex = 0;
2381 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2382 I != E; ++I, ++ParamIndex) {
2383 const ParmVarDecl *PVD = *I;
2384 if (PVD->hasAttr<NonNullAttr>() ||
2385 isNonNullType(S.Context, PVD->getType())) {
2386 if (NonNullArgs.empty())
2387 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002388
Douglas Gregorb4866e82015-06-19 18:13:19 +00002389 NonNullArgs.set(ParamIndex);
2390 }
2391 }
2392 } else {
2393 // If we have a non-function, non-method declaration but no
2394 // function prototype, try to dig out the function prototype.
2395 if (!Proto) {
2396 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2397 QualType type = VD->getType().getNonReferenceType();
2398 if (auto pointerType = type->getAs<PointerType>())
2399 type = pointerType->getPointeeType();
2400 else if (auto blockType = type->getAs<BlockPointerType>())
2401 type = blockType->getPointeeType();
2402 // FIXME: data member pointers?
2403
2404 // Dig out the function prototype, if there is one.
2405 Proto = type->getAs<FunctionProtoType>();
2406 }
2407 }
2408
2409 // Fill in non-null argument information from the nullability
2410 // information on the parameter types (if we have them).
2411 if (Proto) {
2412 unsigned Index = 0;
2413 for (auto paramType : Proto->getParamTypes()) {
2414 if (isNonNullType(S.Context, paramType)) {
2415 if (NonNullArgs.empty())
2416 NonNullArgs.resize(Args.size());
2417
2418 NonNullArgs.set(Index);
2419 }
2420
2421 ++Index;
2422 }
2423 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002424 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002425
Douglas Gregorb4866e82015-06-19 18:13:19 +00002426 // Check for non-null arguments.
2427 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2428 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002429 if (NonNullArgs[ArgIndex])
2430 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002431 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002432}
2433
Richard Smith55ce3522012-06-25 20:30:08 +00002434/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002435/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2436/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002437void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002438 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2439 bool IsMemberFunction, SourceLocation Loc,
2440 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002441 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002442 if (CurContext->isDependentContext())
2443 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002444
Ted Kremenekb8176da2010-09-09 04:33:05 +00002445 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002446 llvm::SmallBitVector CheckedVarArgs;
2447 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002448 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002449 // Only create vector if there are format attributes.
2450 CheckedVarArgs.resize(Args.size());
2451
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002452 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002453 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002454 }
Richard Smithd7293d72013-08-05 18:49:43 +00002455 }
Richard Smith55ce3522012-06-25 20:30:08 +00002456
2457 // Refuse POD arguments that weren't caught by the format string
2458 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002459 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2460 if (CallType != VariadicDoesNotApply &&
2461 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002462 unsigned NumParams = Proto ? Proto->getNumParams()
2463 : FDecl && isa<FunctionDecl>(FDecl)
2464 ? cast<FunctionDecl>(FDecl)->getNumParams()
2465 : FDecl && isa<ObjCMethodDecl>(FDecl)
2466 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2467 : 0;
2468
Alp Toker9cacbab2014-01-20 20:26:09 +00002469 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002470 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002471 if (const Expr *Arg = Args[ArgIdx]) {
2472 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2473 checkVariadicArgument(Arg, CallType);
2474 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002475 }
Richard Smithd7293d72013-08-05 18:49:43 +00002476 }
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregorb4866e82015-06-19 18:13:19 +00002478 if (FDecl || Proto) {
2479 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002480
Richard Trieu41bc0992013-06-22 00:20:41 +00002481 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002482 if (FDecl) {
2483 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2484 CheckArgumentWithTypeTag(I, Args.data());
2485 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002486 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002487
2488 if (FD)
2489 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002490}
2491
2492/// CheckConstructorCall - Check a constructor call for correctness and safety
2493/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002494void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2495 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002496 const FunctionProtoType *Proto,
2497 SourceLocation Loc) {
2498 VariadicCallType CallType =
2499 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002500 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2501 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002502}
2503
2504/// CheckFunctionCall - Check a direct function call for various correctness
2505/// and safety properties not strictly enforced by the C type system.
2506bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2507 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002508 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2509 isa<CXXMethodDecl>(FDecl);
2510 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2511 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002512 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2513 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002514 Expr** Args = TheCall->getArgs();
2515 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002516
2517 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002518 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002519 // If this is a call to a member operator, hide the first argument
2520 // from checkCall.
2521 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002522 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002523 ++Args;
2524 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002525 } else if (IsMemberFunction)
2526 ImplicitThis =
2527 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2528
2529 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002530 IsMemberFunction, TheCall->getRParenLoc(),
2531 TheCall->getCallee()->getSourceRange(), CallType);
2532
2533 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2534 // None of the checks below are needed for functions that don't have
2535 // simple names (e.g., C++ conversion functions).
2536 if (!FnInfo)
2537 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002538
Richard Trieua7f30b12016-12-06 01:42:28 +00002539 CheckAbsoluteValueFunction(TheCall, FDecl);
2540 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002541
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002542 if (getLangOpts().ObjC1)
2543 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002544
Anna Zaks22122702012-01-17 00:37:07 +00002545 unsigned CMId = FDecl->getMemoryFunctionKind();
2546 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002547 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002548
Anna Zaks201d4892012-01-13 21:52:01 +00002549 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002550 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002551 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002552 else if (CMId == Builtin::BIstrncat)
2553 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002554 else
Anna Zaks22122702012-01-17 00:37:07 +00002555 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002556
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002557 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002558}
2559
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002560bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002561 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002562 VariadicCallType CallType =
2563 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002564
George Burgess IVce6284b2017-01-28 02:19:40 +00002565 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2566 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002567 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002568
2569 return false;
2570}
2571
Richard Trieu664c4c62013-06-20 21:03:13 +00002572bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2573 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002574 QualType Ty;
2575 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002576 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002577 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002578 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002579 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002580 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002581
Douglas Gregorb4866e82015-06-19 18:13:19 +00002582 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2583 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002584 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002585
Richard Trieu664c4c62013-06-20 21:03:13 +00002586 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002587 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002588 CallType = VariadicDoesNotApply;
2589 } else if (Ty->isBlockPointerType()) {
2590 CallType = VariadicBlock;
2591 } else { // Ty->isFunctionPointerType()
2592 CallType = VariadicFunction;
2593 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002594
George Burgess IVce6284b2017-01-28 02:19:40 +00002595 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002596 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2597 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002598 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002599
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002600 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002601}
2602
Richard Trieu41bc0992013-06-22 00:20:41 +00002603/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2604/// such as function pointers returned from functions.
2605bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002606 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002607 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002608 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002609 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002610 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002611 TheCall->getCallee()->getSourceRange(), CallType);
2612
2613 return false;
2614}
2615
Tim Northovere94a34c2014-03-11 10:49:14 +00002616static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002617 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002618 return false;
2619
JF Bastiendda2cb12016-04-18 18:01:49 +00002620 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002621 switch (Op) {
2622 case AtomicExpr::AO__c11_atomic_init:
2623 llvm_unreachable("There is no ordering argument for an init");
2624
2625 case AtomicExpr::AO__c11_atomic_load:
2626 case AtomicExpr::AO__atomic_load_n:
2627 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002628 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2629 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002630
2631 case AtomicExpr::AO__c11_atomic_store:
2632 case AtomicExpr::AO__atomic_store:
2633 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002634 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2635 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2636 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002637
2638 default:
2639 return true;
2640 }
2641}
2642
Richard Smithfeea8832012-04-12 05:08:17 +00002643ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2644 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002645 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2646 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002647
Richard Smithfeea8832012-04-12 05:08:17 +00002648 // All these operations take one of the following forms:
2649 enum {
2650 // C __c11_atomic_init(A *, C)
2651 Init,
2652 // C __c11_atomic_load(A *, int)
2653 Load,
2654 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002655 LoadCopy,
2656 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002657 Copy,
2658 // C __c11_atomic_add(A *, M, int)
2659 Arithmetic,
2660 // C __atomic_exchange_n(A *, CP, int)
2661 Xchg,
2662 // void __atomic_exchange(A *, C *, CP, int)
2663 GNUXchg,
2664 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2665 C11CmpXchg,
2666 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2667 GNUCmpXchg
2668 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002669 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2670 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002671 // where:
2672 // C is an appropriate type,
2673 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2674 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2675 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2676 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002677
Gabor Horvath98bd0982015-03-16 09:59:54 +00002678 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2679 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2680 AtomicExpr::AO__atomic_load,
2681 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002682 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2683 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2684 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2685 Op == AtomicExpr::AO__atomic_store_n ||
2686 Op == AtomicExpr::AO__atomic_exchange_n ||
2687 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2688 bool IsAddSub = false;
2689
2690 switch (Op) {
2691 case AtomicExpr::AO__c11_atomic_init:
2692 Form = Init;
2693 break;
2694
2695 case AtomicExpr::AO__c11_atomic_load:
2696 case AtomicExpr::AO__atomic_load_n:
2697 Form = Load;
2698 break;
2699
Richard Smithfeea8832012-04-12 05:08:17 +00002700 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002701 Form = LoadCopy;
2702 break;
2703
2704 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002705 case AtomicExpr::AO__atomic_store:
2706 case AtomicExpr::AO__atomic_store_n:
2707 Form = Copy;
2708 break;
2709
2710 case AtomicExpr::AO__c11_atomic_fetch_add:
2711 case AtomicExpr::AO__c11_atomic_fetch_sub:
2712 case AtomicExpr::AO__atomic_fetch_add:
2713 case AtomicExpr::AO__atomic_fetch_sub:
2714 case AtomicExpr::AO__atomic_add_fetch:
2715 case AtomicExpr::AO__atomic_sub_fetch:
2716 IsAddSub = true;
2717 // Fall through.
2718 case AtomicExpr::AO__c11_atomic_fetch_and:
2719 case AtomicExpr::AO__c11_atomic_fetch_or:
2720 case AtomicExpr::AO__c11_atomic_fetch_xor:
2721 case AtomicExpr::AO__atomic_fetch_and:
2722 case AtomicExpr::AO__atomic_fetch_or:
2723 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002724 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002725 case AtomicExpr::AO__atomic_and_fetch:
2726 case AtomicExpr::AO__atomic_or_fetch:
2727 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002728 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002729 Form = Arithmetic;
2730 break;
2731
2732 case AtomicExpr::AO__c11_atomic_exchange:
2733 case AtomicExpr::AO__atomic_exchange_n:
2734 Form = Xchg;
2735 break;
2736
2737 case AtomicExpr::AO__atomic_exchange:
2738 Form = GNUXchg;
2739 break;
2740
2741 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2742 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2743 Form = C11CmpXchg;
2744 break;
2745
2746 case AtomicExpr::AO__atomic_compare_exchange:
2747 case AtomicExpr::AO__atomic_compare_exchange_n:
2748 Form = GNUCmpXchg;
2749 break;
2750 }
2751
2752 // Check we have the right number of arguments.
2753 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002754 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002755 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002756 << TheCall->getCallee()->getSourceRange();
2757 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002758 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2759 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002760 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002761 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002762 << TheCall->getCallee()->getSourceRange();
2763 return ExprError();
2764 }
2765
Richard Smithfeea8832012-04-12 05:08:17 +00002766 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002767 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002768 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2769 if (ConvertedPtr.isInvalid())
2770 return ExprError();
2771
2772 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002773 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2774 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002775 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002776 << Ptr->getType() << Ptr->getSourceRange();
2777 return ExprError();
2778 }
2779
Richard Smithfeea8832012-04-12 05:08:17 +00002780 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2781 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2782 QualType ValType = AtomTy; // 'C'
2783 if (IsC11) {
2784 if (!AtomTy->isAtomicType()) {
2785 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2786 << Ptr->getType() << Ptr->getSourceRange();
2787 return ExprError();
2788 }
Richard Smithe00921a2012-09-15 06:09:58 +00002789 if (AtomTy.isConstQualified()) {
2790 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2791 << Ptr->getType() << Ptr->getSourceRange();
2792 return ExprError();
2793 }
Richard Smithfeea8832012-04-12 05:08:17 +00002794 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002795 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002796 if (ValType.isConstQualified()) {
2797 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2798 << Ptr->getType() << Ptr->getSourceRange();
2799 return ExprError();
2800 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002801 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002802
Richard Smithfeea8832012-04-12 05:08:17 +00002803 // For an arithmetic operation, the implied arithmetic must be well-formed.
2804 if (Form == Arithmetic) {
2805 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2806 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2807 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2808 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2809 return ExprError();
2810 }
2811 if (!IsAddSub && !ValType->isIntegerType()) {
2812 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2813 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2814 return ExprError();
2815 }
David Majnemere85cff82015-01-28 05:48:06 +00002816 if (IsC11 && ValType->isPointerType() &&
2817 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2818 diag::err_incomplete_type)) {
2819 return ExprError();
2820 }
Richard Smithfeea8832012-04-12 05:08:17 +00002821 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2822 // For __atomic_*_n operations, the value type must be a scalar integral or
2823 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002824 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002825 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2826 return ExprError();
2827 }
2828
Eli Friedmanaa769812013-09-11 03:49:34 +00002829 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2830 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002831 // For GNU atomics, require a trivially-copyable type. This is not part of
2832 // the GNU atomics specification, but we enforce it for sanity.
2833 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002834 << Ptr->getType() << Ptr->getSourceRange();
2835 return ExprError();
2836 }
2837
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002838 switch (ValType.getObjCLifetime()) {
2839 case Qualifiers::OCL_None:
2840 case Qualifiers::OCL_ExplicitNone:
2841 // okay
2842 break;
2843
2844 case Qualifiers::OCL_Weak:
2845 case Qualifiers::OCL_Strong:
2846 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002847 // FIXME: Can this happen? By this point, ValType should be known
2848 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002849 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2850 << ValType << Ptr->getSourceRange();
2851 return ExprError();
2852 }
2853
David Majnemerc6eb6502015-06-03 00:26:35 +00002854 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2855 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002856 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002857 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002858 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002859 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002860 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002861 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002862 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002863 ResultType = Context.BoolTy;
2864
Richard Smithfeea8832012-04-12 05:08:17 +00002865 // The type of a parameter passed 'by value'. In the GNU atomics, such
2866 // arguments are actually passed as pointers.
2867 QualType ByValType = ValType; // 'CP'
2868 if (!IsC11 && !IsN)
2869 ByValType = Ptr->getType();
2870
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002871 // The first argument --- the pointer --- has a fixed type; we
2872 // deduce the types of the rest of the arguments accordingly. Walk
2873 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002874 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002875 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002876 if (i < NumVals[Form] + 1) {
2877 switch (i) {
2878 case 1:
2879 // The second argument is the non-atomic operand. For arithmetic, this
2880 // is always passed by value, and for a compare_exchange it is always
2881 // passed by address. For the rest, GNU uses by-address and C11 uses
2882 // by-value.
2883 assert(Form != Load);
2884 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2885 Ty = ValType;
2886 else if (Form == Copy || Form == Xchg)
2887 Ty = ByValType;
2888 else if (Form == Arithmetic)
2889 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002890 else {
2891 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00002892 // Treat this argument as _Nonnull as we want to show a warning if
2893 // NULL is passed into it.
2894 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002895 unsigned AS = 0;
2896 // Keep address space of non-atomic pointer type.
2897 if (const PointerType *PtrTy =
2898 ValArg->getType()->getAs<PointerType>()) {
2899 AS = PtrTy->getPointeeType().getAddressSpace();
2900 }
2901 Ty = Context.getPointerType(
2902 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2903 }
Richard Smithfeea8832012-04-12 05:08:17 +00002904 break;
2905 case 2:
2906 // The third argument to compare_exchange / GNU exchange is a
2907 // (pointer to a) desired value.
2908 Ty = ByValType;
2909 break;
2910 case 3:
2911 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2912 Ty = Context.BoolTy;
2913 break;
2914 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002915 } else {
2916 // The order(s) are always converted to int.
2917 Ty = Context.IntTy;
2918 }
Richard Smithfeea8832012-04-12 05:08:17 +00002919
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002920 InitializedEntity Entity =
2921 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002922 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002923 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2924 if (Arg.isInvalid())
2925 return true;
2926 TheCall->setArg(i, Arg.get());
2927 }
2928
Richard Smithfeea8832012-04-12 05:08:17 +00002929 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002930 SmallVector<Expr*, 5> SubExprs;
2931 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002932 switch (Form) {
2933 case Init:
2934 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002935 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002936 break;
2937 case Load:
2938 SubExprs.push_back(TheCall->getArg(1)); // Order
2939 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002940 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002941 case Copy:
2942 case Arithmetic:
2943 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002944 SubExprs.push_back(TheCall->getArg(2)); // Order
2945 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002946 break;
2947 case GNUXchg:
2948 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2949 SubExprs.push_back(TheCall->getArg(3)); // Order
2950 SubExprs.push_back(TheCall->getArg(1)); // Val1
2951 SubExprs.push_back(TheCall->getArg(2)); // Val2
2952 break;
2953 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002954 SubExprs.push_back(TheCall->getArg(3)); // Order
2955 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002956 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002957 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002958 break;
2959 case GNUCmpXchg:
2960 SubExprs.push_back(TheCall->getArg(4)); // Order
2961 SubExprs.push_back(TheCall->getArg(1)); // Val1
2962 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2963 SubExprs.push_back(TheCall->getArg(2)); // Val2
2964 SubExprs.push_back(TheCall->getArg(3)); // Weak
2965 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002966 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002967
2968 if (SubExprs.size() >= 2 && Form != Init) {
2969 llvm::APSInt Result(32);
2970 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2971 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002972 Diag(SubExprs[1]->getLocStart(),
2973 diag::warn_atomic_op_has_invalid_memory_order)
2974 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002975 }
2976
Fariborz Jahanian615de762013-05-28 17:37:39 +00002977 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2978 SubExprs, ResultType, Op,
2979 TheCall->getRParenLoc());
2980
2981 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2982 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2983 Context.AtomicUsesUnsupportedLibcall(AE))
2984 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2985 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002986
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002987 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002988}
2989
John McCall29ad95b2011-08-27 01:09:30 +00002990/// checkBuiltinArgument - Given a call to a builtin function, perform
2991/// normal type-checking on the given argument, updating the call in
2992/// place. This is useful when a builtin function requires custom
2993/// type-checking for some of its arguments but not necessarily all of
2994/// them.
2995///
2996/// Returns true on error.
2997static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2998 FunctionDecl *Fn = E->getDirectCallee();
2999 assert(Fn && "builtin call without direct callee!");
3000
3001 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3002 InitializedEntity Entity =
3003 InitializedEntity::InitializeParameter(S.Context, Param);
3004
3005 ExprResult Arg = E->getArg(0);
3006 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3007 if (Arg.isInvalid())
3008 return true;
3009
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003010 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003011 return false;
3012}
3013
Chris Lattnerdc046542009-05-08 06:58:22 +00003014/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3015/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3016/// type of its first argument. The main ActOnCallExpr routines have already
3017/// promoted the types of arguments because all of these calls are prototyped as
3018/// void(...).
3019///
3020/// This function goes through and does final semantic checking for these
3021/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003022ExprResult
3023Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003024 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003025 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3026 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3027
3028 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003029 if (TheCall->getNumArgs() < 1) {
3030 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3031 << 0 << 1 << TheCall->getNumArgs()
3032 << TheCall->getCallee()->getSourceRange();
3033 return ExprError();
3034 }
Mike Stump11289f42009-09-09 15:08:12 +00003035
Chris Lattnerdc046542009-05-08 06:58:22 +00003036 // Inspect the first argument of the atomic builtin. This should always be
3037 // a pointer type, whose element is an integral scalar or pointer type.
3038 // Because it is a pointer type, we don't have to worry about any implicit
3039 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003040 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003041 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003042 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3043 if (FirstArgResult.isInvalid())
3044 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003045 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003046 TheCall->setArg(0, FirstArg);
3047
John McCall31168b02011-06-15 23:02:42 +00003048 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3049 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003050 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3051 << FirstArg->getType() << FirstArg->getSourceRange();
3052 return ExprError();
3053 }
Mike Stump11289f42009-09-09 15:08:12 +00003054
John McCall31168b02011-06-15 23:02:42 +00003055 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003056 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003057 !ValType->isBlockPointerType()) {
3058 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3059 << FirstArg->getType() << FirstArg->getSourceRange();
3060 return ExprError();
3061 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003062
John McCall31168b02011-06-15 23:02:42 +00003063 switch (ValType.getObjCLifetime()) {
3064 case Qualifiers::OCL_None:
3065 case Qualifiers::OCL_ExplicitNone:
3066 // okay
3067 break;
3068
3069 case Qualifiers::OCL_Weak:
3070 case Qualifiers::OCL_Strong:
3071 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003072 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003073 << ValType << FirstArg->getSourceRange();
3074 return ExprError();
3075 }
3076
John McCallb50451a2011-10-05 07:41:44 +00003077 // Strip any qualifiers off ValType.
3078 ValType = ValType.getUnqualifiedType();
3079
Chandler Carruth3973af72010-07-18 20:54:12 +00003080 // The majority of builtins return a value, but a few have special return
3081 // types, so allow them to override appropriately below.
3082 QualType ResultType = ValType;
3083
Chris Lattnerdc046542009-05-08 06:58:22 +00003084 // We need to figure out which concrete builtin this maps onto. For example,
3085 // __sync_fetch_and_add with a 2 byte object turns into
3086 // __sync_fetch_and_add_2.
3087#define BUILTIN_ROW(x) \
3088 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3089 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003090
Chris Lattnerdc046542009-05-08 06:58:22 +00003091 static const unsigned BuiltinIndices[][5] = {
3092 BUILTIN_ROW(__sync_fetch_and_add),
3093 BUILTIN_ROW(__sync_fetch_and_sub),
3094 BUILTIN_ROW(__sync_fetch_and_or),
3095 BUILTIN_ROW(__sync_fetch_and_and),
3096 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003097 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003098
Chris Lattnerdc046542009-05-08 06:58:22 +00003099 BUILTIN_ROW(__sync_add_and_fetch),
3100 BUILTIN_ROW(__sync_sub_and_fetch),
3101 BUILTIN_ROW(__sync_and_and_fetch),
3102 BUILTIN_ROW(__sync_or_and_fetch),
3103 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003104 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003105
Chris Lattnerdc046542009-05-08 06:58:22 +00003106 BUILTIN_ROW(__sync_val_compare_and_swap),
3107 BUILTIN_ROW(__sync_bool_compare_and_swap),
3108 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003109 BUILTIN_ROW(__sync_lock_release),
3110 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003111 };
Mike Stump11289f42009-09-09 15:08:12 +00003112#undef BUILTIN_ROW
3113
Chris Lattnerdc046542009-05-08 06:58:22 +00003114 // Determine the index of the size.
3115 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003116 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003117 case 1: SizeIndex = 0; break;
3118 case 2: SizeIndex = 1; break;
3119 case 4: SizeIndex = 2; break;
3120 case 8: SizeIndex = 3; break;
3121 case 16: SizeIndex = 4; break;
3122 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003123 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3124 << FirstArg->getType() << FirstArg->getSourceRange();
3125 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
Chris Lattnerdc046542009-05-08 06:58:22 +00003128 // Each of these builtins has one pointer argument, followed by some number of
3129 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3130 // that we ignore. Find out which row of BuiltinIndices to read from as well
3131 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003132 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003133 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003134 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003135 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003136 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003137 case Builtin::BI__sync_fetch_and_add:
3138 case Builtin::BI__sync_fetch_and_add_1:
3139 case Builtin::BI__sync_fetch_and_add_2:
3140 case Builtin::BI__sync_fetch_and_add_4:
3141 case Builtin::BI__sync_fetch_and_add_8:
3142 case Builtin::BI__sync_fetch_and_add_16:
3143 BuiltinIndex = 0;
3144 break;
3145
3146 case Builtin::BI__sync_fetch_and_sub:
3147 case Builtin::BI__sync_fetch_and_sub_1:
3148 case Builtin::BI__sync_fetch_and_sub_2:
3149 case Builtin::BI__sync_fetch_and_sub_4:
3150 case Builtin::BI__sync_fetch_and_sub_8:
3151 case Builtin::BI__sync_fetch_and_sub_16:
3152 BuiltinIndex = 1;
3153 break;
3154
3155 case Builtin::BI__sync_fetch_and_or:
3156 case Builtin::BI__sync_fetch_and_or_1:
3157 case Builtin::BI__sync_fetch_and_or_2:
3158 case Builtin::BI__sync_fetch_and_or_4:
3159 case Builtin::BI__sync_fetch_and_or_8:
3160 case Builtin::BI__sync_fetch_and_or_16:
3161 BuiltinIndex = 2;
3162 break;
3163
3164 case Builtin::BI__sync_fetch_and_and:
3165 case Builtin::BI__sync_fetch_and_and_1:
3166 case Builtin::BI__sync_fetch_and_and_2:
3167 case Builtin::BI__sync_fetch_and_and_4:
3168 case Builtin::BI__sync_fetch_and_and_8:
3169 case Builtin::BI__sync_fetch_and_and_16:
3170 BuiltinIndex = 3;
3171 break;
Mike Stump11289f42009-09-09 15:08:12 +00003172
Douglas Gregor73722482011-11-28 16:30:08 +00003173 case Builtin::BI__sync_fetch_and_xor:
3174 case Builtin::BI__sync_fetch_and_xor_1:
3175 case Builtin::BI__sync_fetch_and_xor_2:
3176 case Builtin::BI__sync_fetch_and_xor_4:
3177 case Builtin::BI__sync_fetch_and_xor_8:
3178 case Builtin::BI__sync_fetch_and_xor_16:
3179 BuiltinIndex = 4;
3180 break;
3181
Hal Finkeld2208b52014-10-02 20:53:50 +00003182 case Builtin::BI__sync_fetch_and_nand:
3183 case Builtin::BI__sync_fetch_and_nand_1:
3184 case Builtin::BI__sync_fetch_and_nand_2:
3185 case Builtin::BI__sync_fetch_and_nand_4:
3186 case Builtin::BI__sync_fetch_and_nand_8:
3187 case Builtin::BI__sync_fetch_and_nand_16:
3188 BuiltinIndex = 5;
3189 WarnAboutSemanticsChange = true;
3190 break;
3191
Douglas Gregor73722482011-11-28 16:30:08 +00003192 case Builtin::BI__sync_add_and_fetch:
3193 case Builtin::BI__sync_add_and_fetch_1:
3194 case Builtin::BI__sync_add_and_fetch_2:
3195 case Builtin::BI__sync_add_and_fetch_4:
3196 case Builtin::BI__sync_add_and_fetch_8:
3197 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003198 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003199 break;
3200
3201 case Builtin::BI__sync_sub_and_fetch:
3202 case Builtin::BI__sync_sub_and_fetch_1:
3203 case Builtin::BI__sync_sub_and_fetch_2:
3204 case Builtin::BI__sync_sub_and_fetch_4:
3205 case Builtin::BI__sync_sub_and_fetch_8:
3206 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003207 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003208 break;
3209
3210 case Builtin::BI__sync_and_and_fetch:
3211 case Builtin::BI__sync_and_and_fetch_1:
3212 case Builtin::BI__sync_and_and_fetch_2:
3213 case Builtin::BI__sync_and_and_fetch_4:
3214 case Builtin::BI__sync_and_and_fetch_8:
3215 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003216 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003217 break;
3218
3219 case Builtin::BI__sync_or_and_fetch:
3220 case Builtin::BI__sync_or_and_fetch_1:
3221 case Builtin::BI__sync_or_and_fetch_2:
3222 case Builtin::BI__sync_or_and_fetch_4:
3223 case Builtin::BI__sync_or_and_fetch_8:
3224 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003225 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003226 break;
3227
3228 case Builtin::BI__sync_xor_and_fetch:
3229 case Builtin::BI__sync_xor_and_fetch_1:
3230 case Builtin::BI__sync_xor_and_fetch_2:
3231 case Builtin::BI__sync_xor_and_fetch_4:
3232 case Builtin::BI__sync_xor_and_fetch_8:
3233 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003234 BuiltinIndex = 10;
3235 break;
3236
3237 case Builtin::BI__sync_nand_and_fetch:
3238 case Builtin::BI__sync_nand_and_fetch_1:
3239 case Builtin::BI__sync_nand_and_fetch_2:
3240 case Builtin::BI__sync_nand_and_fetch_4:
3241 case Builtin::BI__sync_nand_and_fetch_8:
3242 case Builtin::BI__sync_nand_and_fetch_16:
3243 BuiltinIndex = 11;
3244 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003245 break;
Mike Stump11289f42009-09-09 15:08:12 +00003246
Chris Lattnerdc046542009-05-08 06:58:22 +00003247 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003248 case Builtin::BI__sync_val_compare_and_swap_1:
3249 case Builtin::BI__sync_val_compare_and_swap_2:
3250 case Builtin::BI__sync_val_compare_and_swap_4:
3251 case Builtin::BI__sync_val_compare_and_swap_8:
3252 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003253 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003254 NumFixed = 2;
3255 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003256
Chris Lattnerdc046542009-05-08 06:58:22 +00003257 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003258 case Builtin::BI__sync_bool_compare_and_swap_1:
3259 case Builtin::BI__sync_bool_compare_and_swap_2:
3260 case Builtin::BI__sync_bool_compare_and_swap_4:
3261 case Builtin::BI__sync_bool_compare_and_swap_8:
3262 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003263 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003264 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003265 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003266 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003267
3268 case Builtin::BI__sync_lock_test_and_set:
3269 case Builtin::BI__sync_lock_test_and_set_1:
3270 case Builtin::BI__sync_lock_test_and_set_2:
3271 case Builtin::BI__sync_lock_test_and_set_4:
3272 case Builtin::BI__sync_lock_test_and_set_8:
3273 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003274 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003275 break;
3276
Chris Lattnerdc046542009-05-08 06:58:22 +00003277 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003278 case Builtin::BI__sync_lock_release_1:
3279 case Builtin::BI__sync_lock_release_2:
3280 case Builtin::BI__sync_lock_release_4:
3281 case Builtin::BI__sync_lock_release_8:
3282 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003283 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003284 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003285 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003286 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003287
3288 case Builtin::BI__sync_swap:
3289 case Builtin::BI__sync_swap_1:
3290 case Builtin::BI__sync_swap_2:
3291 case Builtin::BI__sync_swap_4:
3292 case Builtin::BI__sync_swap_8:
3293 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003294 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003295 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003296 }
Mike Stump11289f42009-09-09 15:08:12 +00003297
Chris Lattnerdc046542009-05-08 06:58:22 +00003298 // Now that we know how many fixed arguments we expect, first check that we
3299 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003300 if (TheCall->getNumArgs() < 1+NumFixed) {
3301 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3302 << 0 << 1+NumFixed << TheCall->getNumArgs()
3303 << TheCall->getCallee()->getSourceRange();
3304 return ExprError();
3305 }
Mike Stump11289f42009-09-09 15:08:12 +00003306
Hal Finkeld2208b52014-10-02 20:53:50 +00003307 if (WarnAboutSemanticsChange) {
3308 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3309 << TheCall->getCallee()->getSourceRange();
3310 }
3311
Chris Lattner5b9241b2009-05-08 15:36:58 +00003312 // Get the decl for the concrete builtin from this, we can tell what the
3313 // concrete integer type we should convert to is.
3314 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003315 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003316 FunctionDecl *NewBuiltinDecl;
3317 if (NewBuiltinID == BuiltinID)
3318 NewBuiltinDecl = FDecl;
3319 else {
3320 // Perform builtin lookup to avoid redeclaring it.
3321 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3322 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3323 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3324 assert(Res.getFoundDecl());
3325 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003326 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003327 return ExprError();
3328 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003329
John McCallcf142162010-08-07 06:22:56 +00003330 // The first argument --- the pointer --- has a fixed type; we
3331 // deduce the types of the rest of the arguments accordingly. Walk
3332 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003333 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003334 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003335
Chris Lattnerdc046542009-05-08 06:58:22 +00003336 // GCC does an implicit conversion to the pointer or integer ValType. This
3337 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003338 // Initialize the argument.
3339 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3340 ValType, /*consume*/ false);
3341 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003342 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003343 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003344
Chris Lattnerdc046542009-05-08 06:58:22 +00003345 // Okay, we have something that *can* be converted to the right type. Check
3346 // to see if there is a potentially weird extension going on here. This can
3347 // happen when you do an atomic operation on something like an char* and
3348 // pass in 42. The 42 gets converted to char. This is even more strange
3349 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003350 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003351 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003352 }
Mike Stump11289f42009-09-09 15:08:12 +00003353
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003354 ASTContext& Context = this->getASTContext();
3355
3356 // Create a new DeclRefExpr to refer to the new decl.
3357 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3358 Context,
3359 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003360 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003361 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003362 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003363 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003364 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003365 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003366
Chris Lattnerdc046542009-05-08 06:58:22 +00003367 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003368 // FIXME: This loses syntactic information.
3369 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3370 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3371 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003372 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003373
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003374 // Change the result type of the call to match the original value type. This
3375 // is arbitrary, but the codegen for these builtins ins design to handle it
3376 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003377 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003378
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003379 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003380}
3381
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003382/// SemaBuiltinNontemporalOverloaded - We have a call to
3383/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3384/// overloaded function based on the pointer type of its last argument.
3385///
3386/// This function goes through and does final semantic checking for these
3387/// builtins.
3388ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3389 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3390 DeclRefExpr *DRE =
3391 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3392 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3393 unsigned BuiltinID = FDecl->getBuiltinID();
3394 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3395 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3396 "Unexpected nontemporal load/store builtin!");
3397 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3398 unsigned numArgs = isStore ? 2 : 1;
3399
3400 // Ensure that we have the proper number of arguments.
3401 if (checkArgCount(*this, TheCall, numArgs))
3402 return ExprError();
3403
3404 // Inspect the last argument of the nontemporal builtin. This should always
3405 // be a pointer type, from which we imply the type of the memory access.
3406 // Because it is a pointer type, we don't have to worry about any implicit
3407 // casts here.
3408 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3409 ExprResult PointerArgResult =
3410 DefaultFunctionArrayLvalueConversion(PointerArg);
3411
3412 if (PointerArgResult.isInvalid())
3413 return ExprError();
3414 PointerArg = PointerArgResult.get();
3415 TheCall->setArg(numArgs - 1, PointerArg);
3416
3417 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3418 if (!pointerType) {
3419 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3420 << PointerArg->getType() << PointerArg->getSourceRange();
3421 return ExprError();
3422 }
3423
3424 QualType ValType = pointerType->getPointeeType();
3425
3426 // Strip any qualifiers off ValType.
3427 ValType = ValType.getUnqualifiedType();
3428 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3429 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3430 !ValType->isVectorType()) {
3431 Diag(DRE->getLocStart(),
3432 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3433 << PointerArg->getType() << PointerArg->getSourceRange();
3434 return ExprError();
3435 }
3436
3437 if (!isStore) {
3438 TheCall->setType(ValType);
3439 return TheCallResult;
3440 }
3441
3442 ExprResult ValArg = TheCall->getArg(0);
3443 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3444 Context, ValType, /*consume*/ false);
3445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3446 if (ValArg.isInvalid())
3447 return ExprError();
3448
3449 TheCall->setArg(0, ValArg.get());
3450 TheCall->setType(Context.VoidTy);
3451 return TheCallResult;
3452}
3453
Chris Lattner6436fb62009-02-18 06:01:06 +00003454/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003455/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003456/// Note: It might also make sense to do the UTF-16 conversion here (would
3457/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003458bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003459 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003460 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3461
Douglas Gregorfb65e592011-07-27 05:40:30 +00003462 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003463 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3464 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003465 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003466 }
Mike Stump11289f42009-09-09 15:08:12 +00003467
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003468 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003469 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003470 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003471 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3472 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3473 llvm::UTF16 *ToPtr = &ToBuf[0];
3474
3475 llvm::ConversionResult Result =
3476 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3477 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003478 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003479 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003480 Diag(Arg->getLocStart(),
3481 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3482 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003483 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003484}
3485
Mehdi Amini06d367c2016-10-24 20:39:34 +00003486/// CheckObjCString - Checks that the format string argument to the os_log()
3487/// and os_trace() functions is correct, and converts it to const char *.
3488ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3489 Arg = Arg->IgnoreParenCasts();
3490 auto *Literal = dyn_cast<StringLiteral>(Arg);
3491 if (!Literal) {
3492 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3493 Literal = ObjcLiteral->getString();
3494 }
3495 }
3496
3497 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3498 return ExprError(
3499 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3500 << Arg->getSourceRange());
3501 }
3502
3503 ExprResult Result(Literal);
3504 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3505 InitializedEntity Entity =
3506 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3507 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3508 return Result;
3509}
3510
Charles Davisc7d5c942015-09-17 20:55:33 +00003511/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3512/// for validity. Emit an error and return true on failure; return false
3513/// on success.
3514bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003515 Expr *Fn = TheCall->getCallee();
3516 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003517 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003518 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003519 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3520 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003521 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003522 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003523 return true;
3524 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003525
3526 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003527 return Diag(TheCall->getLocEnd(),
3528 diag::err_typecheck_call_too_few_args_at_least)
3529 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003530 }
3531
John McCall29ad95b2011-08-27 01:09:30 +00003532 // Type-check the first argument normally.
3533 if (checkBuiltinArgument(*this, TheCall, 0))
3534 return true;
3535
Chris Lattnere202e6a2007-12-20 00:05:45 +00003536 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003537 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003538 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003539 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003540 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003541 else if (FunctionDecl *FD = getCurFunctionDecl())
3542 isVariadic = FD->isVariadic();
3543 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003544 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003545
Chris Lattnere202e6a2007-12-20 00:05:45 +00003546 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003547 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3548 return true;
3549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Chris Lattner43be2e62007-12-19 23:59:04 +00003551 // Verify that the second argument to the builtin is the last argument of the
3552 // current function or method.
3553 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003554 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003555
Nico Weber9eea7642013-05-24 23:31:57 +00003556 // These are valid if SecondArgIsLastNamedArgument is false after the next
3557 // block.
3558 QualType Type;
3559 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003560 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003561
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003562 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3563 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003564 // FIXME: This isn't correct for methods (results in bogus warning).
3565 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003566 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003567 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003568 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003569 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003570 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003571 else
David Majnemera3debed2016-06-24 05:33:44 +00003572 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003573 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003574
3575 Type = PV->getType();
3576 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003577 IsCRegister =
3578 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003579 }
3580 }
Mike Stump11289f42009-09-09 15:08:12 +00003581
Chris Lattner43be2e62007-12-19 23:59:04 +00003582 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003583 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003584 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003585 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003586 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3587 // Promotable integers are UB, but enumerations need a bit of
3588 // extra checking to see what their promotable type actually is.
3589 if (!Type->isPromotableIntegerType())
3590 return false;
3591 if (!Type->isEnumeralType())
3592 return true;
3593 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3594 return !(ED &&
3595 Context.typesAreCompatible(ED->getPromotionType(), Type));
3596 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003597 unsigned Reason = 0;
3598 if (Type->isReferenceType()) Reason = 1;
3599 else if (IsCRegister) Reason = 2;
3600 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003601 Diag(ParamLoc, diag::note_parameter_type) << Type;
3602 }
3603
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003604 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003605 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003606}
Chris Lattner43be2e62007-12-19 23:59:04 +00003607
Charles Davisc7d5c942015-09-17 20:55:33 +00003608/// Check the arguments to '__builtin_va_start' for validity, and that
3609/// it was called from a function of the native ABI.
3610/// Emit an error and return true on failure; return false on success.
3611bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3612 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3613 // On x64 Windows, don't allow this in System V ABI functions.
3614 // (Yes, that means there's no corresponding way to support variadic
3615 // System V ABI functions on Windows.)
3616 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3617 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3618 clang::CallingConv CC = CC_C;
3619 if (const FunctionDecl *FD = getCurFunctionDecl())
3620 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3621 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3622 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3623 return Diag(TheCall->getCallee()->getLocStart(),
3624 diag::err_va_start_used_in_wrong_abi_function)
3625 << (OS != llvm::Triple::Win32);
3626 }
3627 return SemaBuiltinVAStartImpl(TheCall);
3628}
3629
3630/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3631/// it was called from a Win64 ABI function.
3632/// Emit an error and return true on failure; return false on success.
3633bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3634 // This only makes sense for x86-64.
3635 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3636 Expr *Callee = TheCall->getCallee();
3637 if (TT.getArch() != llvm::Triple::x86_64)
3638 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3639 // Don't allow this in System V ABI functions.
3640 clang::CallingConv CC = CC_C;
3641 if (const FunctionDecl *FD = getCurFunctionDecl())
3642 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3643 if (CC == CC_X86_64SysV ||
3644 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3645 return Diag(Callee->getLocStart(),
3646 diag::err_ms_va_start_used_in_sysv_function);
3647 return SemaBuiltinVAStartImpl(TheCall);
3648}
3649
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003650bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3651 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3652 // const char *named_addr);
3653
3654 Expr *Func = Call->getCallee();
3655
3656 if (Call->getNumArgs() < 3)
3657 return Diag(Call->getLocEnd(),
3658 diag::err_typecheck_call_too_few_args_at_least)
3659 << 0 /*function call*/ << 3 << Call->getNumArgs();
3660
3661 // Determine whether the current function is variadic or not.
3662 bool IsVariadic;
3663 if (BlockScopeInfo *CurBlock = getCurBlock())
3664 IsVariadic = CurBlock->TheDecl->isVariadic();
3665 else if (FunctionDecl *FD = getCurFunctionDecl())
3666 IsVariadic = FD->isVariadic();
3667 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3668 IsVariadic = MD->isVariadic();
3669 else
3670 llvm_unreachable("unexpected statement type");
3671
3672 if (!IsVariadic) {
3673 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3674 return true;
3675 }
3676
3677 // Type-check the first argument normally.
3678 if (checkBuiltinArgument(*this, Call, 0))
3679 return true;
3680
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003681 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003682 unsigned ArgNo;
3683 QualType Type;
3684 } ArgumentTypes[] = {
3685 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3686 { 2, Context.getSizeType() },
3687 };
3688
3689 for (const auto &AT : ArgumentTypes) {
3690 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3691 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3692 continue;
3693 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3694 << Arg->getType() << AT.Type << 1 /* different class */
3695 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3696 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3697 }
3698
3699 return false;
3700}
3701
Chris Lattner2da14fb2007-12-20 00:26:33 +00003702/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3703/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003704bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3705 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003706 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003707 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003708 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003709 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003710 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003711 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003712 << SourceRange(TheCall->getArg(2)->getLocStart(),
3713 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003714
John Wiegley01296292011-04-08 18:41:53 +00003715 ExprResult OrigArg0 = TheCall->getArg(0);
3716 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003717
Chris Lattner2da14fb2007-12-20 00:26:33 +00003718 // Do standard promotions between the two arguments, returning their common
3719 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003720 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003721 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3722 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003723
3724 // Make sure any conversions are pushed back into the call; this is
3725 // type safe since unordered compare builtins are declared as "_Bool
3726 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003727 TheCall->setArg(0, OrigArg0.get());
3728 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003729
John Wiegley01296292011-04-08 18:41:53 +00003730 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003731 return false;
3732
Chris Lattner2da14fb2007-12-20 00:26:33 +00003733 // If the common type isn't a real floating type, then the arguments were
3734 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003735 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003736 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003737 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003738 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3739 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003740
Chris Lattner2da14fb2007-12-20 00:26:33 +00003741 return false;
3742}
3743
Benjamin Kramer634fc102010-02-15 22:42:31 +00003744/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3745/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003746/// to check everything. We expect the last argument to be a floating point
3747/// value.
3748bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3749 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003750 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003751 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003752 if (TheCall->getNumArgs() > NumArgs)
3753 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003754 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003755 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003756 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003757 (*(TheCall->arg_end()-1))->getLocEnd());
3758
Benjamin Kramer64aae502010-02-16 10:07:31 +00003759 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003760
Eli Friedman7e4faac2009-08-31 20:06:00 +00003761 if (OrigArg->isTypeDependent())
3762 return false;
3763
Chris Lattner68784ef2010-05-06 05:50:07 +00003764 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003765 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003766 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003767 diag::err_typecheck_call_invalid_unary_fp)
3768 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003769
Neil Hickey88c0fac2016-12-13 16:22:50 +00003770 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003771 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003772 // Only remove standard FloatCasts, leaving other casts inplace
3773 if (Cast->getCastKind() == CK_FloatingCast) {
3774 Expr *CastArg = Cast->getSubExpr();
3775 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3776 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3777 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3778 "promotion from float to either float or double is the only expected cast here");
3779 Cast->setSubExpr(nullptr);
3780 TheCall->setArg(NumArgs-1, CastArg);
3781 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003782 }
3783 }
3784
Eli Friedman7e4faac2009-08-31 20:06:00 +00003785 return false;
3786}
3787
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003788/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3789// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003790ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003791 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003792 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003793 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003794 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3795 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003796
Nate Begemana0110022010-06-08 00:16:34 +00003797 // Determine which of the following types of shufflevector we're checking:
3798 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003799 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003800 QualType resType = TheCall->getArg(0)->getType();
3801 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003802
Douglas Gregorc25f7662009-05-19 22:10:17 +00003803 if (!TheCall->getArg(0)->isTypeDependent() &&
3804 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003805 QualType LHSType = TheCall->getArg(0)->getType();
3806 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003807
Craig Topperbaca3892013-07-29 06:47:04 +00003808 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3809 return ExprError(Diag(TheCall->getLocStart(),
3810 diag::err_shufflevector_non_vector)
3811 << SourceRange(TheCall->getArg(0)->getLocStart(),
3812 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003813
Nate Begemana0110022010-06-08 00:16:34 +00003814 numElements = LHSType->getAs<VectorType>()->getNumElements();
3815 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003816
Nate Begemana0110022010-06-08 00:16:34 +00003817 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3818 // with mask. If so, verify that RHS is an integer vector type with the
3819 // same number of elts as lhs.
3820 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003821 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003822 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003823 return ExprError(Diag(TheCall->getLocStart(),
3824 diag::err_shufflevector_incompatible_vector)
3825 << SourceRange(TheCall->getArg(1)->getLocStart(),
3826 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003827 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003828 return ExprError(Diag(TheCall->getLocStart(),
3829 diag::err_shufflevector_incompatible_vector)
3830 << SourceRange(TheCall->getArg(0)->getLocStart(),
3831 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003832 } else if (numElements != numResElements) {
3833 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003834 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003835 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003836 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003837 }
3838
3839 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003840 if (TheCall->getArg(i)->isTypeDependent() ||
3841 TheCall->getArg(i)->isValueDependent())
3842 continue;
3843
Nate Begemana0110022010-06-08 00:16:34 +00003844 llvm::APSInt Result(32);
3845 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3846 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003847 diag::err_shufflevector_nonconstant_argument)
3848 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003849
Craig Topper50ad5b72013-08-03 17:40:38 +00003850 // Allow -1 which will be translated to undef in the IR.
3851 if (Result.isSigned() && Result.isAllOnesValue())
3852 continue;
3853
Chris Lattner7ab824e2008-08-10 02:05:13 +00003854 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003855 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003856 diag::err_shufflevector_argument_too_large)
3857 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003858 }
3859
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003860 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003861
Chris Lattner7ab824e2008-08-10 02:05:13 +00003862 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003863 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003864 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003865 }
3866
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003867 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3868 TheCall->getCallee()->getLocStart(),
3869 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003870}
Chris Lattner43be2e62007-12-19 23:59:04 +00003871
Hal Finkelc4d7c822013-09-18 03:29:45 +00003872/// SemaConvertVectorExpr - Handle __builtin_convertvector
3873ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3874 SourceLocation BuiltinLoc,
3875 SourceLocation RParenLoc) {
3876 ExprValueKind VK = VK_RValue;
3877 ExprObjectKind OK = OK_Ordinary;
3878 QualType DstTy = TInfo->getType();
3879 QualType SrcTy = E->getType();
3880
3881 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3882 return ExprError(Diag(BuiltinLoc,
3883 diag::err_convertvector_non_vector)
3884 << E->getSourceRange());
3885 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3886 return ExprError(Diag(BuiltinLoc,
3887 diag::err_convertvector_non_vector_type));
3888
3889 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3890 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3891 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3892 if (SrcElts != DstElts)
3893 return ExprError(Diag(BuiltinLoc,
3894 diag::err_convertvector_incompatible_vector)
3895 << E->getSourceRange());
3896 }
3897
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003898 return new (Context)
3899 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003900}
3901
Daniel Dunbarb7257262008-07-21 22:59:13 +00003902/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3903// This is declared to take (const void*, ...) and can take two
3904// optional constant int args.
3905bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003906 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003907
Chris Lattner3b054132008-11-19 05:08:23 +00003908 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003909 return Diag(TheCall->getLocEnd(),
3910 diag::err_typecheck_call_too_many_args_at_most)
3911 << 0 /*function call*/ << 3 << NumArgs
3912 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003913
3914 // Argument 0 is checked for us and the remaining arguments must be
3915 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003916 for (unsigned i = 1; i != NumArgs; ++i)
3917 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003918 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003919
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003920 return false;
3921}
3922
Hal Finkelf0417332014-07-17 14:25:55 +00003923/// SemaBuiltinAssume - Handle __assume (MS Extension).
3924// __assume does not evaluate its arguments, and should warn if its argument
3925// has side effects.
3926bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3927 Expr *Arg = TheCall->getArg(0);
3928 if (Arg->isInstantiationDependent()) return false;
3929
3930 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003931 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003932 << Arg->getSourceRange()
3933 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3934
3935 return false;
3936}
3937
David Majnemer86b1bfa2016-10-31 18:07:57 +00003938/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003939/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3940/// than 8.
3941bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3942 // The alignment must be a constant integer.
3943 Expr *Arg = TheCall->getArg(1);
3944
3945 // We can't check the value of a dependent argument.
3946 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003947 if (const auto *UE =
3948 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3949 if (UE->getKind() == UETT_AlignOf)
3950 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3951 << Arg->getSourceRange();
3952
David Majnemer51169932016-10-31 05:37:48 +00003953 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3954
3955 if (!Result.isPowerOf2())
3956 return Diag(TheCall->getLocStart(),
3957 diag::err_alignment_not_power_of_two)
3958 << Arg->getSourceRange();
3959
3960 if (Result < Context.getCharWidth())
3961 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3962 << (unsigned)Context.getCharWidth()
3963 << Arg->getSourceRange();
3964
3965 if (Result > INT32_MAX)
3966 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3967 << INT32_MAX
3968 << Arg->getSourceRange();
3969 }
3970
3971 return false;
3972}
3973
3974/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003975/// as (const void*, size_t, ...) and can take one optional constant int arg.
3976bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3977 unsigned NumArgs = TheCall->getNumArgs();
3978
3979 if (NumArgs > 3)
3980 return Diag(TheCall->getLocEnd(),
3981 diag::err_typecheck_call_too_many_args_at_most)
3982 << 0 /*function call*/ << 3 << NumArgs
3983 << TheCall->getSourceRange();
3984
3985 // The alignment must be a constant integer.
3986 Expr *Arg = TheCall->getArg(1);
3987
3988 // We can't check the value of a dependent argument.
3989 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3990 llvm::APSInt Result;
3991 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3992 return true;
3993
3994 if (!Result.isPowerOf2())
3995 return Diag(TheCall->getLocStart(),
3996 diag::err_alignment_not_power_of_two)
3997 << Arg->getSourceRange();
3998 }
3999
4000 if (NumArgs > 2) {
4001 ExprResult Arg(TheCall->getArg(2));
4002 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4003 Context.getSizeType(), false);
4004 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4005 if (Arg.isInvalid()) return true;
4006 TheCall->setArg(2, Arg.get());
4007 }
Hal Finkelf0417332014-07-17 14:25:55 +00004008
4009 return false;
4010}
4011
Mehdi Amini06d367c2016-10-24 20:39:34 +00004012bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4013 unsigned BuiltinID =
4014 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4015 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4016
4017 unsigned NumArgs = TheCall->getNumArgs();
4018 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4019 if (NumArgs < NumRequiredArgs) {
4020 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4021 << 0 /* function call */ << NumRequiredArgs << NumArgs
4022 << TheCall->getSourceRange();
4023 }
4024 if (NumArgs >= NumRequiredArgs + 0x100) {
4025 return Diag(TheCall->getLocEnd(),
4026 diag::err_typecheck_call_too_many_args_at_most)
4027 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4028 << TheCall->getSourceRange();
4029 }
4030 unsigned i = 0;
4031
4032 // For formatting call, check buffer arg.
4033 if (!IsSizeCall) {
4034 ExprResult Arg(TheCall->getArg(i));
4035 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4036 Context, Context.VoidPtrTy, false);
4037 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4038 if (Arg.isInvalid())
4039 return true;
4040 TheCall->setArg(i, Arg.get());
4041 i++;
4042 }
4043
4044 // Check string literal arg.
4045 unsigned FormatIdx = i;
4046 {
4047 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4048 if (Arg.isInvalid())
4049 return true;
4050 TheCall->setArg(i, Arg.get());
4051 i++;
4052 }
4053
4054 // Make sure variadic args are scalar.
4055 unsigned FirstDataArg = i;
4056 while (i < NumArgs) {
4057 ExprResult Arg = DefaultVariadicArgumentPromotion(
4058 TheCall->getArg(i), VariadicFunction, nullptr);
4059 if (Arg.isInvalid())
4060 return true;
4061 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4062 if (ArgSize.getQuantity() >= 0x100) {
4063 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4064 << i << (int)ArgSize.getQuantity() << 0xff
4065 << TheCall->getSourceRange();
4066 }
4067 TheCall->setArg(i, Arg.get());
4068 i++;
4069 }
4070
4071 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4072 // call to avoid duplicate diagnostics.
4073 if (!IsSizeCall) {
4074 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4075 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4076 bool Success = CheckFormatArguments(
4077 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4078 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4079 CheckedVarArgs);
4080 if (!Success)
4081 return true;
4082 }
4083
4084 if (IsSizeCall) {
4085 TheCall->setType(Context.getSizeType());
4086 } else {
4087 TheCall->setType(Context.VoidPtrTy);
4088 }
4089 return false;
4090}
4091
Eric Christopher8d0c6212010-04-17 02:26:23 +00004092/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4093/// TheCall is a constant expression.
4094bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4095 llvm::APSInt &Result) {
4096 Expr *Arg = TheCall->getArg(ArgNum);
4097 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4098 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4099
4100 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4101
4102 if (!Arg->isIntegerConstantExpr(Result, Context))
4103 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004104 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004105
Chris Lattnerd545ad12009-09-23 06:06:36 +00004106 return false;
4107}
4108
Richard Sandiford28940af2014-04-16 08:47:51 +00004109/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4110/// TheCall is a constant expression in the range [Low, High].
4111bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4112 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004113 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004114
4115 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004116 Expr *Arg = TheCall->getArg(ArgNum);
4117 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004118 return false;
4119
Eric Christopher8d0c6212010-04-17 02:26:23 +00004120 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004121 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004122 return true;
4123
Richard Sandiford28940af2014-04-16 08:47:51 +00004124 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004125 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004126 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004127
4128 return false;
4129}
4130
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004131/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4132/// TheCall is a constant expression is a multiple of Num..
4133bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4134 unsigned Num) {
4135 llvm::APSInt Result;
4136
4137 // We can't check the value of a dependent argument.
4138 Expr *Arg = TheCall->getArg(ArgNum);
4139 if (Arg->isTypeDependent() || Arg->isValueDependent())
4140 return false;
4141
4142 // Check constant-ness first.
4143 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4144 return true;
4145
4146 if (Result.getSExtValue() % Num != 0)
4147 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4148 << Num << Arg->getSourceRange();
4149
4150 return false;
4151}
4152
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004153/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4154/// TheCall is an ARM/AArch64 special register string literal.
4155bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4156 int ArgNum, unsigned ExpectedFieldNum,
4157 bool AllowName) {
4158 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4159 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4160 BuiltinID == ARM::BI__builtin_arm_rsr ||
4161 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4162 BuiltinID == ARM::BI__builtin_arm_wsr ||
4163 BuiltinID == ARM::BI__builtin_arm_wsrp;
4164 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4165 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4166 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4167 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4168 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4169 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4170 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4171
4172 // We can't check the value of a dependent argument.
4173 Expr *Arg = TheCall->getArg(ArgNum);
4174 if (Arg->isTypeDependent() || Arg->isValueDependent())
4175 return false;
4176
4177 // Check if the argument is a string literal.
4178 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4179 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4180 << Arg->getSourceRange();
4181
4182 // Check the type of special register given.
4183 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4184 SmallVector<StringRef, 6> Fields;
4185 Reg.split(Fields, ":");
4186
4187 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4188 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4189 << Arg->getSourceRange();
4190
4191 // If the string is the name of a register then we cannot check that it is
4192 // valid here but if the string is of one the forms described in ACLE then we
4193 // can check that the supplied fields are integers and within the valid
4194 // ranges.
4195 if (Fields.size() > 1) {
4196 bool FiveFields = Fields.size() == 5;
4197
4198 bool ValidString = true;
4199 if (IsARMBuiltin) {
4200 ValidString &= Fields[0].startswith_lower("cp") ||
4201 Fields[0].startswith_lower("p");
4202 if (ValidString)
4203 Fields[0] =
4204 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4205
4206 ValidString &= Fields[2].startswith_lower("c");
4207 if (ValidString)
4208 Fields[2] = Fields[2].drop_front(1);
4209
4210 if (FiveFields) {
4211 ValidString &= Fields[3].startswith_lower("c");
4212 if (ValidString)
4213 Fields[3] = Fields[3].drop_front(1);
4214 }
4215 }
4216
4217 SmallVector<int, 5> Ranges;
4218 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004219 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004220 else
4221 Ranges.append({15, 7, 15});
4222
4223 for (unsigned i=0; i<Fields.size(); ++i) {
4224 int IntField;
4225 ValidString &= !Fields[i].getAsInteger(10, IntField);
4226 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4227 }
4228
4229 if (!ValidString)
4230 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4231 << Arg->getSourceRange();
4232
4233 } else if (IsAArch64Builtin && Fields.size() == 1) {
4234 // If the register name is one of those that appear in the condition below
4235 // and the special register builtin being used is one of the write builtins,
4236 // then we require that the argument provided for writing to the register
4237 // is an integer constant expression. This is because it will be lowered to
4238 // an MSR (immediate) instruction, so we need to know the immediate at
4239 // compile time.
4240 if (TheCall->getNumArgs() != 2)
4241 return false;
4242
4243 std::string RegLower = Reg.lower();
4244 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4245 RegLower != "pan" && RegLower != "uao")
4246 return false;
4247
4248 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4249 }
4250
4251 return false;
4252}
4253
Eli Friedmanc97d0142009-05-03 06:04:26 +00004254/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004255/// This checks that the target supports __builtin_longjmp and
4256/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004257bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004258 if (!Context.getTargetInfo().hasSjLjLowering())
4259 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4260 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4261
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004262 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004263 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004264
Eric Christopher8d0c6212010-04-17 02:26:23 +00004265 // TODO: This is less than ideal. Overload this to take a value.
4266 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4267 return true;
4268
4269 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004270 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4271 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4272
4273 return false;
4274}
4275
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004276/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4277/// This checks that the target supports __builtin_setjmp.
4278bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4279 if (!Context.getTargetInfo().hasSjLjLowering())
4280 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4281 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4282 return false;
4283}
4284
Richard Smithd7293d72013-08-05 18:49:43 +00004285namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004286class UncoveredArgHandler {
4287 enum { Unknown = -1, AllCovered = -2 };
4288 signed FirstUncoveredArg;
4289 SmallVector<const Expr *, 4> DiagnosticExprs;
4290
4291public:
4292 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4293
4294 bool hasUncoveredArg() const {
4295 return (FirstUncoveredArg >= 0);
4296 }
4297
4298 unsigned getUncoveredArg() const {
4299 assert(hasUncoveredArg() && "no uncovered argument");
4300 return FirstUncoveredArg;
4301 }
4302
4303 void setAllCovered() {
4304 // A string has been found with all arguments covered, so clear out
4305 // the diagnostics.
4306 DiagnosticExprs.clear();
4307 FirstUncoveredArg = AllCovered;
4308 }
4309
4310 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4311 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4312
4313 // Don't update if a previous string covers all arguments.
4314 if (FirstUncoveredArg == AllCovered)
4315 return;
4316
4317 // UncoveredArgHandler tracks the highest uncovered argument index
4318 // and with it all the strings that match this index.
4319 if (NewFirstUncoveredArg == FirstUncoveredArg)
4320 DiagnosticExprs.push_back(StrExpr);
4321 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4322 DiagnosticExprs.clear();
4323 DiagnosticExprs.push_back(StrExpr);
4324 FirstUncoveredArg = NewFirstUncoveredArg;
4325 }
4326 }
4327
4328 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4329};
4330
Richard Smithd7293d72013-08-05 18:49:43 +00004331enum StringLiteralCheckType {
4332 SLCT_NotALiteral,
4333 SLCT_UncheckedLiteral,
4334 SLCT_CheckedLiteral
4335};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004336} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004337
Stephen Hines648c3692016-09-16 01:07:04 +00004338static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4339 BinaryOperatorKind BinOpKind,
4340 bool AddendIsRight) {
4341 unsigned BitWidth = Offset.getBitWidth();
4342 unsigned AddendBitWidth = Addend.getBitWidth();
4343 // There might be negative interim results.
4344 if (Addend.isUnsigned()) {
4345 Addend = Addend.zext(++AddendBitWidth);
4346 Addend.setIsSigned(true);
4347 }
4348 // Adjust the bit width of the APSInts.
4349 if (AddendBitWidth > BitWidth) {
4350 Offset = Offset.sext(AddendBitWidth);
4351 BitWidth = AddendBitWidth;
4352 } else if (BitWidth > AddendBitWidth) {
4353 Addend = Addend.sext(BitWidth);
4354 }
4355
4356 bool Ov = false;
4357 llvm::APSInt ResOffset = Offset;
4358 if (BinOpKind == BO_Add)
4359 ResOffset = Offset.sadd_ov(Addend, Ov);
4360 else {
4361 assert(AddendIsRight && BinOpKind == BO_Sub &&
4362 "operator must be add or sub with addend on the right");
4363 ResOffset = Offset.ssub_ov(Addend, Ov);
4364 }
4365
4366 // We add an offset to a pointer here so we should support an offset as big as
4367 // possible.
4368 if (Ov) {
4369 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004370 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004371 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4372 return;
4373 }
4374
4375 Offset = ResOffset;
4376}
4377
4378namespace {
4379// This is a wrapper class around StringLiteral to support offsetted string
4380// literals as format strings. It takes the offset into account when returning
4381// the string and its length or the source locations to display notes correctly.
4382class FormatStringLiteral {
4383 const StringLiteral *FExpr;
4384 int64_t Offset;
4385
4386 public:
4387 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4388 : FExpr(fexpr), Offset(Offset) {}
4389
4390 StringRef getString() const {
4391 return FExpr->getString().drop_front(Offset);
4392 }
4393
4394 unsigned getByteLength() const {
4395 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4396 }
4397 unsigned getLength() const { return FExpr->getLength() - Offset; }
4398 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4399
4400 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4401
4402 QualType getType() const { return FExpr->getType(); }
4403
4404 bool isAscii() const { return FExpr->isAscii(); }
4405 bool isWide() const { return FExpr->isWide(); }
4406 bool isUTF8() const { return FExpr->isUTF8(); }
4407 bool isUTF16() const { return FExpr->isUTF16(); }
4408 bool isUTF32() const { return FExpr->isUTF32(); }
4409 bool isPascal() const { return FExpr->isPascal(); }
4410
4411 SourceLocation getLocationOfByte(
4412 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4413 const TargetInfo &Target, unsigned *StartToken = nullptr,
4414 unsigned *StartTokenByteOffset = nullptr) const {
4415 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4416 StartToken, StartTokenByteOffset);
4417 }
4418
4419 SourceLocation getLocStart() const LLVM_READONLY {
4420 return FExpr->getLocStart().getLocWithOffset(Offset);
4421 }
4422 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4423};
4424} // end anonymous namespace
4425
4426static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004427 const Expr *OrigFormatExpr,
4428 ArrayRef<const Expr *> Args,
4429 bool HasVAListArg, unsigned format_idx,
4430 unsigned firstDataArg,
4431 Sema::FormatStringType Type,
4432 bool inFunctionCall,
4433 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004434 llvm::SmallBitVector &CheckedVarArgs,
4435 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004436
Richard Smith55ce3522012-06-25 20:30:08 +00004437// Determine if an expression is a string literal or constant string.
4438// If this function returns false on the arguments to a function expecting a
4439// format string, we will usually need to emit a warning.
4440// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004441static StringLiteralCheckType
4442checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4443 bool HasVAListArg, unsigned format_idx,
4444 unsigned firstDataArg, Sema::FormatStringType Type,
4445 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004446 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004447 UncoveredArgHandler &UncoveredArg,
4448 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004449 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004450 assert(Offset.isSigned() && "invalid offset");
4451
Douglas Gregorc25f7662009-05-19 22:10:17 +00004452 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004453 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004454
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004455 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004456
Richard Smithd7293d72013-08-05 18:49:43 +00004457 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004458 // Technically -Wformat-nonliteral does not warn about this case.
4459 // The behavior of printf and friends in this case is implementation
4460 // dependent. Ideally if the format string cannot be null then
4461 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004462 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004463
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004464 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004465 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004466 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004467 // The expression is a literal if both sub-expressions were, and it was
4468 // completely checked only if both sub-expressions were checked.
4469 const AbstractConditionalOperator *C =
4470 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004471
4472 // Determine whether it is necessary to check both sub-expressions, for
4473 // example, because the condition expression is a constant that can be
4474 // evaluated at compile time.
4475 bool CheckLeft = true, CheckRight = true;
4476
4477 bool Cond;
4478 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4479 if (Cond)
4480 CheckRight = false;
4481 else
4482 CheckLeft = false;
4483 }
4484
Stephen Hines648c3692016-09-16 01:07:04 +00004485 // We need to maintain the offsets for the right and the left hand side
4486 // separately to check if every possible indexed expression is a valid
4487 // string literal. They might have different offsets for different string
4488 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004489 StringLiteralCheckType Left;
4490 if (!CheckLeft)
4491 Left = SLCT_UncheckedLiteral;
4492 else {
4493 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4494 HasVAListArg, format_idx, firstDataArg,
4495 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004496 CheckedVarArgs, UncoveredArg, Offset);
4497 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004498 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004499 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004500 }
4501
Richard Smith55ce3522012-06-25 20:30:08 +00004502 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004503 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004504 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004505 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004506 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004507
4508 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004509 }
4510
4511 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004512 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4513 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004514 }
4515
John McCallc07a0c72011-02-17 10:25:35 +00004516 case Stmt::OpaqueValueExprClass:
4517 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4518 E = src;
4519 goto tryAgain;
4520 }
Richard Smith55ce3522012-06-25 20:30:08 +00004521 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004522
Ted Kremeneka8890832011-02-24 23:03:04 +00004523 case Stmt::PredefinedExprClass:
4524 // While __func__, etc., are technically not string literals, they
4525 // cannot contain format specifiers and thus are not a security
4526 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004527 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004528
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004529 case Stmt::DeclRefExprClass: {
4530 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004531
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004532 // As an exception, do not flag errors for variables binding to
4533 // const string literals.
4534 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4535 bool isConstant = false;
4536 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004537
Richard Smithd7293d72013-08-05 18:49:43 +00004538 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4539 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004540 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004541 isConstant = T.isConstant(S.Context) &&
4542 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004543 } else if (T->isObjCObjectPointerType()) {
4544 // In ObjC, there is usually no "const ObjectPointer" type,
4545 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004546 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004547 }
Mike Stump11289f42009-09-09 15:08:12 +00004548
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004549 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004550 if (const Expr *Init = VD->getAnyInitializer()) {
4551 // Look through initializers like const char c[] = { "foo" }
4552 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4553 if (InitList->isStringLiteralInit())
4554 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4555 }
Richard Smithd7293d72013-08-05 18:49:43 +00004556 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004557 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004558 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004559 /*InFunctionCall*/ false, CheckedVarArgs,
4560 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004561 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004562 }
Mike Stump11289f42009-09-09 15:08:12 +00004563
Anders Carlssonb012ca92009-06-28 19:55:58 +00004564 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4565 // special check to see if the format string is a function parameter
4566 // of the function calling the printf function. If the function
4567 // has an attribute indicating it is a printf-like function, then we
4568 // should suppress warnings concerning non-literals being used in a call
4569 // to a vprintf function. For example:
4570 //
4571 // void
4572 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4573 // va_list ap;
4574 // va_start(ap, fmt);
4575 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4576 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004577 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004578 if (HasVAListArg) {
4579 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4580 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4581 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004582 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004583 // adjust for implicit parameter
4584 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4585 if (MD->isInstance())
4586 ++PVIndex;
4587 // We also check if the formats are compatible.
4588 // We can't pass a 'scanf' string to a 'printf' function.
4589 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004590 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004591 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004592 }
4593 }
4594 }
4595 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004596 }
Mike Stump11289f42009-09-09 15:08:12 +00004597
Richard Smith55ce3522012-06-25 20:30:08 +00004598 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004599 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004600
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004601 case Stmt::CallExprClass:
4602 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004603 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004604 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4605 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4606 unsigned ArgIndex = FA->getFormatIdx();
4607 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4608 if (MD->isInstance())
4609 --ArgIndex;
4610 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004611
Richard Smithd7293d72013-08-05 18:49:43 +00004612 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004613 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004614 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004615 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004616 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4617 unsigned BuiltinID = FD->getBuiltinID();
4618 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4619 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4620 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004621 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004622 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004623 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004624 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004625 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004626 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004627 }
4628 }
Mike Stump11289f42009-09-09 15:08:12 +00004629
Richard Smith55ce3522012-06-25 20:30:08 +00004630 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004631 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004632 case Stmt::ObjCMessageExprClass: {
4633 const auto *ME = cast<ObjCMessageExpr>(E);
4634 if (const auto *ND = ME->getMethodDecl()) {
4635 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4636 unsigned ArgIndex = FA->getFormatIdx();
4637 const Expr *Arg = ME->getArg(ArgIndex - 1);
4638 return checkFormatStringExpr(
4639 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4640 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4641 }
4642 }
4643
4644 return SLCT_NotALiteral;
4645 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004646 case Stmt::ObjCStringLiteralClass:
4647 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004648 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004649
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004650 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004651 StrE = ObjCFExpr->getString();
4652 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004653 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004654
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004655 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004656 if (Offset.isNegative() || Offset > StrE->getLength()) {
4657 // TODO: It would be better to have an explicit warning for out of
4658 // bounds literals.
4659 return SLCT_NotALiteral;
4660 }
4661 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4662 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004663 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004664 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004665 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004666 }
Mike Stump11289f42009-09-09 15:08:12 +00004667
Richard Smith55ce3522012-06-25 20:30:08 +00004668 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004669 }
Stephen Hines648c3692016-09-16 01:07:04 +00004670 case Stmt::BinaryOperatorClass: {
4671 llvm::APSInt LResult;
4672 llvm::APSInt RResult;
4673
4674 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4675
4676 // A string literal + an int offset is still a string literal.
4677 if (BinOp->isAdditiveOp()) {
4678 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4679 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4680
4681 if (LIsInt != RIsInt) {
4682 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4683
4684 if (LIsInt) {
4685 if (BinOpKind == BO_Add) {
4686 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4687 E = BinOp->getRHS();
4688 goto tryAgain;
4689 }
4690 } else {
4691 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4692 E = BinOp->getLHS();
4693 goto tryAgain;
4694 }
4695 }
Stephen Hines648c3692016-09-16 01:07:04 +00004696 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004697
4698 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004699 }
4700 case Stmt::UnaryOperatorClass: {
4701 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4702 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4703 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4704 llvm::APSInt IndexResult;
4705 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4706 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4707 E = ASE->getBase();
4708 goto tryAgain;
4709 }
4710 }
4711
4712 return SLCT_NotALiteral;
4713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004715 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004716 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004717 }
4718}
4719
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004720Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004721 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004722 .Case("scanf", FST_Scanf)
4723 .Cases("printf", "printf0", FST_Printf)
4724 .Cases("NSString", "CFString", FST_NSString)
4725 .Case("strftime", FST_Strftime)
4726 .Case("strfmon", FST_Strfmon)
4727 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4728 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4729 .Case("os_trace", FST_OSLog)
4730 .Case("os_log", FST_OSLog)
4731 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004732}
4733
Jordan Rose3e0ec582012-07-19 18:10:23 +00004734/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004735/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004736/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004737bool Sema::CheckFormatArguments(const FormatAttr *Format,
4738 ArrayRef<const Expr *> Args,
4739 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004740 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004741 SourceLocation Loc, SourceRange Range,
4742 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004743 FormatStringInfo FSI;
4744 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004745 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004746 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004747 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004748 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004749}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004750
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004751bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004752 bool HasVAListArg, unsigned format_idx,
4753 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004754 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004755 SourceLocation Loc, SourceRange Range,
4756 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004757 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004758 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004759 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004760 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004761 }
Mike Stump11289f42009-09-09 15:08:12 +00004762
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004763 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004764
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004765 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004766 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004767 // Dynamically generated format strings are difficult to
4768 // automatically vet at compile time. Requiring that format strings
4769 // are string literals: (1) permits the checking of format strings by
4770 // the compiler and thereby (2) can practically remove the source of
4771 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004772
Mike Stump11289f42009-09-09 15:08:12 +00004773 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004774 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004775 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004776 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004777 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004778 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004779 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4780 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004781 /*IsFunctionCall*/ true, CheckedVarArgs,
4782 UncoveredArg,
4783 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004784
4785 // Generate a diagnostic where an uncovered argument is detected.
4786 if (UncoveredArg.hasUncoveredArg()) {
4787 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4788 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4789 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4790 }
4791
Richard Smith55ce3522012-06-25 20:30:08 +00004792 if (CT != SLCT_NotALiteral)
4793 // Literal format string found, check done!
4794 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004795
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004796 // Strftime is particular as it always uses a single 'time' argument,
4797 // so it is safe to pass a non-literal string.
4798 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004799 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004800
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004801 // Do not emit diag when the string param is a macro expansion and the
4802 // format is either NSString or CFString. This is a hack to prevent
4803 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4804 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004805 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4806 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004807 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004808
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004809 // If there are no arguments specified, warn with -Wformat-security, otherwise
4810 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004811 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004812 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4813 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004814 switch (Type) {
4815 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004816 break;
4817 case FST_Kprintf:
4818 case FST_FreeBSDKPrintf:
4819 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004820 Diag(FormatLoc, diag::note_format_security_fixit)
4821 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004822 break;
4823 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004824 Diag(FormatLoc, diag::note_format_security_fixit)
4825 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004826 break;
4827 }
4828 } else {
4829 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004830 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004831 }
Richard Smith55ce3522012-06-25 20:30:08 +00004832 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004833}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004834
Ted Kremenekab278de2010-01-28 23:39:18 +00004835namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004836class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4837protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004838 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004839 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004840 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004841 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004842 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004843 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004844 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004845 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004846 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004847 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004848 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004849 bool usesPositionalArgs;
4850 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004851 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004852 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004853 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004854 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004855
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004856public:
Stephen Hines648c3692016-09-16 01:07:04 +00004857 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004858 const Expr *origFormatExpr,
4859 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004860 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004861 ArrayRef<const Expr *> Args, unsigned formatIdx,
4862 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004863 llvm::SmallBitVector &CheckedVarArgs,
4864 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004865 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4866 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4867 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4868 usesPositionalArgs(false), atFirstArg(true),
4869 inFunctionCall(inFunctionCall), CallType(callType),
4870 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004871 CoveredArgs.resize(numDataArgs);
4872 CoveredArgs.reset();
4873 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004874
Ted Kremenek019d2242010-01-29 01:50:07 +00004875 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004876
Ted Kremenek02087932010-07-16 02:11:22 +00004877 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004878 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004879
Jordan Rose92303592012-09-08 04:00:03 +00004880 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004881 const analyze_format_string::FormatSpecifier &FS,
4882 const analyze_format_string::ConversionSpecifier &CS,
4883 const char *startSpecifier, unsigned specifierLen,
4884 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004885
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004886 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004887 const analyze_format_string::FormatSpecifier &FS,
4888 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004889
4890 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004891 const analyze_format_string::ConversionSpecifier &CS,
4892 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004893
Craig Toppere14c0f82014-03-12 04:55:44 +00004894 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004895
Craig Toppere14c0f82014-03-12 04:55:44 +00004896 void HandleInvalidPosition(const char *startSpecifier,
4897 unsigned specifierLen,
4898 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004899
Craig Toppere14c0f82014-03-12 04:55:44 +00004900 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004901
Craig Toppere14c0f82014-03-12 04:55:44 +00004902 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004903
Richard Trieu03cf7b72011-10-28 00:41:25 +00004904 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004905 static void
4906 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4907 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4908 bool IsStringLocation, Range StringRange,
4909 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004910
Ted Kremenek02087932010-07-16 02:11:22 +00004911protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004912 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4913 const char *startSpec,
4914 unsigned specifierLen,
4915 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004916
4917 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4918 const char *startSpec,
4919 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004920
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004921 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004922 CharSourceRange getSpecifierRange(const char *startSpecifier,
4923 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004924 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004925
Ted Kremenek5739de72010-01-29 01:06:55 +00004926 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004927
4928 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4929 const analyze_format_string::ConversionSpecifier &CS,
4930 const char *startSpecifier, unsigned specifierLen,
4931 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004932
4933 template <typename Range>
4934 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4935 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004936 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004937};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004938} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004939
Ted Kremenek02087932010-07-16 02:11:22 +00004940SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004941 return OrigFormatExpr->getSourceRange();
4942}
4943
Ted Kremenek02087932010-07-16 02:11:22 +00004944CharSourceRange CheckFormatHandler::
4945getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004946 SourceLocation Start = getLocationOfByte(startSpecifier);
4947 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4948
4949 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004950 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004951
4952 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004953}
4954
Ted Kremenek02087932010-07-16 02:11:22 +00004955SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004956 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4957 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004958}
4959
Ted Kremenek02087932010-07-16 02:11:22 +00004960void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4961 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004962 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4963 getLocationOfByte(startSpecifier),
4964 /*IsStringLocation*/true,
4965 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004966}
4967
Jordan Rose92303592012-09-08 04:00:03 +00004968void CheckFormatHandler::HandleInvalidLengthModifier(
4969 const analyze_format_string::FormatSpecifier &FS,
4970 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004971 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004972 using namespace analyze_format_string;
4973
4974 const LengthModifier &LM = FS.getLengthModifier();
4975 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4976
4977 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004978 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004979 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004980 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004981 getLocationOfByte(LM.getStart()),
4982 /*IsStringLocation*/true,
4983 getSpecifierRange(startSpecifier, specifierLen));
4984
4985 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4986 << FixedLM->toString()
4987 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4988
4989 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004990 FixItHint Hint;
4991 if (DiagID == diag::warn_format_nonsensical_length)
4992 Hint = FixItHint::CreateRemoval(LMRange);
4993
4994 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004995 getLocationOfByte(LM.getStart()),
4996 /*IsStringLocation*/true,
4997 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004998 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004999 }
5000}
5001
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005002void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005003 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005004 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005005 using namespace analyze_format_string;
5006
5007 const LengthModifier &LM = FS.getLengthModifier();
5008 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5009
5010 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005011 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005012 if (FixedLM) {
5013 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5014 << LM.toString() << 0,
5015 getLocationOfByte(LM.getStart()),
5016 /*IsStringLocation*/true,
5017 getSpecifierRange(startSpecifier, specifierLen));
5018
5019 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5020 << FixedLM->toString()
5021 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5022
5023 } else {
5024 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5025 << LM.toString() << 0,
5026 getLocationOfByte(LM.getStart()),
5027 /*IsStringLocation*/true,
5028 getSpecifierRange(startSpecifier, specifierLen));
5029 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005030}
5031
5032void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5033 const analyze_format_string::ConversionSpecifier &CS,
5034 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005035 using namespace analyze_format_string;
5036
5037 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005038 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005039 if (FixedCS) {
5040 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5041 << CS.toString() << /*conversion specifier*/1,
5042 getLocationOfByte(CS.getStart()),
5043 /*IsStringLocation*/true,
5044 getSpecifierRange(startSpecifier, specifierLen));
5045
5046 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5047 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5048 << FixedCS->toString()
5049 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5050 } else {
5051 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5052 << CS.toString() << /*conversion specifier*/1,
5053 getLocationOfByte(CS.getStart()),
5054 /*IsStringLocation*/true,
5055 getSpecifierRange(startSpecifier, specifierLen));
5056 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005057}
5058
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005059void CheckFormatHandler::HandlePosition(const char *startPos,
5060 unsigned posLen) {
5061 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5062 getLocationOfByte(startPos),
5063 /*IsStringLocation*/true,
5064 getSpecifierRange(startPos, posLen));
5065}
5066
Ted Kremenekd1668192010-02-27 01:41:03 +00005067void
Ted Kremenek02087932010-07-16 02:11:22 +00005068CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5069 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005070 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5071 << (unsigned) p,
5072 getLocationOfByte(startPos), /*IsStringLocation*/true,
5073 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005074}
5075
Ted Kremenek02087932010-07-16 02:11:22 +00005076void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005077 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005078 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5079 getLocationOfByte(startPos),
5080 /*IsStringLocation*/true,
5081 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005082}
5083
Ted Kremenek02087932010-07-16 02:11:22 +00005084void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005085 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005086 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005087 EmitFormatDiagnostic(
5088 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5089 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5090 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005091 }
Ted Kremenek02087932010-07-16 02:11:22 +00005092}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005093
Jordan Rose58bbe422012-07-19 18:10:08 +00005094// Note that this may return NULL if there was an error parsing or building
5095// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005096const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005097 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005098}
5099
5100void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005101 // Does the number of data arguments exceed the number of
5102 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005103 if (!HasVAListArg) {
5104 // Find any arguments that weren't covered.
5105 CoveredArgs.flip();
5106 signed notCoveredArg = CoveredArgs.find_first();
5107 if (notCoveredArg >= 0) {
5108 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005109 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5110 } else {
5111 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005112 }
5113 }
5114}
5115
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005116void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5117 const Expr *ArgExpr) {
5118 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5119 "Invalid state");
5120
5121 if (!ArgExpr)
5122 return;
5123
5124 SourceLocation Loc = ArgExpr->getLocStart();
5125
5126 if (S.getSourceManager().isInSystemMacro(Loc))
5127 return;
5128
5129 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5130 for (auto E : DiagnosticExprs)
5131 PDiag << E->getSourceRange();
5132
5133 CheckFormatHandler::EmitFormatDiagnostic(
5134 S, IsFunctionCall, DiagnosticExprs[0],
5135 PDiag, Loc, /*IsStringLocation*/false,
5136 DiagnosticExprs[0]->getSourceRange());
5137}
5138
Ted Kremenekce815422010-07-19 21:25:57 +00005139bool
5140CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5141 SourceLocation Loc,
5142 const char *startSpec,
5143 unsigned specifierLen,
5144 const char *csStart,
5145 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005146 bool keepGoing = true;
5147 if (argIndex < NumDataArgs) {
5148 // Consider the argument coverered, even though the specifier doesn't
5149 // make sense.
5150 CoveredArgs.set(argIndex);
5151 }
5152 else {
5153 // If argIndex exceeds the number of data arguments we
5154 // don't issue a warning because that is just a cascade of warnings (and
5155 // they may have intended '%%' anyway). We don't want to continue processing
5156 // the format string after this point, however, as we will like just get
5157 // gibberish when trying to match arguments.
5158 keepGoing = false;
5159 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005160
5161 StringRef Specifier(csStart, csLen);
5162
5163 // If the specifier in non-printable, it could be the first byte of a UTF-8
5164 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5165 // hex value.
5166 std::string CodePointStr;
5167 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005168 llvm::UTF32 CodePoint;
5169 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5170 const llvm::UTF8 *E =
5171 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5172 llvm::ConversionResult Result =
5173 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005174
Justin Lebar90910552016-09-30 00:38:45 +00005175 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005176 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005177 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005178 }
5179
5180 llvm::raw_string_ostream OS(CodePointStr);
5181 if (CodePoint < 256)
5182 OS << "\\x" << llvm::format("%02x", CodePoint);
5183 else if (CodePoint <= 0xFFFF)
5184 OS << "\\u" << llvm::format("%04x", CodePoint);
5185 else
5186 OS << "\\U" << llvm::format("%08x", CodePoint);
5187 OS.flush();
5188 Specifier = CodePointStr;
5189 }
5190
5191 EmitFormatDiagnostic(
5192 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5193 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5194
Ted Kremenekce815422010-07-19 21:25:57 +00005195 return keepGoing;
5196}
5197
Richard Trieu03cf7b72011-10-28 00:41:25 +00005198void
5199CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5200 const char *startSpec,
5201 unsigned specifierLen) {
5202 EmitFormatDiagnostic(
5203 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5204 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5205}
5206
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005207bool
5208CheckFormatHandler::CheckNumArgs(
5209 const analyze_format_string::FormatSpecifier &FS,
5210 const analyze_format_string::ConversionSpecifier &CS,
5211 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5212
5213 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005214 PartialDiagnostic PDiag = FS.usesPositionalArg()
5215 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5216 << (argIndex+1) << NumDataArgs)
5217 : S.PDiag(diag::warn_printf_insufficient_data_args);
5218 EmitFormatDiagnostic(
5219 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5220 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005221
5222 // Since more arguments than conversion tokens are given, by extension
5223 // all arguments are covered, so mark this as so.
5224 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005225 return false;
5226 }
5227 return true;
5228}
5229
Richard Trieu03cf7b72011-10-28 00:41:25 +00005230template<typename Range>
5231void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5232 SourceLocation Loc,
5233 bool IsStringLocation,
5234 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005235 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005236 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005237 Loc, IsStringLocation, StringRange, FixIt);
5238}
5239
5240/// \brief If the format string is not within the funcion call, emit a note
5241/// so that the function call and string are in diagnostic messages.
5242///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005243/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005244/// call and only one diagnostic message will be produced. Otherwise, an
5245/// extra note will be emitted pointing to location of the format string.
5246///
5247/// \param ArgumentExpr the expression that is passed as the format string
5248/// argument in the function call. Used for getting locations when two
5249/// diagnostics are emitted.
5250///
5251/// \param PDiag the callee should already have provided any strings for the
5252/// diagnostic message. This function only adds locations and fixits
5253/// to diagnostics.
5254///
5255/// \param Loc primary location for diagnostic. If two diagnostics are
5256/// required, one will be at Loc and a new SourceLocation will be created for
5257/// the other one.
5258///
5259/// \param IsStringLocation if true, Loc points to the format string should be
5260/// used for the note. Otherwise, Loc points to the argument list and will
5261/// be used with PDiag.
5262///
5263/// \param StringRange some or all of the string to highlight. This is
5264/// templated so it can accept either a CharSourceRange or a SourceRange.
5265///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005266/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005267template <typename Range>
5268void CheckFormatHandler::EmitFormatDiagnostic(
5269 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5270 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5271 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005272 if (InFunctionCall) {
5273 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5274 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005275 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005276 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005277 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5278 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005279
5280 const Sema::SemaDiagnosticBuilder &Note =
5281 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5282 diag::note_format_string_defined);
5283
5284 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005285 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005286 }
5287}
5288
Ted Kremenek02087932010-07-16 02:11:22 +00005289//===--- CHECK: Printf format string checking ------------------------------===//
5290
5291namespace {
5292class CheckPrintfHandler : public CheckFormatHandler {
5293public:
Stephen Hines648c3692016-09-16 01:07:04 +00005294 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005295 const Expr *origFormatExpr,
5296 const Sema::FormatStringType type, unsigned firstDataArg,
5297 unsigned numDataArgs, bool isObjC, const char *beg,
5298 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005299 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005300 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005301 llvm::SmallBitVector &CheckedVarArgs,
5302 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005303 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5304 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5305 inFunctionCall, CallType, CheckedVarArgs,
5306 UncoveredArg) {}
5307
5308 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5309
5310 /// Returns true if '%@' specifiers are allowed in the format string.
5311 bool allowsObjCArg() const {
5312 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5313 FSType == Sema::FST_OSTrace;
5314 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005315
Ted Kremenek02087932010-07-16 02:11:22 +00005316 bool HandleInvalidPrintfConversionSpecifier(
5317 const analyze_printf::PrintfSpecifier &FS,
5318 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005319 unsigned specifierLen) override;
5320
Ted Kremenek02087932010-07-16 02:11:22 +00005321 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5322 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005323 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005324 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5325 const char *StartSpecifier,
5326 unsigned SpecifierLen,
5327 const Expr *E);
5328
Ted Kremenek02087932010-07-16 02:11:22 +00005329 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5330 const char *startSpecifier, unsigned specifierLen);
5331 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5332 const analyze_printf::OptionalAmount &Amt,
5333 unsigned type,
5334 const char *startSpecifier, unsigned specifierLen);
5335 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5336 const analyze_printf::OptionalFlag &flag,
5337 const char *startSpecifier, unsigned specifierLen);
5338 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5339 const analyze_printf::OptionalFlag &ignoredFlag,
5340 const analyze_printf::OptionalFlag &flag,
5341 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005342 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005343 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005344
5345 void HandleEmptyObjCModifierFlag(const char *startFlag,
5346 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005347
Ted Kremenek2b417712015-07-02 05:39:16 +00005348 void HandleInvalidObjCModifierFlag(const char *startFlag,
5349 unsigned flagLen) override;
5350
5351 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5352 const char *flagsEnd,
5353 const char *conversionPosition)
5354 override;
5355};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005356} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005357
5358bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5359 const analyze_printf::PrintfSpecifier &FS,
5360 const char *startSpecifier,
5361 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005362 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005363 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005364
Ted Kremenekce815422010-07-19 21:25:57 +00005365 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5366 getLocationOfByte(CS.getStart()),
5367 startSpecifier, specifierLen,
5368 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005369}
5370
Ted Kremenek02087932010-07-16 02:11:22 +00005371bool CheckPrintfHandler::HandleAmount(
5372 const analyze_format_string::OptionalAmount &Amt,
5373 unsigned k, const char *startSpecifier,
5374 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005375 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005376 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005377 unsigned argIndex = Amt.getArgIndex();
5378 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005379 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5380 << k,
5381 getLocationOfByte(Amt.getStart()),
5382 /*IsStringLocation*/true,
5383 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005384 // Don't do any more checking. We will just emit
5385 // spurious errors.
5386 return false;
5387 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005388
Ted Kremenek5739de72010-01-29 01:06:55 +00005389 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005390 // Although not in conformance with C99, we also allow the argument to be
5391 // an 'unsigned int' as that is a reasonably safe case. GCC also
5392 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005393 CoveredArgs.set(argIndex);
5394 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005395 if (!Arg)
5396 return false;
5397
Ted Kremenek5739de72010-01-29 01:06:55 +00005398 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005399
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005400 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5401 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005402
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005403 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005404 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005405 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005406 << T << Arg->getSourceRange(),
5407 getLocationOfByte(Amt.getStart()),
5408 /*IsStringLocation*/true,
5409 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005410 // Don't do any more checking. We will just emit
5411 // spurious errors.
5412 return false;
5413 }
5414 }
5415 }
5416 return true;
5417}
Ted Kremenek5739de72010-01-29 01:06:55 +00005418
Tom Careb49ec692010-06-17 19:00:27 +00005419void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005420 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005421 const analyze_printf::OptionalAmount &Amt,
5422 unsigned type,
5423 const char *startSpecifier,
5424 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005425 const analyze_printf::PrintfConversionSpecifier &CS =
5426 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005427
Richard Trieu03cf7b72011-10-28 00:41:25 +00005428 FixItHint fixit =
5429 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5430 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5431 Amt.getConstantLength()))
5432 : FixItHint();
5433
5434 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5435 << type << CS.toString(),
5436 getLocationOfByte(Amt.getStart()),
5437 /*IsStringLocation*/true,
5438 getSpecifierRange(startSpecifier, specifierLen),
5439 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005440}
5441
Ted Kremenek02087932010-07-16 02:11:22 +00005442void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005443 const analyze_printf::OptionalFlag &flag,
5444 const char *startSpecifier,
5445 unsigned specifierLen) {
5446 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005447 const analyze_printf::PrintfConversionSpecifier &CS =
5448 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5450 << flag.toString() << CS.toString(),
5451 getLocationOfByte(flag.getPosition()),
5452 /*IsStringLocation*/true,
5453 getSpecifierRange(startSpecifier, specifierLen),
5454 FixItHint::CreateRemoval(
5455 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005456}
5457
5458void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005459 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005460 const analyze_printf::OptionalFlag &ignoredFlag,
5461 const analyze_printf::OptionalFlag &flag,
5462 const char *startSpecifier,
5463 unsigned specifierLen) {
5464 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005465 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5466 << ignoredFlag.toString() << flag.toString(),
5467 getLocationOfByte(ignoredFlag.getPosition()),
5468 /*IsStringLocation*/true,
5469 getSpecifierRange(startSpecifier, specifierLen),
5470 FixItHint::CreateRemoval(
5471 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005472}
5473
Ted Kremenek2b417712015-07-02 05:39:16 +00005474// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5475// bool IsStringLocation, Range StringRange,
5476// ArrayRef<FixItHint> Fixit = None);
5477
5478void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5479 unsigned flagLen) {
5480 // Warn about an empty flag.
5481 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5482 getLocationOfByte(startFlag),
5483 /*IsStringLocation*/true,
5484 getSpecifierRange(startFlag, flagLen));
5485}
5486
5487void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5488 unsigned flagLen) {
5489 // Warn about an invalid flag.
5490 auto Range = getSpecifierRange(startFlag, flagLen);
5491 StringRef flag(startFlag, flagLen);
5492 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5493 getLocationOfByte(startFlag),
5494 /*IsStringLocation*/true,
5495 Range, FixItHint::CreateRemoval(Range));
5496}
5497
5498void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5499 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5500 // Warn about using '[...]' without a '@' conversion.
5501 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5502 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5503 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5504 getLocationOfByte(conversionPosition),
5505 /*IsStringLocation*/true,
5506 Range, FixItHint::CreateRemoval(Range));
5507}
5508
Richard Smith55ce3522012-06-25 20:30:08 +00005509// Determines if the specified is a C++ class or struct containing
5510// a member with the specified name and kind (e.g. a CXXMethodDecl named
5511// "c_str()").
5512template<typename MemberKind>
5513static llvm::SmallPtrSet<MemberKind*, 1>
5514CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5515 const RecordType *RT = Ty->getAs<RecordType>();
5516 llvm::SmallPtrSet<MemberKind*, 1> Results;
5517
5518 if (!RT)
5519 return Results;
5520 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005521 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005522 return Results;
5523
Alp Tokerb6cc5922014-05-03 03:45:55 +00005524 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005525 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005526 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005527
5528 // We just need to include all members of the right kind turned up by the
5529 // filter, at this point.
5530 if (S.LookupQualifiedName(R, RT->getDecl()))
5531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5532 NamedDecl *decl = (*I)->getUnderlyingDecl();
5533 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5534 Results.insert(FK);
5535 }
5536 return Results;
5537}
5538
Richard Smith2868a732014-02-28 01:36:39 +00005539/// Check if we could call '.c_str()' on an object.
5540///
5541/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5542/// allow the call, or if it would be ambiguous).
5543bool Sema::hasCStrMethod(const Expr *E) {
5544 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5545 MethodSet Results =
5546 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5547 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5548 MI != ME; ++MI)
5549 if ((*MI)->getMinRequiredArguments() == 0)
5550 return true;
5551 return false;
5552}
5553
Richard Smith55ce3522012-06-25 20:30:08 +00005554// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005555// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005556// Returns true when a c_str() conversion method is found.
5557bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005558 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005559 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5560
5561 MethodSet Results =
5562 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5563
5564 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5565 MI != ME; ++MI) {
5566 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005567 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005568 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005569 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005570 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005571 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5572 << "c_str()"
5573 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5574 return true;
5575 }
5576 }
5577
5578 return false;
5579}
5580
Ted Kremenekab278de2010-01-28 23:39:18 +00005581bool
Ted Kremenek02087932010-07-16 02:11:22 +00005582CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005583 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005584 const char *startSpecifier,
5585 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005586 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005587 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005588 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005589
Ted Kremenek6cd69422010-07-19 22:01:06 +00005590 if (FS.consumesDataArgument()) {
5591 if (atFirstArg) {
5592 atFirstArg = false;
5593 usesPositionalArgs = FS.usesPositionalArg();
5594 }
5595 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005596 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5597 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005598 return false;
5599 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005600 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005601
Ted Kremenekd1668192010-02-27 01:41:03 +00005602 // First check if the field width, precision, and conversion specifier
5603 // have matching data arguments.
5604 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5605 startSpecifier, specifierLen)) {
5606 return false;
5607 }
5608
5609 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5610 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005611 return false;
5612 }
5613
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005614 if (!CS.consumesDataArgument()) {
5615 // FIXME: Technically specifying a precision or field width here
5616 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005617 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005618 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005619
Ted Kremenek4a49d982010-02-26 19:18:41 +00005620 // Consume the argument.
5621 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005622 if (argIndex < NumDataArgs) {
5623 // The check to see if the argIndex is valid will come later.
5624 // We set the bit here because we may exit early from this
5625 // function if we encounter some other error.
5626 CoveredArgs.set(argIndex);
5627 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005628
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005629 // FreeBSD kernel extensions.
5630 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5631 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5632 // We need at least two arguments.
5633 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5634 return false;
5635
5636 // Claim the second argument.
5637 CoveredArgs.set(argIndex + 1);
5638
5639 // Type check the first argument (int for %b, pointer for %D)
5640 const Expr *Ex = getDataArg(argIndex);
5641 const analyze_printf::ArgType &AT =
5642 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5643 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5644 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5645 EmitFormatDiagnostic(
5646 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5647 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5648 << false << Ex->getSourceRange(),
5649 Ex->getLocStart(), /*IsStringLocation*/false,
5650 getSpecifierRange(startSpecifier, specifierLen));
5651
5652 // Type check the second argument (char * for both %b and %D)
5653 Ex = getDataArg(argIndex + 1);
5654 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5655 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5656 EmitFormatDiagnostic(
5657 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5658 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5659 << false << Ex->getSourceRange(),
5660 Ex->getLocStart(), /*IsStringLocation*/false,
5661 getSpecifierRange(startSpecifier, specifierLen));
5662
5663 return true;
5664 }
5665
Ted Kremenek4a49d982010-02-26 19:18:41 +00005666 // Check for using an Objective-C specific conversion specifier
5667 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005668 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005669 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5670 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005671 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005672
Mehdi Amini06d367c2016-10-24 20:39:34 +00005673 // %P can only be used with os_log.
5674 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5675 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5676 specifierLen);
5677 }
5678
5679 // %n is not allowed with os_log.
5680 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5681 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5682 getLocationOfByte(CS.getStart()),
5683 /*IsStringLocation*/ false,
5684 getSpecifierRange(startSpecifier, specifierLen));
5685
5686 return true;
5687 }
5688
5689 // Only scalars are allowed for os_trace.
5690 if (FSType == Sema::FST_OSTrace &&
5691 (CS.getKind() == ConversionSpecifier::PArg ||
5692 CS.getKind() == ConversionSpecifier::sArg ||
5693 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5694 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5695 specifierLen);
5696 }
5697
5698 // Check for use of public/private annotation outside of os_log().
5699 if (FSType != Sema::FST_OSLog) {
5700 if (FS.isPublic().isSet()) {
5701 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5702 << "public",
5703 getLocationOfByte(FS.isPublic().getPosition()),
5704 /*IsStringLocation*/ false,
5705 getSpecifierRange(startSpecifier, specifierLen));
5706 }
5707 if (FS.isPrivate().isSet()) {
5708 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5709 << "private",
5710 getLocationOfByte(FS.isPrivate().getPosition()),
5711 /*IsStringLocation*/ false,
5712 getSpecifierRange(startSpecifier, specifierLen));
5713 }
5714 }
5715
Tom Careb49ec692010-06-17 19:00:27 +00005716 // Check for invalid use of field width
5717 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005718 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005719 startSpecifier, specifierLen);
5720 }
5721
5722 // Check for invalid use of precision
5723 if (!FS.hasValidPrecision()) {
5724 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5725 startSpecifier, specifierLen);
5726 }
5727
Mehdi Amini06d367c2016-10-24 20:39:34 +00005728 // Precision is mandatory for %P specifier.
5729 if (CS.getKind() == ConversionSpecifier::PArg &&
5730 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5731 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5732 getLocationOfByte(startSpecifier),
5733 /*IsStringLocation*/ false,
5734 getSpecifierRange(startSpecifier, specifierLen));
5735 }
5736
Tom Careb49ec692010-06-17 19:00:27 +00005737 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005738 if (!FS.hasValidThousandsGroupingPrefix())
5739 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005740 if (!FS.hasValidLeadingZeros())
5741 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5742 if (!FS.hasValidPlusPrefix())
5743 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005744 if (!FS.hasValidSpacePrefix())
5745 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005746 if (!FS.hasValidAlternativeForm())
5747 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5748 if (!FS.hasValidLeftJustified())
5749 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5750
5751 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005752 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5753 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5754 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005755 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5756 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5757 startSpecifier, specifierLen);
5758
5759 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005760 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005761 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5762 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005763 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005764 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005765 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005766 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5767 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005768
Jordan Rose92303592012-09-08 04:00:03 +00005769 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5770 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5771
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005772 // The remaining checks depend on the data arguments.
5773 if (HasVAListArg)
5774 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005775
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005776 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005777 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005778
Jordan Rose58bbe422012-07-19 18:10:08 +00005779 const Expr *Arg = getDataArg(argIndex);
5780 if (!Arg)
5781 return true;
5782
5783 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005784}
5785
Jordan Roseaee34382012-09-05 22:56:26 +00005786static bool requiresParensToAddCast(const Expr *E) {
5787 // FIXME: We should have a general way to reason about operator
5788 // precedence and whether parens are actually needed here.
5789 // Take care of a few common cases where they aren't.
5790 const Expr *Inside = E->IgnoreImpCasts();
5791 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5792 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5793
5794 switch (Inside->getStmtClass()) {
5795 case Stmt::ArraySubscriptExprClass:
5796 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005797 case Stmt::CharacterLiteralClass:
5798 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005799 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005800 case Stmt::FloatingLiteralClass:
5801 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005802 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005803 case Stmt::ObjCArrayLiteralClass:
5804 case Stmt::ObjCBoolLiteralExprClass:
5805 case Stmt::ObjCBoxedExprClass:
5806 case Stmt::ObjCDictionaryLiteralClass:
5807 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005808 case Stmt::ObjCIvarRefExprClass:
5809 case Stmt::ObjCMessageExprClass:
5810 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005811 case Stmt::ObjCStringLiteralClass:
5812 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005813 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005814 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005815 case Stmt::UnaryOperatorClass:
5816 return false;
5817 default:
5818 return true;
5819 }
5820}
5821
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005822static std::pair<QualType, StringRef>
5823shouldNotPrintDirectly(const ASTContext &Context,
5824 QualType IntendedTy,
5825 const Expr *E) {
5826 // Use a 'while' to peel off layers of typedefs.
5827 QualType TyTy = IntendedTy;
5828 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5829 StringRef Name = UserTy->getDecl()->getName();
5830 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5831 .Case("NSInteger", Context.LongTy)
5832 .Case("NSUInteger", Context.UnsignedLongTy)
5833 .Case("SInt32", Context.IntTy)
5834 .Case("UInt32", Context.UnsignedIntTy)
5835 .Default(QualType());
5836
5837 if (!CastTy.isNull())
5838 return std::make_pair(CastTy, Name);
5839
5840 TyTy = UserTy->desugar();
5841 }
5842
5843 // Strip parens if necessary.
5844 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5845 return shouldNotPrintDirectly(Context,
5846 PE->getSubExpr()->getType(),
5847 PE->getSubExpr());
5848
5849 // If this is a conditional expression, then its result type is constructed
5850 // via usual arithmetic conversions and thus there might be no necessary
5851 // typedef sugar there. Recurse to operands to check for NSInteger &
5852 // Co. usage condition.
5853 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5854 QualType TrueTy, FalseTy;
5855 StringRef TrueName, FalseName;
5856
5857 std::tie(TrueTy, TrueName) =
5858 shouldNotPrintDirectly(Context,
5859 CO->getTrueExpr()->getType(),
5860 CO->getTrueExpr());
5861 std::tie(FalseTy, FalseName) =
5862 shouldNotPrintDirectly(Context,
5863 CO->getFalseExpr()->getType(),
5864 CO->getFalseExpr());
5865
5866 if (TrueTy == FalseTy)
5867 return std::make_pair(TrueTy, TrueName);
5868 else if (TrueTy.isNull())
5869 return std::make_pair(FalseTy, FalseName);
5870 else if (FalseTy.isNull())
5871 return std::make_pair(TrueTy, TrueName);
5872 }
5873
5874 return std::make_pair(QualType(), StringRef());
5875}
5876
Richard Smith55ce3522012-06-25 20:30:08 +00005877bool
5878CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5879 const char *StartSpecifier,
5880 unsigned SpecifierLen,
5881 const Expr *E) {
5882 using namespace analyze_format_string;
5883 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005884 // Now type check the data expression that matches the
5885 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005886 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005887 if (!AT.isValid())
5888 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005889
Jordan Rose598ec092012-12-05 18:44:40 +00005890 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005891 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5892 ExprTy = TET->getUnderlyingExpr()->getType();
5893 }
5894
Seth Cantrellb4802962015-03-04 03:12:10 +00005895 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5896
5897 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005898 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005899 }
Jordan Rose98709982012-06-04 22:48:57 +00005900
Jordan Rose22b74712012-09-05 22:56:19 +00005901 // Look through argument promotions for our error message's reported type.
5902 // This includes the integral and floating promotions, but excludes array
5903 // and function pointer decay; seeing that an argument intended to be a
5904 // string has type 'char [6]' is probably more confusing than 'char *'.
5905 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5906 if (ICE->getCastKind() == CK_IntegralCast ||
5907 ICE->getCastKind() == CK_FloatingCast) {
5908 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005909 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005910
5911 // Check if we didn't match because of an implicit cast from a 'char'
5912 // or 'short' to an 'int'. This is done because printf is a varargs
5913 // function.
5914 if (ICE->getType() == S.Context.IntTy ||
5915 ICE->getType() == S.Context.UnsignedIntTy) {
5916 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005917 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005918 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005919 }
Jordan Rose98709982012-06-04 22:48:57 +00005920 }
Jordan Rose598ec092012-12-05 18:44:40 +00005921 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5922 // Special case for 'a', which has type 'int' in C.
5923 // Note, however, that we do /not/ want to treat multibyte constants like
5924 // 'MooV' as characters! This form is deprecated but still exists.
5925 if (ExprTy == S.Context.IntTy)
5926 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5927 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005928 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005929
Jordan Rosebc53ed12014-05-31 04:12:14 +00005930 // Look through enums to their underlying type.
5931 bool IsEnum = false;
5932 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5933 ExprTy = EnumTy->getDecl()->getIntegerType();
5934 IsEnum = true;
5935 }
5936
Jordan Rose0e5badd2012-12-05 18:44:49 +00005937 // %C in an Objective-C context prints a unichar, not a wchar_t.
5938 // If the argument is an integer of some kind, believe the %C and suggest
5939 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005940 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005941 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005942 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5943 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5944 !ExprTy->isCharType()) {
5945 // 'unichar' is defined as a typedef of unsigned short, but we should
5946 // prefer using the typedef if it is visible.
5947 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005948
5949 // While we are here, check if the value is an IntegerLiteral that happens
5950 // to be within the valid range.
5951 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5952 const llvm::APInt &V = IL->getValue();
5953 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5954 return true;
5955 }
5956
Jordan Rose0e5badd2012-12-05 18:44:49 +00005957 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5958 Sema::LookupOrdinaryName);
5959 if (S.LookupName(Result, S.getCurScope())) {
5960 NamedDecl *ND = Result.getFoundDecl();
5961 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5962 if (TD->getUnderlyingType() == IntendedTy)
5963 IntendedTy = S.Context.getTypedefType(TD);
5964 }
5965 }
5966 }
5967
5968 // Special-case some of Darwin's platform-independence types by suggesting
5969 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005970 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005971 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005972 QualType CastTy;
5973 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5974 if (!CastTy.isNull()) {
5975 IntendedTy = CastTy;
5976 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005977 }
5978 }
5979
Jordan Rose22b74712012-09-05 22:56:19 +00005980 // We may be able to offer a FixItHint if it is a supported type.
5981 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005982 bool success =
5983 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005984
Jordan Rose22b74712012-09-05 22:56:19 +00005985 if (success) {
5986 // Get the fix string from the fixed format specifier
5987 SmallString<16> buf;
5988 llvm::raw_svector_ostream os(buf);
5989 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005990
Jordan Roseaee34382012-09-05 22:56:26 +00005991 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5992
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005993 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005994 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5995 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5996 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5997 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005998 // In this case, the specifier is wrong and should be changed to match
5999 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006000 EmitFormatDiagnostic(S.PDiag(diag)
6001 << AT.getRepresentativeTypeName(S.Context)
6002 << IntendedTy << IsEnum << E->getSourceRange(),
6003 E->getLocStart(),
6004 /*IsStringLocation*/ false, SpecRange,
6005 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006006 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006007 // The canonical type for formatting this value is different from the
6008 // actual type of the expression. (This occurs, for example, with Darwin's
6009 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6010 // should be printed as 'long' for 64-bit compatibility.)
6011 // Rather than emitting a normal format/argument mismatch, we want to
6012 // add a cast to the recommended type (and correct the format string
6013 // if necessary).
6014 SmallString<16> CastBuf;
6015 llvm::raw_svector_ostream CastFix(CastBuf);
6016 CastFix << "(";
6017 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6018 CastFix << ")";
6019
6020 SmallVector<FixItHint,4> Hints;
6021 if (!AT.matchesType(S.Context, IntendedTy))
6022 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6023
6024 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6025 // If there's already a cast present, just replace it.
6026 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6027 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6028
6029 } else if (!requiresParensToAddCast(E)) {
6030 // If the expression has high enough precedence,
6031 // just write the C-style cast.
6032 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6033 CastFix.str()));
6034 } else {
6035 // Otherwise, add parens around the expression as well as the cast.
6036 CastFix << "(";
6037 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6038 CastFix.str()));
6039
Alp Tokerb6cc5922014-05-03 03:45:55 +00006040 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006041 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6042 }
6043
Jordan Rose0e5badd2012-12-05 18:44:49 +00006044 if (ShouldNotPrintDirectly) {
6045 // The expression has a type that should not be printed directly.
6046 // We extract the name from the typedef because we don't want to show
6047 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006048 StringRef Name;
6049 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6050 Name = TypedefTy->getDecl()->getName();
6051 else
6052 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006053 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006054 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006055 << E->getSourceRange(),
6056 E->getLocStart(), /*IsStringLocation=*/false,
6057 SpecRange, Hints);
6058 } else {
6059 // In this case, the expression could be printed using a different
6060 // specifier, but we've decided that the specifier is probably correct
6061 // and we should cast instead. Just use the normal warning message.
6062 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006063 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6064 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006065 << E->getSourceRange(),
6066 E->getLocStart(), /*IsStringLocation*/false,
6067 SpecRange, Hints);
6068 }
Jordan Roseaee34382012-09-05 22:56:26 +00006069 }
Jordan Rose22b74712012-09-05 22:56:19 +00006070 } else {
6071 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6072 SpecifierLen);
6073 // Since the warning for passing non-POD types to variadic functions
6074 // was deferred until now, we emit a warning for non-POD
6075 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006076 switch (S.isValidVarArgType(ExprTy)) {
6077 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006078 case Sema::VAK_ValidInCXX11: {
6079 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6080 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6081 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6082 }
Richard Smithd7293d72013-08-05 18:49:43 +00006083
Seth Cantrellb4802962015-03-04 03:12:10 +00006084 EmitFormatDiagnostic(
6085 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6086 << IsEnum << CSR << E->getSourceRange(),
6087 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6088 break;
6089 }
Richard Smithd7293d72013-08-05 18:49:43 +00006090 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006091 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006092 EmitFormatDiagnostic(
6093 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006094 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006095 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006096 << CallType
6097 << AT.getRepresentativeTypeName(S.Context)
6098 << CSR
6099 << E->getSourceRange(),
6100 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006101 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006102 break;
6103
6104 case Sema::VAK_Invalid:
6105 if (ExprTy->isObjCObjectType())
6106 EmitFormatDiagnostic(
6107 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6108 << S.getLangOpts().CPlusPlus11
6109 << ExprTy
6110 << CallType
6111 << AT.getRepresentativeTypeName(S.Context)
6112 << CSR
6113 << E->getSourceRange(),
6114 E->getLocStart(), /*IsStringLocation*/false, CSR);
6115 else
6116 // FIXME: If this is an initializer list, suggest removing the braces
6117 // or inserting a cast to the target type.
6118 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6119 << isa<InitListExpr>(E) << ExprTy << CallType
6120 << AT.getRepresentativeTypeName(S.Context)
6121 << E->getSourceRange();
6122 break;
6123 }
6124
6125 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6126 "format string specifier index out of range");
6127 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006128 }
6129
Ted Kremenekab278de2010-01-28 23:39:18 +00006130 return true;
6131}
6132
Ted Kremenek02087932010-07-16 02:11:22 +00006133//===--- CHECK: Scanf format string checking ------------------------------===//
6134
6135namespace {
6136class CheckScanfHandler : public CheckFormatHandler {
6137public:
Stephen Hines648c3692016-09-16 01:07:04 +00006138 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006139 const Expr *origFormatExpr, Sema::FormatStringType type,
6140 unsigned firstDataArg, unsigned numDataArgs,
6141 const char *beg, bool hasVAListArg,
6142 ArrayRef<const Expr *> Args, unsigned formatIdx,
6143 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006144 llvm::SmallBitVector &CheckedVarArgs,
6145 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006146 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6147 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6148 inFunctionCall, CallType, CheckedVarArgs,
6149 UncoveredArg) {}
6150
Ted Kremenek02087932010-07-16 02:11:22 +00006151 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6152 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006153 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006154
6155 bool HandleInvalidScanfConversionSpecifier(
6156 const analyze_scanf::ScanfSpecifier &FS,
6157 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006158 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006159
Craig Toppere14c0f82014-03-12 04:55:44 +00006160 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006161};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006162} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006163
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006164void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6165 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006166 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6167 getLocationOfByte(end), /*IsStringLocation*/true,
6168 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006169}
6170
Ted Kremenekce815422010-07-19 21:25:57 +00006171bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6172 const analyze_scanf::ScanfSpecifier &FS,
6173 const char *startSpecifier,
6174 unsigned specifierLen) {
6175
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006176 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006177 FS.getConversionSpecifier();
6178
6179 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6180 getLocationOfByte(CS.getStart()),
6181 startSpecifier, specifierLen,
6182 CS.getStart(), CS.getLength());
6183}
6184
Ted Kremenek02087932010-07-16 02:11:22 +00006185bool CheckScanfHandler::HandleScanfSpecifier(
6186 const analyze_scanf::ScanfSpecifier &FS,
6187 const char *startSpecifier,
6188 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006189 using namespace analyze_scanf;
6190 using namespace analyze_format_string;
6191
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006192 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006193
Ted Kremenek6cd69422010-07-19 22:01:06 +00006194 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6195 // be used to decide if we are using positional arguments consistently.
6196 if (FS.consumesDataArgument()) {
6197 if (atFirstArg) {
6198 atFirstArg = false;
6199 usesPositionalArgs = FS.usesPositionalArg();
6200 }
6201 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006202 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6203 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006204 return false;
6205 }
Ted Kremenek02087932010-07-16 02:11:22 +00006206 }
6207
6208 // Check if the field with is non-zero.
6209 const OptionalAmount &Amt = FS.getFieldWidth();
6210 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6211 if (Amt.getConstantAmount() == 0) {
6212 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6213 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006214 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6215 getLocationOfByte(Amt.getStart()),
6216 /*IsStringLocation*/true, R,
6217 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006218 }
6219 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006220
Ted Kremenek02087932010-07-16 02:11:22 +00006221 if (!FS.consumesDataArgument()) {
6222 // FIXME: Technically specifying a precision or field width here
6223 // makes no sense. Worth issuing a warning at some point.
6224 return true;
6225 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006226
Ted Kremenek02087932010-07-16 02:11:22 +00006227 // Consume the argument.
6228 unsigned argIndex = FS.getArgIndex();
6229 if (argIndex < NumDataArgs) {
6230 // The check to see if the argIndex is valid will come later.
6231 // We set the bit here because we may exit early from this
6232 // function if we encounter some other error.
6233 CoveredArgs.set(argIndex);
6234 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006235
Ted Kremenek4407ea42010-07-20 20:04:47 +00006236 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006237 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006238 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6239 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006240 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006241 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006242 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006243 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6244 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006245
Jordan Rose92303592012-09-08 04:00:03 +00006246 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6247 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6248
Ted Kremenek02087932010-07-16 02:11:22 +00006249 // The remaining checks depend on the data arguments.
6250 if (HasVAListArg)
6251 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006252
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006253 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006254 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006255
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006256 // Check that the argument type matches the format specifier.
6257 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006258 if (!Ex)
6259 return true;
6260
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006261 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006262
6263 if (!AT.isValid()) {
6264 return true;
6265 }
6266
Seth Cantrellb4802962015-03-04 03:12:10 +00006267 analyze_format_string::ArgType::MatchKind match =
6268 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006269 if (match == analyze_format_string::ArgType::Match) {
6270 return true;
6271 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006272
Seth Cantrell79340072015-03-04 05:58:08 +00006273 ScanfSpecifier fixedFS = FS;
6274 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6275 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006276
Seth Cantrell79340072015-03-04 05:58:08 +00006277 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6278 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6279 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6280 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006281
Seth Cantrell79340072015-03-04 05:58:08 +00006282 if (success) {
6283 // Get the fix string from the fixed format specifier.
6284 SmallString<128> buf;
6285 llvm::raw_svector_ostream os(buf);
6286 fixedFS.toString(os);
6287
6288 EmitFormatDiagnostic(
6289 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6290 << Ex->getType() << false << Ex->getSourceRange(),
6291 Ex->getLocStart(),
6292 /*IsStringLocation*/ false,
6293 getSpecifierRange(startSpecifier, specifierLen),
6294 FixItHint::CreateReplacement(
6295 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6296 } else {
6297 EmitFormatDiagnostic(S.PDiag(diag)
6298 << AT.getRepresentativeTypeName(S.Context)
6299 << Ex->getType() << false << Ex->getSourceRange(),
6300 Ex->getLocStart(),
6301 /*IsStringLocation*/ false,
6302 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006303 }
6304
Ted Kremenek02087932010-07-16 02:11:22 +00006305 return true;
6306}
6307
Stephen Hines648c3692016-09-16 01:07:04 +00006308static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006309 const Expr *OrigFormatExpr,
6310 ArrayRef<const Expr *> Args,
6311 bool HasVAListArg, unsigned format_idx,
6312 unsigned firstDataArg,
6313 Sema::FormatStringType Type,
6314 bool inFunctionCall,
6315 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006316 llvm::SmallBitVector &CheckedVarArgs,
6317 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006318 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006319 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006320 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006321 S, inFunctionCall, Args[format_idx],
6322 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006323 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006324 return;
6325 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006326
Ted Kremenekab278de2010-01-28 23:39:18 +00006327 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006328 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006329 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006330 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006331 const ConstantArrayType *T =
6332 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006333 assert(T && "String literal not of constant array type!");
6334 size_t TypeSize = T->getSize().getZExtValue();
6335 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006336 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006337
6338 // Emit a warning if the string literal is truncated and does not contain an
6339 // embedded null character.
6340 if (TypeSize <= StrRef.size() &&
6341 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6342 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006343 S, inFunctionCall, Args[format_idx],
6344 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006345 FExpr->getLocStart(),
6346 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6347 return;
6348 }
6349
Ted Kremenekab278de2010-01-28 23:39:18 +00006350 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006351 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006352 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006353 S, inFunctionCall, Args[format_idx],
6354 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006355 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006356 return;
6357 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006358
6359 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006360 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6361 Type == Sema::FST_OSTrace) {
6362 CheckPrintfHandler H(
6363 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6364 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6365 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6366 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006367
Hans Wennborg23926bd2011-12-15 10:25:47 +00006368 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006369 S.getLangOpts(),
6370 S.Context.getTargetInfo(),
6371 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006372 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006373 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006374 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6375 numDataArgs, Str, HasVAListArg, Args, format_idx,
6376 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006377
Hans Wennborg23926bd2011-12-15 10:25:47 +00006378 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006379 S.getLangOpts(),
6380 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006381 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006382 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006383}
6384
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006385bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6386 // Str - The format string. NOTE: this is NOT null-terminated!
6387 StringRef StrRef = FExpr->getString();
6388 const char *Str = StrRef.data();
6389 // Account for cases where the string literal is truncated in a declaration.
6390 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6391 assert(T && "String literal not of constant array type!");
6392 size_t TypeSize = T->getSize().getZExtValue();
6393 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6394 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6395 getLangOpts(),
6396 Context.getTargetInfo());
6397}
6398
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006399//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6400
6401// Returns the related absolute value function that is larger, of 0 if one
6402// does not exist.
6403static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6404 switch (AbsFunction) {
6405 default:
6406 return 0;
6407
6408 case Builtin::BI__builtin_abs:
6409 return Builtin::BI__builtin_labs;
6410 case Builtin::BI__builtin_labs:
6411 return Builtin::BI__builtin_llabs;
6412 case Builtin::BI__builtin_llabs:
6413 return 0;
6414
6415 case Builtin::BI__builtin_fabsf:
6416 return Builtin::BI__builtin_fabs;
6417 case Builtin::BI__builtin_fabs:
6418 return Builtin::BI__builtin_fabsl;
6419 case Builtin::BI__builtin_fabsl:
6420 return 0;
6421
6422 case Builtin::BI__builtin_cabsf:
6423 return Builtin::BI__builtin_cabs;
6424 case Builtin::BI__builtin_cabs:
6425 return Builtin::BI__builtin_cabsl;
6426 case Builtin::BI__builtin_cabsl:
6427 return 0;
6428
6429 case Builtin::BIabs:
6430 return Builtin::BIlabs;
6431 case Builtin::BIlabs:
6432 return Builtin::BIllabs;
6433 case Builtin::BIllabs:
6434 return 0;
6435
6436 case Builtin::BIfabsf:
6437 return Builtin::BIfabs;
6438 case Builtin::BIfabs:
6439 return Builtin::BIfabsl;
6440 case Builtin::BIfabsl:
6441 return 0;
6442
6443 case Builtin::BIcabsf:
6444 return Builtin::BIcabs;
6445 case Builtin::BIcabs:
6446 return Builtin::BIcabsl;
6447 case Builtin::BIcabsl:
6448 return 0;
6449 }
6450}
6451
6452// Returns the argument type of the absolute value function.
6453static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6454 unsigned AbsType) {
6455 if (AbsType == 0)
6456 return QualType();
6457
6458 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6459 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6460 if (Error != ASTContext::GE_None)
6461 return QualType();
6462
6463 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6464 if (!FT)
6465 return QualType();
6466
6467 if (FT->getNumParams() != 1)
6468 return QualType();
6469
6470 return FT->getParamType(0);
6471}
6472
6473// Returns the best absolute value function, or zero, based on type and
6474// current absolute value function.
6475static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6476 unsigned AbsFunctionKind) {
6477 unsigned BestKind = 0;
6478 uint64_t ArgSize = Context.getTypeSize(ArgType);
6479 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6480 Kind = getLargerAbsoluteValueFunction(Kind)) {
6481 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6482 if (Context.getTypeSize(ParamType) >= ArgSize) {
6483 if (BestKind == 0)
6484 BestKind = Kind;
6485 else if (Context.hasSameType(ParamType, ArgType)) {
6486 BestKind = Kind;
6487 break;
6488 }
6489 }
6490 }
6491 return BestKind;
6492}
6493
6494enum AbsoluteValueKind {
6495 AVK_Integer,
6496 AVK_Floating,
6497 AVK_Complex
6498};
6499
6500static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6501 if (T->isIntegralOrEnumerationType())
6502 return AVK_Integer;
6503 if (T->isRealFloatingType())
6504 return AVK_Floating;
6505 if (T->isAnyComplexType())
6506 return AVK_Complex;
6507
6508 llvm_unreachable("Type not integer, floating, or complex");
6509}
6510
6511// Changes the absolute value function to a different type. Preserves whether
6512// the function is a builtin.
6513static unsigned changeAbsFunction(unsigned AbsKind,
6514 AbsoluteValueKind ValueKind) {
6515 switch (ValueKind) {
6516 case AVK_Integer:
6517 switch (AbsKind) {
6518 default:
6519 return 0;
6520 case Builtin::BI__builtin_fabsf:
6521 case Builtin::BI__builtin_fabs:
6522 case Builtin::BI__builtin_fabsl:
6523 case Builtin::BI__builtin_cabsf:
6524 case Builtin::BI__builtin_cabs:
6525 case Builtin::BI__builtin_cabsl:
6526 return Builtin::BI__builtin_abs;
6527 case Builtin::BIfabsf:
6528 case Builtin::BIfabs:
6529 case Builtin::BIfabsl:
6530 case Builtin::BIcabsf:
6531 case Builtin::BIcabs:
6532 case Builtin::BIcabsl:
6533 return Builtin::BIabs;
6534 }
6535 case AVK_Floating:
6536 switch (AbsKind) {
6537 default:
6538 return 0;
6539 case Builtin::BI__builtin_abs:
6540 case Builtin::BI__builtin_labs:
6541 case Builtin::BI__builtin_llabs:
6542 case Builtin::BI__builtin_cabsf:
6543 case Builtin::BI__builtin_cabs:
6544 case Builtin::BI__builtin_cabsl:
6545 return Builtin::BI__builtin_fabsf;
6546 case Builtin::BIabs:
6547 case Builtin::BIlabs:
6548 case Builtin::BIllabs:
6549 case Builtin::BIcabsf:
6550 case Builtin::BIcabs:
6551 case Builtin::BIcabsl:
6552 return Builtin::BIfabsf;
6553 }
6554 case AVK_Complex:
6555 switch (AbsKind) {
6556 default:
6557 return 0;
6558 case Builtin::BI__builtin_abs:
6559 case Builtin::BI__builtin_labs:
6560 case Builtin::BI__builtin_llabs:
6561 case Builtin::BI__builtin_fabsf:
6562 case Builtin::BI__builtin_fabs:
6563 case Builtin::BI__builtin_fabsl:
6564 return Builtin::BI__builtin_cabsf;
6565 case Builtin::BIabs:
6566 case Builtin::BIlabs:
6567 case Builtin::BIllabs:
6568 case Builtin::BIfabsf:
6569 case Builtin::BIfabs:
6570 case Builtin::BIfabsl:
6571 return Builtin::BIcabsf;
6572 }
6573 }
6574 llvm_unreachable("Unable to convert function");
6575}
6576
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006577static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006578 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6579 if (!FnInfo)
6580 return 0;
6581
6582 switch (FDecl->getBuiltinID()) {
6583 default:
6584 return 0;
6585 case Builtin::BI__builtin_abs:
6586 case Builtin::BI__builtin_fabs:
6587 case Builtin::BI__builtin_fabsf:
6588 case Builtin::BI__builtin_fabsl:
6589 case Builtin::BI__builtin_labs:
6590 case Builtin::BI__builtin_llabs:
6591 case Builtin::BI__builtin_cabs:
6592 case Builtin::BI__builtin_cabsf:
6593 case Builtin::BI__builtin_cabsl:
6594 case Builtin::BIabs:
6595 case Builtin::BIlabs:
6596 case Builtin::BIllabs:
6597 case Builtin::BIfabs:
6598 case Builtin::BIfabsf:
6599 case Builtin::BIfabsl:
6600 case Builtin::BIcabs:
6601 case Builtin::BIcabsf:
6602 case Builtin::BIcabsl:
6603 return FDecl->getBuiltinID();
6604 }
6605 llvm_unreachable("Unknown Builtin type");
6606}
6607
6608// If the replacement is valid, emit a note with replacement function.
6609// Additionally, suggest including the proper header if not already included.
6610static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006611 unsigned AbsKind, QualType ArgType) {
6612 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006613 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006614 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006615 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6616 FunctionName = "std::abs";
6617 if (ArgType->isIntegralOrEnumerationType()) {
6618 HeaderName = "cstdlib";
6619 } else if (ArgType->isRealFloatingType()) {
6620 HeaderName = "cmath";
6621 } else {
6622 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006623 }
Richard Trieubeffb832014-04-15 23:47:53 +00006624
6625 // Lookup all std::abs
6626 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006627 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006628 R.suppressDiagnostics();
6629 S.LookupQualifiedName(R, Std);
6630
6631 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006632 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006633 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6634 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6635 } else {
6636 FDecl = dyn_cast<FunctionDecl>(I);
6637 }
6638 if (!FDecl)
6639 continue;
6640
6641 // Found std::abs(), check that they are the right ones.
6642 if (FDecl->getNumParams() != 1)
6643 continue;
6644
6645 // Check that the parameter type can handle the argument.
6646 QualType ParamType = FDecl->getParamDecl(0)->getType();
6647 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6648 S.Context.getTypeSize(ArgType) <=
6649 S.Context.getTypeSize(ParamType)) {
6650 // Found a function, don't need the header hint.
6651 EmitHeaderHint = false;
6652 break;
6653 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006654 }
Richard Trieubeffb832014-04-15 23:47:53 +00006655 }
6656 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006657 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006658 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6659
6660 if (HeaderName) {
6661 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6662 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6663 R.suppressDiagnostics();
6664 S.LookupName(R, S.getCurScope());
6665
6666 if (R.isSingleResult()) {
6667 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6668 if (FD && FD->getBuiltinID() == AbsKind) {
6669 EmitHeaderHint = false;
6670 } else {
6671 return;
6672 }
6673 } else if (!R.empty()) {
6674 return;
6675 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006676 }
6677 }
6678
6679 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006680 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006681
Richard Trieubeffb832014-04-15 23:47:53 +00006682 if (!HeaderName)
6683 return;
6684
6685 if (!EmitHeaderHint)
6686 return;
6687
Alp Toker5d96e0a2014-07-11 20:53:51 +00006688 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6689 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006690}
6691
Richard Trieua7f30b12016-12-06 01:42:28 +00006692template <std::size_t StrLen>
6693static bool IsStdFunction(const FunctionDecl *FDecl,
6694 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006695 if (!FDecl)
6696 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006697 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006698 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006699 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006700 return false;
6701
6702 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006703}
6704
6705// Warn when using the wrong abs() function.
6706void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006707 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006708 if (Call->getNumArgs() != 1)
6709 return;
6710
6711 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006712 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006713 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006714 return;
6715
6716 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6717 QualType ParamType = Call->getArg(0)->getType();
6718
Alp Toker5d96e0a2014-07-11 20:53:51 +00006719 // Unsigned types cannot be negative. Suggest removing the absolute value
6720 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006721 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006722 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006723 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006724 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6725 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006726 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006727 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6728 return;
6729 }
6730
David Majnemer7f77eb92015-11-15 03:04:34 +00006731 // Taking the absolute value of a pointer is very suspicious, they probably
6732 // wanted to index into an array, dereference a pointer, call a function, etc.
6733 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6734 unsigned DiagType = 0;
6735 if (ArgType->isFunctionType())
6736 DiagType = 1;
6737 else if (ArgType->isArrayType())
6738 DiagType = 2;
6739
6740 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6741 return;
6742 }
6743
Richard Trieubeffb832014-04-15 23:47:53 +00006744 // std::abs has overloads which prevent most of the absolute value problems
6745 // from occurring.
6746 if (IsStdAbs)
6747 return;
6748
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006749 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6750 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6751
6752 // The argument and parameter are the same kind. Check if they are the right
6753 // size.
6754 if (ArgValueKind == ParamValueKind) {
6755 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6756 return;
6757
6758 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6759 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6760 << FDecl << ArgType << ParamType;
6761
6762 if (NewAbsKind == 0)
6763 return;
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 return;
6768 }
6769
6770 // ArgValueKind != ParamValueKind
6771 // The wrong type of absolute value function was used. Attempt to find the
6772 // proper one.
6773 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6774 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6775 if (NewAbsKind == 0)
6776 return;
6777
6778 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6779 << FDecl << ParamValueKind << ArgValueKind;
6780
6781 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006782 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006783}
6784
Richard Trieu67c00712016-12-05 23:41:46 +00006785//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006786void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6787 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006788 if (!Call || !FDecl) return;
6789
6790 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006791 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006792 if (Call->getExprLoc().isMacroID()) return;
6793
6794 // Only care about the one template argument, two function parameter std::max
6795 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006796 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006797 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6798 if (!ArgList) return;
6799 if (ArgList->size() != 1) return;
6800
6801 // Check that template type argument is unsigned integer.
6802 const auto& TA = ArgList->get(0);
6803 if (TA.getKind() != TemplateArgument::Type) return;
6804 QualType ArgType = TA.getAsType();
6805 if (!ArgType->isUnsignedIntegerType()) return;
6806
6807 // See if either argument is a literal zero.
6808 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6809 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6810 if (!MTE) return false;
6811 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6812 if (!Num) return false;
6813 if (Num->getValue() != 0) return false;
6814 return true;
6815 };
6816
6817 const Expr *FirstArg = Call->getArg(0);
6818 const Expr *SecondArg = Call->getArg(1);
6819 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6820 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6821
6822 // Only warn when exactly one argument is zero.
6823 if (IsFirstArgZero == IsSecondArgZero) return;
6824
6825 SourceRange FirstRange = FirstArg->getSourceRange();
6826 SourceRange SecondRange = SecondArg->getSourceRange();
6827
6828 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
6829
6830 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
6831 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
6832
6833 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
6834 SourceRange RemovalRange;
6835 if (IsFirstArgZero) {
6836 RemovalRange = SourceRange(FirstRange.getBegin(),
6837 SecondRange.getBegin().getLocWithOffset(-1));
6838 } else {
6839 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
6840 SecondRange.getEnd());
6841 }
6842
6843 Diag(Call->getExprLoc(), diag::note_remove_max_call)
6844 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
6845 << FixItHint::CreateRemoval(RemovalRange);
6846}
6847
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006848//===--- CHECK: Standard memory functions ---------------------------------===//
6849
Nico Weber0e6daef2013-12-26 23:38:39 +00006850/// \brief Takes the expression passed to the size_t parameter of functions
6851/// such as memcmp, strncat, etc and warns if it's a comparison.
6852///
6853/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6854static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6855 IdentifierInfo *FnName,
6856 SourceLocation FnLoc,
6857 SourceLocation RParenLoc) {
6858 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6859 if (!Size)
6860 return false;
6861
6862 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6863 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6864 return false;
6865
Nico Weber0e6daef2013-12-26 23:38:39 +00006866 SourceRange SizeRange = Size->getSourceRange();
6867 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6868 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006869 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006870 << FnName << FixItHint::CreateInsertion(
6871 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006872 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006873 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006874 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006875 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6876 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006877
6878 return true;
6879}
6880
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006881/// \brief Determine whether the given type is or contains a dynamic class type
6882/// (e.g., whether it has a vtable).
6883static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6884 bool &IsContained) {
6885 // Look through array types while ignoring qualifiers.
6886 const Type *Ty = T->getBaseElementTypeUnsafe();
6887 IsContained = false;
6888
6889 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6890 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006891 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006892 return nullptr;
6893
6894 if (RD->isDynamicClass())
6895 return RD;
6896
6897 // Check all the fields. If any bases were dynamic, the class is dynamic.
6898 // It's impossible for a class to transitively contain itself by value, so
6899 // infinite recursion is impossible.
6900 for (auto *FD : RD->fields()) {
6901 bool SubContained;
6902 if (const CXXRecordDecl *ContainedRD =
6903 getContainedDynamicClass(FD->getType(), SubContained)) {
6904 IsContained = true;
6905 return ContainedRD;
6906 }
6907 }
6908
6909 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006910}
6911
Chandler Carruth889ed862011-06-21 23:04:20 +00006912/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006913/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006914static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006915 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006916 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6917 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6918 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006919
Craig Topperc3ec1492014-05-26 06:22:03 +00006920 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006921}
6922
Chandler Carruth889ed862011-06-21 23:04:20 +00006923/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006924static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006925 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6926 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6927 if (SizeOf->getKind() == clang::UETT_SizeOf)
6928 return SizeOf->getTypeOfArgument();
6929
6930 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006931}
6932
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006933/// \brief Check for dangerous or invalid arguments to memset().
6934///
Chandler Carruthac687262011-06-03 06:23:57 +00006935/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006936/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6937/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006938///
6939/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006940void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006941 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006942 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006943 assert(BId != 0);
6944
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006945 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006946 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006947 unsigned ExpectedNumArgs =
6948 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006949 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006950 return;
6951
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006952 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006953 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006954 unsigned LenArg =
6955 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006956 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006957
Nico Weber0e6daef2013-12-26 23:38:39 +00006958 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6959 Call->getLocStart(), Call->getRParenLoc()))
6960 return;
6961
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006962 // We have special checking when the length is a sizeof expression.
6963 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6964 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6965 llvm::FoldingSetNodeID SizeOfArgID;
6966
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006967 // Although widely used, 'bzero' is not a standard function. Be more strict
6968 // with the argument types before allowing diagnostics and only allow the
6969 // form bzero(ptr, sizeof(...)).
6970 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6971 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6972 return;
6973
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006974 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6975 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006976 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006977
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006978 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006979 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006980 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006981 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006982
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006983 // Never warn about void type pointers. This can be used to suppress
6984 // false positives.
6985 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006986 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006987
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006988 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6989 // actually comparing the expressions for equality. Because computing the
6990 // expression IDs can be expensive, we only do this if the diagnostic is
6991 // enabled.
6992 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006993 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6994 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006995 // We only compute IDs for expressions if the warning is enabled, and
6996 // cache the sizeof arg's ID.
6997 if (SizeOfArgID == llvm::FoldingSetNodeID())
6998 SizeOfArg->Profile(SizeOfArgID, Context, true);
6999 llvm::FoldingSetNodeID DestID;
7000 Dest->Profile(DestID, Context, true);
7001 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007002 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7003 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007004 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007005 StringRef ReadableName = FnName->getName();
7006
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007007 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007008 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007009 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007010 if (!PointeeTy->isIncompleteType() &&
7011 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007012 ActionIdx = 2; // If the pointee's size is sizeof(char),
7013 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007014
7015 // If the function is defined as a builtin macro, do not show macro
7016 // expansion.
7017 SourceLocation SL = SizeOfArg->getExprLoc();
7018 SourceRange DSR = Dest->getSourceRange();
7019 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007020 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007021
7022 if (SM.isMacroArgExpansion(SL)) {
7023 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7024 SL = SM.getSpellingLoc(SL);
7025 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7026 SM.getSpellingLoc(DSR.getEnd()));
7027 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7028 SM.getSpellingLoc(SSR.getEnd()));
7029 }
7030
Anna Zaksd08d9152012-05-30 23:14:52 +00007031 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007032 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007033 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007034 << PointeeTy
7035 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007036 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007037 << SSR);
7038 DiagRuntimeBehavior(SL, SizeOfArg,
7039 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7040 << ActionIdx
7041 << SSR);
7042
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007043 break;
7044 }
7045 }
7046
7047 // Also check for cases where the sizeof argument is the exact same
7048 // type as the memory argument, and where it points to a user-defined
7049 // record type.
7050 if (SizeOfArgTy != QualType()) {
7051 if (PointeeTy->isRecordType() &&
7052 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7053 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7054 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7055 << FnName << SizeOfArgTy << ArgIdx
7056 << PointeeTy << Dest->getSourceRange()
7057 << LenExpr->getSourceRange());
7058 break;
7059 }
Nico Weberc5e73862011-06-14 16:14:58 +00007060 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007061 } else if (DestTy->isArrayType()) {
7062 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007063 }
Nico Weberc5e73862011-06-14 16:14:58 +00007064
Nico Weberc44b35e2015-03-21 17:37:46 +00007065 if (PointeeTy == QualType())
7066 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007067
Nico Weberc44b35e2015-03-21 17:37:46 +00007068 // Always complain about dynamic classes.
7069 bool IsContained;
7070 if (const CXXRecordDecl *ContainedRD =
7071 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007072
Nico Weberc44b35e2015-03-21 17:37:46 +00007073 unsigned OperationType = 0;
7074 // "overwritten" if we're warning about the destination for any call
7075 // but memcmp; otherwise a verb appropriate to the call.
7076 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7077 if (BId == Builtin::BImemcpy)
7078 OperationType = 1;
7079 else if(BId == Builtin::BImemmove)
7080 OperationType = 2;
7081 else if (BId == Builtin::BImemcmp)
7082 OperationType = 3;
7083 }
7084
John McCall31168b02011-06-15 23:02:42 +00007085 DiagRuntimeBehavior(
7086 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007087 PDiag(diag::warn_dyn_class_memaccess)
7088 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7089 << FnName << IsContained << ContainedRD << OperationType
7090 << Call->getCallee()->getSourceRange());
7091 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7092 BId != Builtin::BImemset)
7093 DiagRuntimeBehavior(
7094 Dest->getExprLoc(), Dest,
7095 PDiag(diag::warn_arc_object_memaccess)
7096 << ArgIdx << FnName << PointeeTy
7097 << Call->getCallee()->getSourceRange());
7098 else
7099 continue;
7100
7101 DiagRuntimeBehavior(
7102 Dest->getExprLoc(), Dest,
7103 PDiag(diag::note_bad_memaccess_silence)
7104 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7105 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007106 }
7107}
7108
Ted Kremenek6865f772011-08-18 20:55:45 +00007109// A little helper routine: ignore addition and subtraction of integer literals.
7110// This intentionally does not ignore all integer constant expressions because
7111// we don't want to remove sizeof().
7112static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7113 Ex = Ex->IgnoreParenCasts();
7114
7115 for (;;) {
7116 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7117 if (!BO || !BO->isAdditiveOp())
7118 break;
7119
7120 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7121 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7122
7123 if (isa<IntegerLiteral>(RHS))
7124 Ex = LHS;
7125 else if (isa<IntegerLiteral>(LHS))
7126 Ex = RHS;
7127 else
7128 break;
7129 }
7130
7131 return Ex;
7132}
7133
Anna Zaks13b08572012-08-08 21:42:23 +00007134static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7135 ASTContext &Context) {
7136 // Only handle constant-sized or VLAs, but not flexible members.
7137 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7138 // Only issue the FIXIT for arrays of size > 1.
7139 if (CAT->getSize().getSExtValue() <= 1)
7140 return false;
7141 } else if (!Ty->isVariableArrayType()) {
7142 return false;
7143 }
7144 return true;
7145}
7146
Ted Kremenek6865f772011-08-18 20:55:45 +00007147// Warn if the user has made the 'size' argument to strlcpy or strlcat
7148// be the size of the source, instead of the destination.
7149void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7150 IdentifierInfo *FnName) {
7151
7152 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007153 unsigned NumArgs = Call->getNumArgs();
7154 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007155 return;
7156
7157 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7158 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007159 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007160
7161 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7162 Call->getLocStart(), Call->getRParenLoc()))
7163 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007164
7165 // Look for 'strlcpy(dst, x, sizeof(x))'
7166 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7167 CompareWithSrc = Ex;
7168 else {
7169 // Look for 'strlcpy(dst, x, strlen(x))'
7170 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007171 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7172 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007173 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7174 }
7175 }
7176
7177 if (!CompareWithSrc)
7178 return;
7179
7180 // Determine if the argument to sizeof/strlen is equal to the source
7181 // argument. In principle there's all kinds of things you could do
7182 // here, for instance creating an == expression and evaluating it with
7183 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7184 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7185 if (!SrcArgDRE)
7186 return;
7187
7188 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7189 if (!CompareWithSrcDRE ||
7190 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7191 return;
7192
7193 const Expr *OriginalSizeArg = Call->getArg(2);
7194 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7195 << OriginalSizeArg->getSourceRange() << FnName;
7196
7197 // Output a FIXIT hint if the destination is an array (rather than a
7198 // pointer to an array). This could be enhanced to handle some
7199 // pointers if we know the actual size, like if DstArg is 'array+2'
7200 // we could say 'sizeof(array)-2'.
7201 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007202 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007203 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007204
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007205 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007206 llvm::raw_svector_ostream OS(sizeString);
7207 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007208 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007209 OS << ")";
7210
7211 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7212 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7213 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007214}
7215
Anna Zaks314cd092012-02-01 19:08:57 +00007216/// Check if two expressions refer to the same declaration.
7217static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7218 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7219 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7220 return D1->getDecl() == D2->getDecl();
7221 return false;
7222}
7223
7224static const Expr *getStrlenExprArg(const Expr *E) {
7225 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7226 const FunctionDecl *FD = CE->getDirectCallee();
7227 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007228 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007229 return CE->getArg(0)->IgnoreParenCasts();
7230 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007231 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007232}
7233
7234// Warn on anti-patterns as the 'size' argument to strncat.
7235// The correct size argument should look like following:
7236// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7237void Sema::CheckStrncatArguments(const CallExpr *CE,
7238 IdentifierInfo *FnName) {
7239 // Don't crash if the user has the wrong number of arguments.
7240 if (CE->getNumArgs() < 3)
7241 return;
7242 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7243 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7244 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7245
Nico Weber0e6daef2013-12-26 23:38:39 +00007246 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7247 CE->getRParenLoc()))
7248 return;
7249
Anna Zaks314cd092012-02-01 19:08:57 +00007250 // Identify common expressions, which are wrongly used as the size argument
7251 // to strncat and may lead to buffer overflows.
7252 unsigned PatternType = 0;
7253 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7254 // - sizeof(dst)
7255 if (referToTheSameDecl(SizeOfArg, DstArg))
7256 PatternType = 1;
7257 // - sizeof(src)
7258 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7259 PatternType = 2;
7260 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7261 if (BE->getOpcode() == BO_Sub) {
7262 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7263 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7264 // - sizeof(dst) - strlen(dst)
7265 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7266 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7267 PatternType = 1;
7268 // - sizeof(src) - (anything)
7269 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7270 PatternType = 2;
7271 }
7272 }
7273
7274 if (PatternType == 0)
7275 return;
7276
Anna Zaks5069aa32012-02-03 01:27:37 +00007277 // Generate the diagnostic.
7278 SourceLocation SL = LenArg->getLocStart();
7279 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007280 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007281
7282 // If the function is defined as a builtin macro, do not show macro expansion.
7283 if (SM.isMacroArgExpansion(SL)) {
7284 SL = SM.getSpellingLoc(SL);
7285 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7286 SM.getSpellingLoc(SR.getEnd()));
7287 }
7288
Anna Zaks13b08572012-08-08 21:42:23 +00007289 // Check if the destination is an array (rather than a pointer to an array).
7290 QualType DstTy = DstArg->getType();
7291 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7292 Context);
7293 if (!isKnownSizeArray) {
7294 if (PatternType == 1)
7295 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7296 else
7297 Diag(SL, diag::warn_strncat_src_size) << SR;
7298 return;
7299 }
7300
Anna Zaks314cd092012-02-01 19:08:57 +00007301 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007302 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007303 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007304 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007305
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007306 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007307 llvm::raw_svector_ostream OS(sizeString);
7308 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007309 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007310 OS << ") - ";
7311 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007312 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007313 OS << ") - 1";
7314
Anna Zaks5069aa32012-02-03 01:27:37 +00007315 Diag(SL, diag::note_strncat_wrong_size)
7316 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007317}
7318
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007319//===--- CHECK: Return Address of Stack Variable --------------------------===//
7320
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007321static const Expr *EvalVal(const Expr *E,
7322 SmallVectorImpl<const DeclRefExpr *> &refVars,
7323 const Decl *ParentDecl);
7324static const Expr *EvalAddr(const Expr *E,
7325 SmallVectorImpl<const DeclRefExpr *> &refVars,
7326 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007327
7328/// CheckReturnStackAddr - Check if a return statement returns the address
7329/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007330static void
7331CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7332 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007333
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007334 const Expr *stackE = nullptr;
7335 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007336
7337 // Perform checking for returned stack addresses, local blocks,
7338 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007339 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007340 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007341 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007342 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007343 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007344 }
7345
Craig Topperc3ec1492014-05-26 06:22:03 +00007346 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007347 return; // Nothing suspicious was found.
7348
Richard Trieu81b6c562016-08-05 23:24:47 +00007349 // Parameters are initalized in the calling scope, so taking the address
7350 // of a parameter reference doesn't need a warning.
7351 for (auto *DRE : refVars)
7352 if (isa<ParmVarDecl>(DRE->getDecl()))
7353 return;
7354
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007355 SourceLocation diagLoc;
7356 SourceRange diagRange;
7357 if (refVars.empty()) {
7358 diagLoc = stackE->getLocStart();
7359 diagRange = stackE->getSourceRange();
7360 } else {
7361 // We followed through a reference variable. 'stackE' contains the
7362 // problematic expression but we will warn at the return statement pointing
7363 // at the reference variable. We will later display the "trail" of
7364 // reference variables using notes.
7365 diagLoc = refVars[0]->getLocStart();
7366 diagRange = refVars[0]->getSourceRange();
7367 }
7368
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007369 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7370 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007371 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007372 << DR->getDecl()->getDeclName() << diagRange;
7373 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007374 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007375 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007376 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007377 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007378 // If there is an LValue->RValue conversion, then the value of the
7379 // reference type is used, not the reference.
7380 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7381 if (ICE->getCastKind() == CK_LValueToRValue) {
7382 return;
7383 }
7384 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007385 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7386 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007387 }
7388
7389 // Display the "trail" of reference variables that we followed until we
7390 // found the problematic expression using notes.
7391 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007392 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007393 // If this var binds to another reference var, show the range of the next
7394 // var, otherwise the var binds to the problematic expression, in which case
7395 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007396 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7397 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007398 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7399 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007400 }
7401}
7402
7403/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7404/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007405/// to a location on the stack, a local block, an address of a label, or a
7406/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007407/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007408/// encounter a subexpression that (1) clearly does not lead to one of the
7409/// above problematic expressions (2) is something we cannot determine leads to
7410/// a problematic expression based on such local checking.
7411///
7412/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7413/// the expression that they point to. Such variables are added to the
7414/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007415///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007416/// EvalAddr processes expressions that are pointers that are used as
7417/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007418/// At the base case of the recursion is a check for the above problematic
7419/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007420///
7421/// This implementation handles:
7422///
7423/// * pointer-to-pointer casts
7424/// * implicit conversions from array references to pointers
7425/// * taking the address of fields
7426/// * arbitrary interplay between "&" and "*" operators
7427/// * pointer arithmetic from an address of a stack variable
7428/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007429static const Expr *EvalAddr(const Expr *E,
7430 SmallVectorImpl<const DeclRefExpr *> &refVars,
7431 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007432 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007433 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007434
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007435 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007436 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007437 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007438 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007439 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007440
Peter Collingbourne91147592011-04-15 00:35:48 +00007441 E = E->IgnoreParens();
7442
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007443 // Our "symbolic interpreter" is just a dispatch off the currently
7444 // viewed AST node. We then recursively traverse the AST by calling
7445 // EvalAddr and EvalVal appropriately.
7446 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007447 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007448 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007449
Richard Smith40f08eb2014-01-30 22:05:38 +00007450 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007451 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007452 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007453
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007454 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007455 // If this is a reference variable, follow through to the expression that
7456 // it points to.
7457 if (V->hasLocalStorage() &&
7458 V->getType()->isReferenceType() && V->hasInit()) {
7459 // Add the reference variable to the "trail".
7460 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007461 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007462 }
7463
Craig Topperc3ec1492014-05-26 06:22:03 +00007464 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007465 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007466
Chris Lattner934edb22007-12-28 05:31:15 +00007467 case Stmt::UnaryOperatorClass: {
7468 // The only unary operator that make sense to handle here
7469 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007470 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007471
John McCalle3027922010-08-25 11:45:40 +00007472 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007473 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007474 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007475 }
Mike Stump11289f42009-09-09 15:08:12 +00007476
Chris Lattner934edb22007-12-28 05:31:15 +00007477 case Stmt::BinaryOperatorClass: {
7478 // Handle pointer arithmetic. All other binary operators are not valid
7479 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007480 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007481 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007482
John McCalle3027922010-08-25 11:45:40 +00007483 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007484 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007485
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007486 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007487
7488 // Determine which argument is the real pointer base. It could be
7489 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007490 if (!Base->getType()->isPointerType())
7491 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007492
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007493 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007494 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007495 }
Steve Naroff2752a172008-09-10 19:17:48 +00007496
Chris Lattner934edb22007-12-28 05:31:15 +00007497 // For conditional operators we need to see if either the LHS or RHS are
7498 // valid DeclRefExpr*s. If one of them is valid, we return it.
7499 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007500 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007501
Chris Lattner934edb22007-12-28 05:31:15 +00007502 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007503 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007504 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007505 // In C++, we can have a throw-expression, which has 'void' type.
7506 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007507 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007508 return LHS;
7509 }
Chris Lattner934edb22007-12-28 05:31:15 +00007510
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007511 // In C++, we can have a throw-expression, which has 'void' type.
7512 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007513 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007514
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007515 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007516 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007517
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007518 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007519 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007520 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007521 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007522
7523 case Stmt::AddrLabelExprClass:
7524 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007525
John McCall28fc7092011-11-10 05:35:25 +00007526 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007527 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7528 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007529
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007530 // For casts, we need to handle conversions from arrays to
7531 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007532 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007533 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007534 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007535 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007536 case Stmt::CXXStaticCastExprClass:
7537 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007538 case Stmt::CXXConstCastExprClass:
7539 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007540 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007541 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007542 case CK_LValueToRValue:
7543 case CK_NoOp:
7544 case CK_BaseToDerived:
7545 case CK_DerivedToBase:
7546 case CK_UncheckedDerivedToBase:
7547 case CK_Dynamic:
7548 case CK_CPointerToObjCPointerCast:
7549 case CK_BlockPointerToObjCPointerCast:
7550 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007551 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007552
7553 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007554 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007555
Richard Trieudadefde2014-07-02 04:39:38 +00007556 case CK_BitCast:
7557 if (SubExpr->getType()->isAnyPointerType() ||
7558 SubExpr->getType()->isBlockPointerType() ||
7559 SubExpr->getType()->isObjCQualifiedIdType())
7560 return EvalAddr(SubExpr, refVars, ParentDecl);
7561 else
7562 return nullptr;
7563
Eli Friedman8195ad72012-02-23 23:04:32 +00007564 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007565 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007566 }
Chris Lattner934edb22007-12-28 05:31:15 +00007567 }
Mike Stump11289f42009-09-09 15:08:12 +00007568
Douglas Gregorfe314812011-06-21 17:03:29 +00007569 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007570 if (const Expr *Result =
7571 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7572 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007573 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007574 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007575
Chris Lattner934edb22007-12-28 05:31:15 +00007576 // Everything else: we simply don't reason about them.
7577 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007578 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007579 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007580}
Mike Stump11289f42009-09-09 15:08:12 +00007581
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007582/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7583/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007584static const Expr *EvalVal(const Expr *E,
7585 SmallVectorImpl<const DeclRefExpr *> &refVars,
7586 const Decl *ParentDecl) {
7587 do {
7588 // We should only be called for evaluating non-pointer expressions, or
7589 // expressions with a pointer type that are not used as references but
7590 // instead
7591 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007592
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007593 // Our "symbolic interpreter" is just a dispatch off the currently
7594 // viewed AST node. We then recursively traverse the AST by calling
7595 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007596
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007597 E = E->IgnoreParens();
7598 switch (E->getStmtClass()) {
7599 case Stmt::ImplicitCastExprClass: {
7600 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7601 if (IE->getValueKind() == VK_LValue) {
7602 E = IE->getSubExpr();
7603 continue;
7604 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007605 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007606 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007607
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007608 case Stmt::ExprWithCleanupsClass:
7609 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7610 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007611
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007612 case Stmt::DeclRefExprClass: {
7613 // When we hit a DeclRefExpr we are looking at code that refers to a
7614 // variable's name. If it's not a reference variable we check if it has
7615 // local storage within the function, and if so, return the expression.
7616 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7617
7618 // If we leave the immediate function, the lifetime isn't about to end.
7619 if (DR->refersToEnclosingVariableOrCapture())
7620 return nullptr;
7621
7622 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7623 // Check if it refers to itself, e.g. "int& i = i;".
7624 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007625 return DR;
7626
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007627 if (V->hasLocalStorage()) {
7628 if (!V->getType()->isReferenceType())
7629 return DR;
7630
7631 // Reference variable, follow through to the expression that
7632 // it points to.
7633 if (V->hasInit()) {
7634 // Add the reference variable to the "trail".
7635 refVars.push_back(DR);
7636 return EvalVal(V->getInit(), refVars, V);
7637 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007638 }
7639 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007640
7641 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007642 }
Mike Stump11289f42009-09-09 15:08:12 +00007643
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007644 case Stmt::UnaryOperatorClass: {
7645 // The only unary operator that make sense to handle here
7646 // is Deref. All others don't resolve to a "name." This includes
7647 // handling all sorts of rvalues passed to a unary operator.
7648 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007649
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007650 if (U->getOpcode() == UO_Deref)
7651 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007652
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007653 return nullptr;
7654 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007655
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007656 case Stmt::ArraySubscriptExprClass: {
7657 // Array subscripts are potential references to data on the stack. We
7658 // retrieve the DeclRefExpr* for the array variable if it indeed
7659 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007660 const auto *ASE = cast<ArraySubscriptExpr>(E);
7661 if (ASE->isTypeDependent())
7662 return nullptr;
7663 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007664 }
Mike Stump11289f42009-09-09 15:08:12 +00007665
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007666 case Stmt::OMPArraySectionExprClass: {
7667 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7668 ParentDecl);
7669 }
Mike Stump11289f42009-09-09 15:08:12 +00007670
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007671 case Stmt::ConditionalOperatorClass: {
7672 // For conditional operators we need to see if either the LHS or RHS are
7673 // non-NULL Expr's. If one is non-NULL, we return it.
7674 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007675
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007676 // Handle the GNU extension for missing LHS.
7677 if (const Expr *LHSExpr = C->getLHS()) {
7678 // In C++, we can have a throw-expression, which has 'void' type.
7679 if (!LHSExpr->getType()->isVoidType())
7680 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7681 return LHS;
7682 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007683
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007684 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007685 if (C->getRHS()->getType()->isVoidType())
7686 return nullptr;
7687
7688 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007689 }
7690
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007691 // Accesses to members are potential references to data on the stack.
7692 case Stmt::MemberExprClass: {
7693 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007694
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007695 // Check for indirect access. We only want direct field accesses.
7696 if (M->isArrow())
7697 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007698
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007699 // Check whether the member type is itself a reference, in which case
7700 // we're not going to refer to the member, but to what the member refers
7701 // to.
7702 if (M->getMemberDecl()->getType()->isReferenceType())
7703 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007704
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007705 return EvalVal(M->getBase(), refVars, ParentDecl);
7706 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007707
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007708 case Stmt::MaterializeTemporaryExprClass:
7709 if (const Expr *Result =
7710 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7711 refVars, ParentDecl))
7712 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007713 return E;
7714
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007715 default:
7716 // Check that we don't return or take the address of a reference to a
7717 // temporary. This is only useful in C++.
7718 if (!E->isTypeDependent() && E->isRValue())
7719 return E;
7720
7721 // Everything else: we simply don't reason about them.
7722 return nullptr;
7723 }
7724 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007725}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007726
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007727void
7728Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7729 SourceLocation ReturnLoc,
7730 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007731 const AttrVec *Attrs,
7732 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007733 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7734
7735 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007736 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7737 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007738 CheckNonNullExpr(*this, RetValExp))
7739 Diag(ReturnLoc, diag::warn_null_ret)
7740 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007741
7742 // C++11 [basic.stc.dynamic.allocation]p4:
7743 // If an allocation function declared with a non-throwing
7744 // exception-specification fails to allocate storage, it shall return
7745 // a null pointer. Any other allocation function that fails to allocate
7746 // storage shall indicate failure only by throwing an exception [...]
7747 if (FD) {
7748 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7749 if (Op == OO_New || Op == OO_Array_New) {
7750 const FunctionProtoType *Proto
7751 = FD->getType()->castAs<FunctionProtoType>();
7752 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7753 CheckNonNullExpr(*this, RetValExp))
7754 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7755 << FD << getLangOpts().CPlusPlus11;
7756 }
7757 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007758}
7759
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007760//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7761
7762/// Check for comparisons of floating point operands using != and ==.
7763/// Issue a warning if these are no self-comparisons, as they are not likely
7764/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007765void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007766 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7767 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007768
7769 // Special case: check for x == x (which is OK).
7770 // Do not emit warnings for such cases.
7771 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7772 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7773 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007774 return;
Mike Stump11289f42009-09-09 15:08:12 +00007775
Ted Kremenekeda40e22007-11-29 00:59:04 +00007776 // Special case: check for comparisons against literals that can be exactly
7777 // represented by APFloat. In such cases, do not emit a warning. This
7778 // is a heuristic: often comparison against such literals are used to
7779 // detect if a value in a variable has not changed. This clearly can
7780 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007781 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7782 if (FLL->isExact())
7783 return;
7784 } else
7785 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7786 if (FLR->isExact())
7787 return;
Mike Stump11289f42009-09-09 15:08:12 +00007788
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007789 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007790 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007791 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007792 return;
Mike Stump11289f42009-09-09 15:08:12 +00007793
David Blaikie1f4ff152012-07-16 20:47:22 +00007794 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007795 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007796 return;
Mike Stump11289f42009-09-09 15:08:12 +00007797
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007798 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007799 Diag(Loc, diag::warn_floatingpoint_eq)
7800 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007801}
John McCallca01b222010-01-04 23:21:16 +00007802
John McCall70aa5392010-01-06 05:24:50 +00007803//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7804//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007805
John McCall70aa5392010-01-06 05:24:50 +00007806namespace {
John McCallca01b222010-01-04 23:21:16 +00007807
John McCall70aa5392010-01-06 05:24:50 +00007808/// Structure recording the 'active' range of an integer-valued
7809/// expression.
7810struct IntRange {
7811 /// The number of bits active in the int.
7812 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007813
John McCall70aa5392010-01-06 05:24:50 +00007814 /// True if the int is known not to have negative values.
7815 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007816
John McCall70aa5392010-01-06 05:24:50 +00007817 IntRange(unsigned Width, bool NonNegative)
7818 : Width(Width), NonNegative(NonNegative)
7819 {}
John McCallca01b222010-01-04 23:21:16 +00007820
John McCall817d4af2010-11-10 23:38:19 +00007821 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007822 static IntRange forBoolType() {
7823 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007824 }
7825
John McCall817d4af2010-11-10 23:38:19 +00007826 /// Returns the range of an opaque value of the given integral type.
7827 static IntRange forValueOfType(ASTContext &C, QualType T) {
7828 return forValueOfCanonicalType(C,
7829 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007830 }
7831
John McCall817d4af2010-11-10 23:38:19 +00007832 /// Returns the range of an opaque value of a canonical integral type.
7833 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007834 assert(T->isCanonicalUnqualified());
7835
7836 if (const VectorType *VT = dyn_cast<VectorType>(T))
7837 T = VT->getElementType().getTypePtr();
7838 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7839 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007840 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7841 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007842
David Majnemer6a426652013-06-07 22:07:20 +00007843 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007844 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007845 EnumDecl *Enum = ET->getDecl();
7846 if (!Enum->isCompleteDefinition())
7847 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007848
David Majnemer6a426652013-06-07 22:07:20 +00007849 unsigned NumPositive = Enum->getNumPositiveBits();
7850 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007851
David Majnemer6a426652013-06-07 22:07:20 +00007852 if (NumNegative == 0)
7853 return IntRange(NumPositive, true/*NonNegative*/);
7854 else
7855 return IntRange(std::max(NumPositive + 1, NumNegative),
7856 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007857 }
John McCall70aa5392010-01-06 05:24:50 +00007858
7859 const BuiltinType *BT = cast<BuiltinType>(T);
7860 assert(BT->isInteger());
7861
7862 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7863 }
7864
John McCall817d4af2010-11-10 23:38:19 +00007865 /// Returns the "target" range of a canonical integral type, i.e.
7866 /// the range of values expressible in the type.
7867 ///
7868 /// This matches forValueOfCanonicalType except that enums have the
7869 /// full range of their type, not the range of their enumerators.
7870 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7871 assert(T->isCanonicalUnqualified());
7872
7873 if (const VectorType *VT = dyn_cast<VectorType>(T))
7874 T = VT->getElementType().getTypePtr();
7875 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7876 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007877 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7878 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007879 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007880 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007881
7882 const BuiltinType *BT = cast<BuiltinType>(T);
7883 assert(BT->isInteger());
7884
7885 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7886 }
7887
7888 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007889 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007890 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007891 L.NonNegative && R.NonNegative);
7892 }
7893
John McCall817d4af2010-11-10 23:38:19 +00007894 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007895 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007896 return IntRange(std::min(L.Width, R.Width),
7897 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007898 }
7899};
7900
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007901IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007902 if (value.isSigned() && value.isNegative())
7903 return IntRange(value.getMinSignedBits(), false);
7904
7905 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007906 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007907
7908 // isNonNegative() just checks the sign bit without considering
7909 // signedness.
7910 return IntRange(value.getActiveBits(), true);
7911}
7912
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007913IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7914 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007915 if (result.isInt())
7916 return GetValueRange(C, result.getInt(), MaxWidth);
7917
7918 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007919 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7920 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7921 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7922 R = IntRange::join(R, El);
7923 }
John McCall70aa5392010-01-06 05:24:50 +00007924 return R;
7925 }
7926
7927 if (result.isComplexInt()) {
7928 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7929 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7930 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007931 }
7932
7933 // This can happen with lossless casts to intptr_t of "based" lvalues.
7934 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007935 // FIXME: The only reason we need to pass the type in here is to get
7936 // the sign right on this one case. It would be nice if APValue
7937 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007938 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007939 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007940}
John McCall70aa5392010-01-06 05:24:50 +00007941
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007942QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007943 QualType Ty = E->getType();
7944 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7945 Ty = AtomicRHS->getValueType();
7946 return Ty;
7947}
7948
John McCall70aa5392010-01-06 05:24:50 +00007949/// Pseudo-evaluate the given integer expression, estimating the
7950/// range of values it might take.
7951///
7952/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007953IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007954 E = E->IgnoreParens();
7955
7956 // Try a full evaluation first.
7957 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007958 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007959 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007960
7961 // I think we only want to look through implicit casts here; if the
7962 // user has an explicit widening cast, we should treat the value as
7963 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007964 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007965 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007966 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7967
Eli Friedmane6d33952013-07-08 20:20:06 +00007968 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007969
George Burgess IVdf1ed002016-01-13 01:52:39 +00007970 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7971 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007972
John McCall70aa5392010-01-06 05:24:50 +00007973 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007974 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007975 return OutputTypeRange;
7976
7977 IntRange SubRange
7978 = GetExprRange(C, CE->getSubExpr(),
7979 std::min(MaxWidth, OutputTypeRange.Width));
7980
7981 // Bail out if the subexpr's range is as wide as the cast type.
7982 if (SubRange.Width >= OutputTypeRange.Width)
7983 return OutputTypeRange;
7984
7985 // Otherwise, we take the smaller width, and we're non-negative if
7986 // either the output type or the subexpr is.
7987 return IntRange(SubRange.Width,
7988 SubRange.NonNegative || OutputTypeRange.NonNegative);
7989 }
7990
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007991 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007992 // If we can fold the condition, just take that operand.
7993 bool CondResult;
7994 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7995 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7996 : CO->getFalseExpr(),
7997 MaxWidth);
7998
7999 // Otherwise, conservatively merge.
8000 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8001 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8002 return IntRange::join(L, R);
8003 }
8004
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008005 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008006 switch (BO->getOpcode()) {
8007
8008 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008009 case BO_LAnd:
8010 case BO_LOr:
8011 case BO_LT:
8012 case BO_GT:
8013 case BO_LE:
8014 case BO_GE:
8015 case BO_EQ:
8016 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008017 return IntRange::forBoolType();
8018
John McCallc3688382011-07-13 06:35:24 +00008019 // The type of the assignments is the type of the LHS, so the RHS
8020 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008021 case BO_MulAssign:
8022 case BO_DivAssign:
8023 case BO_RemAssign:
8024 case BO_AddAssign:
8025 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008026 case BO_XorAssign:
8027 case BO_OrAssign:
8028 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008029 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008030
John McCallc3688382011-07-13 06:35:24 +00008031 // Simple assignments just pass through the RHS, which will have
8032 // been coerced to the LHS type.
8033 case BO_Assign:
8034 // TODO: bitfields?
8035 return GetExprRange(C, BO->getRHS(), MaxWidth);
8036
John McCall70aa5392010-01-06 05:24:50 +00008037 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008038 case BO_PtrMemD:
8039 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008040 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008041
John McCall2ce81ad2010-01-06 22:07:33 +00008042 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008043 case BO_And:
8044 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008045 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8046 GetExprRange(C, BO->getRHS(), MaxWidth));
8047
John McCall70aa5392010-01-06 05:24:50 +00008048 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008049 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008050 // ...except that we want to treat '1 << (blah)' as logically
8051 // positive. It's an important idiom.
8052 if (IntegerLiteral *I
8053 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8054 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008055 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008056 return IntRange(R.Width, /*NonNegative*/ true);
8057 }
8058 }
8059 // fallthrough
8060
John McCalle3027922010-08-25 11:45:40 +00008061 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008062 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008063
John McCall2ce81ad2010-01-06 22:07:33 +00008064 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008065 case BO_Shr:
8066 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008067 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8068
8069 // If the shift amount is a positive constant, drop the width by
8070 // that much.
8071 llvm::APSInt shift;
8072 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8073 shift.isNonNegative()) {
8074 unsigned zext = shift.getZExtValue();
8075 if (zext >= L.Width)
8076 L.Width = (L.NonNegative ? 0 : 1);
8077 else
8078 L.Width -= zext;
8079 }
8080
8081 return L;
8082 }
8083
8084 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008085 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008086 return GetExprRange(C, BO->getRHS(), MaxWidth);
8087
John McCall2ce81ad2010-01-06 22:07:33 +00008088 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008089 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008090 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008091 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008092 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008093
John McCall51431812011-07-14 22:39:48 +00008094 // The width of a division result is mostly determined by the size
8095 // of the LHS.
8096 case BO_Div: {
8097 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008098 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008099 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8100
8101 // If the divisor is constant, use that.
8102 llvm::APSInt divisor;
8103 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8104 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8105 if (log2 >= L.Width)
8106 L.Width = (L.NonNegative ? 0 : 1);
8107 else
8108 L.Width = std::min(L.Width - log2, MaxWidth);
8109 return L;
8110 }
8111
8112 // Otherwise, just use the LHS's width.
8113 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8114 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8115 }
8116
8117 // The result of a remainder can't be larger than the result of
8118 // either side.
8119 case BO_Rem: {
8120 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008121 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008122 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8123 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8124
8125 IntRange meet = IntRange::meet(L, R);
8126 meet.Width = std::min(meet.Width, MaxWidth);
8127 return meet;
8128 }
8129
8130 // The default behavior is okay for these.
8131 case BO_Mul:
8132 case BO_Add:
8133 case BO_Xor:
8134 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008135 break;
8136 }
8137
John McCall51431812011-07-14 22:39:48 +00008138 // The default case is to treat the operation as if it were closed
8139 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008140 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8141 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8142 return IntRange::join(L, R);
8143 }
8144
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008145 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008146 switch (UO->getOpcode()) {
8147 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008148 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008149 return IntRange::forBoolType();
8150
8151 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008152 case UO_Deref:
8153 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008154 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008155
8156 default:
8157 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8158 }
8159 }
8160
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008161 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008162 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8163
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008164 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008165 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008166 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008167
Eli Friedmane6d33952013-07-08 20:20:06 +00008168 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008169}
John McCall263a48b2010-01-04 23:31:57 +00008170
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008171IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008172 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008173}
8174
John McCall263a48b2010-01-04 23:31:57 +00008175/// Checks whether the given value, which currently has the given
8176/// source semantics, has the same value when coerced through the
8177/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008178bool IsSameFloatAfterCast(const llvm::APFloat &value,
8179 const llvm::fltSemantics &Src,
8180 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008181 llvm::APFloat truncated = value;
8182
8183 bool ignored;
8184 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8185 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8186
8187 return truncated.bitwiseIsEqual(value);
8188}
8189
8190/// Checks whether the given value, which currently has the given
8191/// source semantics, has the same value when coerced through the
8192/// target semantics.
8193///
8194/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008195bool IsSameFloatAfterCast(const APValue &value,
8196 const llvm::fltSemantics &Src,
8197 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008198 if (value.isFloat())
8199 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8200
8201 if (value.isVector()) {
8202 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8203 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8204 return false;
8205 return true;
8206 }
8207
8208 assert(value.isComplexFloat());
8209 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8210 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8211}
8212
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008213void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008214
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008215bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008216 // Suppress cases where we are comparing against an enum constant.
8217 if (const DeclRefExpr *DR =
8218 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8219 if (isa<EnumConstantDecl>(DR->getDecl()))
8220 return false;
8221
8222 // Suppress cases where the '0' value is expanded from a macro.
8223 if (E->getLocStart().isMacroID())
8224 return false;
8225
John McCallcc7e5bf2010-05-06 08:58:33 +00008226 llvm::APSInt Value;
8227 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8228}
8229
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008230bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008231 // Strip off implicit integral promotions.
8232 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008233 if (ICE->getCastKind() != CK_IntegralCast &&
8234 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008235 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008236 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008237 }
8238
8239 return E->getType()->isEnumeralType();
8240}
8241
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008242void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008243 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008244 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008245 return;
8246
John McCalle3027922010-08-25 11:45:40 +00008247 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008248 if (E->isValueDependent())
8249 return;
8250
John McCalle3027922010-08-25 11:45:40 +00008251 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008252 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008253 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008254 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008255 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008256 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008257 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008258 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008259 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008260 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008261 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008262 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008263 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008264 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008265 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008266 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8267 }
8268}
8269
Benjamin Kramer7320b992016-06-15 14:20:56 +00008270void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8271 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008272 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008273 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008274 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008275 return;
8276
Richard Trieu0f097742014-04-04 04:13:47 +00008277 // TODO: Investigate using GetExprRange() to get tighter bounds
8278 // on the bit ranges.
8279 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008280 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008281 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008282 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8283 unsigned OtherWidth = OtherRange.Width;
8284
8285 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8286
Richard Trieu560910c2012-11-14 22:50:24 +00008287 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008288 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008289 return;
8290
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008291 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008292 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008293
Richard Trieu0f097742014-04-04 04:13:47 +00008294 // Used for diagnostic printout.
8295 enum {
8296 LiteralConstant = 0,
8297 CXXBoolLiteralTrue,
8298 CXXBoolLiteralFalse
8299 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008300
Richard Trieu0f097742014-04-04 04:13:47 +00008301 if (!OtherIsBooleanType) {
8302 QualType ConstantT = Constant->getType();
8303 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008304
Richard Trieu0f097742014-04-04 04:13:47 +00008305 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8306 return;
8307 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8308 "comparison with non-integer type");
8309
8310 bool ConstantSigned = ConstantT->isSignedIntegerType();
8311 bool CommonSigned = CommonT->isSignedIntegerType();
8312
8313 bool EqualityOnly = false;
8314
8315 if (CommonSigned) {
8316 // The common type is signed, therefore no signed to unsigned conversion.
8317 if (!OtherRange.NonNegative) {
8318 // Check that the constant is representable in type OtherT.
8319 if (ConstantSigned) {
8320 if (OtherWidth >= Value.getMinSignedBits())
8321 return;
8322 } else { // !ConstantSigned
8323 if (OtherWidth >= Value.getActiveBits() + 1)
8324 return;
8325 }
8326 } else { // !OtherSigned
8327 // Check that the constant is representable in type OtherT.
8328 // Negative values are out of range.
8329 if (ConstantSigned) {
8330 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8331 return;
8332 } else { // !ConstantSigned
8333 if (OtherWidth >= Value.getActiveBits())
8334 return;
8335 }
Richard Trieu560910c2012-11-14 22:50:24 +00008336 }
Richard Trieu0f097742014-04-04 04:13:47 +00008337 } else { // !CommonSigned
8338 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008339 if (OtherWidth >= Value.getActiveBits())
8340 return;
Craig Toppercf360162014-06-18 05:13:11 +00008341 } else { // OtherSigned
8342 assert(!ConstantSigned &&
8343 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008344 // Check to see if the constant is representable in OtherT.
8345 if (OtherWidth > Value.getActiveBits())
8346 return;
8347 // Check to see if the constant is equivalent to a negative value
8348 // cast to CommonT.
8349 if (S.Context.getIntWidth(ConstantT) ==
8350 S.Context.getIntWidth(CommonT) &&
8351 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8352 return;
8353 // The constant value rests between values that OtherT can represent
8354 // after conversion. Relational comparison still works, but equality
8355 // comparisons will be tautological.
8356 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008357 }
8358 }
Richard Trieu0f097742014-04-04 04:13:47 +00008359
8360 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8361
8362 if (op == BO_EQ || op == BO_NE) {
8363 IsTrue = op == BO_NE;
8364 } else if (EqualityOnly) {
8365 return;
8366 } else if (RhsConstant) {
8367 if (op == BO_GT || op == BO_GE)
8368 IsTrue = !PositiveConstant;
8369 else // op == BO_LT || op == BO_LE
8370 IsTrue = PositiveConstant;
8371 } else {
8372 if (op == BO_LT || op == BO_LE)
8373 IsTrue = !PositiveConstant;
8374 else // op == BO_GT || op == BO_GE
8375 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008376 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008377 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008378 // Other isKnownToHaveBooleanValue
8379 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8380 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8381 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8382
8383 static const struct LinkedConditions {
8384 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8385 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8386 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8387 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8388 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8389 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8390
8391 } TruthTable = {
8392 // Constant on LHS. | Constant on RHS. |
8393 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8394 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8395 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8396 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8397 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8398 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8399 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8400 };
8401
8402 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8403
8404 enum ConstantValue ConstVal = Zero;
8405 if (Value.isUnsigned() || Value.isNonNegative()) {
8406 if (Value == 0) {
8407 LiteralOrBoolConstant =
8408 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8409 ConstVal = Zero;
8410 } else if (Value == 1) {
8411 LiteralOrBoolConstant =
8412 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8413 ConstVal = One;
8414 } else {
8415 LiteralOrBoolConstant = LiteralConstant;
8416 ConstVal = GT_One;
8417 }
8418 } else {
8419 ConstVal = LT_Zero;
8420 }
8421
8422 CompareBoolWithConstantResult CmpRes;
8423
8424 switch (op) {
8425 case BO_LT:
8426 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8427 break;
8428 case BO_GT:
8429 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8430 break;
8431 case BO_LE:
8432 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8433 break;
8434 case BO_GE:
8435 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8436 break;
8437 case BO_EQ:
8438 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8439 break;
8440 case BO_NE:
8441 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8442 break;
8443 default:
8444 CmpRes = Unkwn;
8445 break;
8446 }
8447
8448 if (CmpRes == AFals) {
8449 IsTrue = false;
8450 } else if (CmpRes == ATrue) {
8451 IsTrue = true;
8452 } else {
8453 return;
8454 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008455 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008456
8457 // If this is a comparison to an enum constant, include that
8458 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008459 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008460 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8461 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8462
8463 SmallString<64> PrettySourceValue;
8464 llvm::raw_svector_ostream OS(PrettySourceValue);
8465 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008466 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008467 else
8468 OS << Value;
8469
Richard Trieu0f097742014-04-04 04:13:47 +00008470 S.DiagRuntimeBehavior(
8471 E->getOperatorLoc(), E,
8472 S.PDiag(diag::warn_out_of_range_compare)
8473 << OS.str() << LiteralOrBoolConstant
8474 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8475 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008476}
8477
John McCallcc7e5bf2010-05-06 08:58:33 +00008478/// Analyze the operands of the given comparison. Implements the
8479/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008480void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008481 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8482 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008483}
John McCall263a48b2010-01-04 23:31:57 +00008484
John McCallca01b222010-01-04 23:21:16 +00008485/// \brief Implements -Wsign-compare.
8486///
Richard Trieu82402a02011-09-15 21:56:47 +00008487/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008488void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008489 // The type the comparison is being performed in.
8490 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008491
8492 // Only analyze comparison operators where both sides have been converted to
8493 // the same type.
8494 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8495 return AnalyzeImpConvsInComparison(S, E);
8496
8497 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008498 if (E->isValueDependent())
8499 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008500
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008501 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8502 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008503
8504 bool IsComparisonConstant = false;
8505
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008506 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008507 // of 'true' or 'false'.
8508 if (T->isIntegralType(S.Context)) {
8509 llvm::APSInt RHSValue;
8510 bool IsRHSIntegralLiteral =
8511 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8512 llvm::APSInt LHSValue;
8513 bool IsLHSIntegralLiteral =
8514 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8515 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8516 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8517 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8518 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8519 else
8520 IsComparisonConstant =
8521 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008522 } else if (!T->hasUnsignedIntegerRepresentation())
8523 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008524
John McCallcc7e5bf2010-05-06 08:58:33 +00008525 // We don't do anything special if this isn't an unsigned integral
8526 // comparison: we're only interested in integral comparisons, and
8527 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008528 //
8529 // We also don't care about value-dependent expressions or expressions
8530 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008531 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008532 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008533
John McCallcc7e5bf2010-05-06 08:58:33 +00008534 // Check to see if one of the (unmodified) operands is of different
8535 // signedness.
8536 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008537 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8538 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008539 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008540 signedOperand = LHS;
8541 unsignedOperand = RHS;
8542 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8543 signedOperand = RHS;
8544 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008545 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008546 CheckTrivialUnsignedComparison(S, E);
8547 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008548 }
8549
John McCallcc7e5bf2010-05-06 08:58:33 +00008550 // Otherwise, calculate the effective range of the signed operand.
8551 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008552
John McCallcc7e5bf2010-05-06 08:58:33 +00008553 // Go ahead and analyze implicit conversions in the operands. Note
8554 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008555 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8556 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008557
John McCallcc7e5bf2010-05-06 08:58:33 +00008558 // If the signed range is non-negative, -Wsign-compare won't fire,
8559 // but we should still check for comparisons which are always true
8560 // or false.
8561 if (signedRange.NonNegative)
8562 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008563
8564 // For (in)equality comparisons, if the unsigned operand is a
8565 // constant which cannot collide with a overflowed signed operand,
8566 // then reinterpreting the signed operand as unsigned will not
8567 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008568 if (E->isEqualityOp()) {
8569 unsigned comparisonWidth = S.Context.getIntWidth(T);
8570 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008571
John McCallcc7e5bf2010-05-06 08:58:33 +00008572 // We should never be unable to prove that the unsigned operand is
8573 // non-negative.
8574 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8575
8576 if (unsignedRange.Width < comparisonWidth)
8577 return;
8578 }
8579
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008580 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8581 S.PDiag(diag::warn_mixed_sign_comparison)
8582 << LHS->getType() << RHS->getType()
8583 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008584}
8585
John McCall1f425642010-11-11 03:21:53 +00008586/// Analyzes an attempt to assign the given value to a bitfield.
8587///
8588/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008589bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8590 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008591 assert(Bitfield->isBitField());
8592 if (Bitfield->isInvalidDecl())
8593 return false;
8594
John McCalldeebbcf2010-11-11 05:33:51 +00008595 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008596 QualType BitfieldType = Bitfield->getType();
8597 if (BitfieldType->isBooleanType())
8598 return false;
8599
8600 if (BitfieldType->isEnumeralType()) {
8601 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8602 // If the underlying enum type was not explicitly specified as an unsigned
8603 // type and the enum contain only positive values, MSVC++ will cause an
8604 // inconsistency by storing this as a signed type.
8605 if (S.getLangOpts().CPlusPlus11 &&
8606 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8607 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8608 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8609 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8610 << BitfieldEnumDecl->getNameAsString();
8611 }
8612 }
8613
John McCalldeebbcf2010-11-11 05:33:51 +00008614 if (Bitfield->getType()->isBooleanType())
8615 return false;
8616
Douglas Gregor789adec2011-02-04 13:09:01 +00008617 // Ignore value- or type-dependent expressions.
8618 if (Bitfield->getBitWidth()->isValueDependent() ||
8619 Bitfield->getBitWidth()->isTypeDependent() ||
8620 Init->isValueDependent() ||
8621 Init->isTypeDependent())
8622 return false;
8623
John McCall1f425642010-11-11 03:21:53 +00008624 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8625
Richard Smith5fab0c92011-12-28 19:48:30 +00008626 llvm::APSInt Value;
8627 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008628 return false;
8629
John McCall1f425642010-11-11 03:21:53 +00008630 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008631 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008632
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008633 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008634 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008635 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8636 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008637
John McCall1f425642010-11-11 03:21:53 +00008638 if (OriginalWidth <= FieldWidth)
8639 return false;
8640
Eli Friedmanc267a322012-01-26 23:11:39 +00008641 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008642 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008643 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008644
Eli Friedmanc267a322012-01-26 23:11:39 +00008645 // Check whether the stored value is equal to the original value.
8646 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008647 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008648 return false;
8649
Eli Friedmanc267a322012-01-26 23:11:39 +00008650 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008651 // therefore don't strictly fit into a signed bitfield of width 1.
8652 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008653 return false;
8654
John McCall1f425642010-11-11 03:21:53 +00008655 std::string PrettyValue = Value.toString(10);
8656 std::string PrettyTrunc = TruncatedValue.toString(10);
8657
8658 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8659 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8660 << Init->getSourceRange();
8661
8662 return true;
8663}
8664
John McCalld2a53122010-11-09 23:24:47 +00008665/// Analyze the given simple or compound assignment for warning-worthy
8666/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008667void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008668 // Just recurse on the LHS.
8669 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8670
8671 // We want to recurse on the RHS as normal unless we're assigning to
8672 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008673 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008674 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008675 E->getOperatorLoc())) {
8676 // Recurse, ignoring any implicit conversions on the RHS.
8677 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8678 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008679 }
8680 }
8681
8682 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8683}
8684
John McCall263a48b2010-01-04 23:31:57 +00008685/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008686void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8687 SourceLocation CContext, unsigned diag,
8688 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008689 if (pruneControlFlow) {
8690 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8691 S.PDiag(diag)
8692 << SourceType << T << E->getSourceRange()
8693 << SourceRange(CContext));
8694 return;
8695 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008696 S.Diag(E->getExprLoc(), diag)
8697 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8698}
8699
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008700/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008701void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8702 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008703 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008704}
8705
Richard Trieube234c32016-04-21 21:04:55 +00008706
8707/// Diagnose an implicit cast from a floating point value to an integer value.
8708void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8709
8710 SourceLocation CContext) {
8711 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008712 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008713
8714 Expr *InnerE = E->IgnoreParenImpCasts();
8715 // We also want to warn on, e.g., "int i = -1.234"
8716 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8717 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8718 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8719
8720 const bool IsLiteral =
8721 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8722
8723 llvm::APFloat Value(0.0);
8724 bool IsConstant =
8725 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8726 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008727 return DiagnoseImpCast(S, E, T, CContext,
8728 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008729 }
8730
Chandler Carruth016ef402011-04-10 08:36:24 +00008731 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008732
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008733 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8734 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008735 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8736 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008737 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008738 if (IsLiteral) return;
8739 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8740 PruneWarnings);
8741 }
8742
8743 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008744 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008745 // Warn on floating point literal to integer.
8746 DiagID = diag::warn_impcast_literal_float_to_integer;
8747 } else if (IntegerValue == 0) {
8748 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8749 return DiagnoseImpCast(S, E, T, CContext,
8750 diag::warn_impcast_float_integer, PruneWarnings);
8751 }
8752 // Warn on non-zero to zero conversion.
8753 DiagID = diag::warn_impcast_float_to_integer_zero;
8754 } else {
8755 if (IntegerValue.isUnsigned()) {
8756 if (!IntegerValue.isMaxValue()) {
8757 return DiagnoseImpCast(S, E, T, CContext,
8758 diag::warn_impcast_float_integer, PruneWarnings);
8759 }
8760 } else { // IntegerValue.isSigned()
8761 if (!IntegerValue.isMaxSignedValue() &&
8762 !IntegerValue.isMinSignedValue()) {
8763 return DiagnoseImpCast(S, E, T, CContext,
8764 diag::warn_impcast_float_integer, PruneWarnings);
8765 }
8766 }
8767 // Warn on evaluatable floating point expression to integer conversion.
8768 DiagID = diag::warn_impcast_float_to_integer;
8769 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008770
Eli Friedman07185912013-08-29 23:44:43 +00008771 // FIXME: Force the precision of the source value down so we don't print
8772 // digits which are usually useless (we don't really care here if we
8773 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8774 // would automatically print the shortest representation, but it's a bit
8775 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008776 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008777 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8778 precision = (precision * 59 + 195) / 196;
8779 Value.toString(PrettySourceValue, precision);
8780
David Blaikie9b88cc02012-05-15 17:18:27 +00008781 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008782 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008783 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008784 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008785 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008786
Richard Trieube234c32016-04-21 21:04:55 +00008787 if (PruneWarnings) {
8788 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8789 S.PDiag(DiagID)
8790 << E->getType() << T.getUnqualifiedType()
8791 << PrettySourceValue << PrettyTargetValue
8792 << E->getSourceRange() << SourceRange(CContext));
8793 } else {
8794 S.Diag(E->getExprLoc(), DiagID)
8795 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8796 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8797 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008798}
8799
John McCall18a2c2c2010-11-09 22:22:12 +00008800std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8801 if (!Range.Width) return "0";
8802
8803 llvm::APSInt ValueInRange = Value;
8804 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008805 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008806 return ValueInRange.toString(10);
8807}
8808
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008809bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008810 if (!isa<ImplicitCastExpr>(Ex))
8811 return false;
8812
8813 Expr *InnerE = Ex->IgnoreParenImpCasts();
8814 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8815 const Type *Source =
8816 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8817 if (Target->isDependentType())
8818 return false;
8819
8820 const BuiltinType *FloatCandidateBT =
8821 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8822 const Type *BoolCandidateType = ToBool ? Target : Source;
8823
8824 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8825 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8826}
8827
8828void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8829 SourceLocation CC) {
8830 unsigned NumArgs = TheCall->getNumArgs();
8831 for (unsigned i = 0; i < NumArgs; ++i) {
8832 Expr *CurrA = TheCall->getArg(i);
8833 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8834 continue;
8835
8836 bool IsSwapped = ((i > 0) &&
8837 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8838 IsSwapped |= ((i < (NumArgs - 1)) &&
8839 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8840 if (IsSwapped) {
8841 // Warn on this floating-point to bool conversion.
8842 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8843 CurrA->getType(), CC,
8844 diag::warn_impcast_floating_point_to_bool);
8845 }
8846 }
8847}
8848
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008849void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008850 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8851 E->getExprLoc()))
8852 return;
8853
Richard Trieu09d6b802016-01-08 23:35:06 +00008854 // Don't warn on functions which have return type nullptr_t.
8855 if (isa<CallExpr>(E))
8856 return;
8857
Richard Trieu5b993502014-10-15 03:42:06 +00008858 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8859 const Expr::NullPointerConstantKind NullKind =
8860 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8861 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8862 return;
8863
8864 // Return if target type is a safe conversion.
8865 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8866 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8867 return;
8868
8869 SourceLocation Loc = E->getSourceRange().getBegin();
8870
Richard Trieu0a5e1662016-02-13 00:58:53 +00008871 // Venture through the macro stacks to get to the source of macro arguments.
8872 // The new location is a better location than the complete location that was
8873 // passed in.
8874 while (S.SourceMgr.isMacroArgExpansion(Loc))
8875 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8876
8877 while (S.SourceMgr.isMacroArgExpansion(CC))
8878 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8879
Richard Trieu5b993502014-10-15 03:42:06 +00008880 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008881 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8882 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8883 Loc, S.SourceMgr, S.getLangOpts());
8884 if (MacroName == "NULL")
8885 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008886 }
8887
8888 // Only warn if the null and context location are in the same macro expansion.
8889 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8890 return;
8891
8892 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8893 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8894 << FixItHint::CreateReplacement(Loc,
8895 S.getFixItZeroLiteralForType(T, Loc));
8896}
8897
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008898void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8899 ObjCArrayLiteral *ArrayLiteral);
8900void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8901 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008902
8903/// Check a single element within a collection literal against the
8904/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008905void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8906 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008907 // Skip a bitcast to 'id' or qualified 'id'.
8908 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8909 if (ICE->getCastKind() == CK_BitCast &&
8910 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8911 Element = ICE->getSubExpr();
8912 }
8913
8914 QualType ElementType = Element->getType();
8915 ExprResult ElementResult(Element);
8916 if (ElementType->getAs<ObjCObjectPointerType>() &&
8917 S.CheckSingleAssignmentConstraints(TargetElementType,
8918 ElementResult,
8919 false, false)
8920 != Sema::Compatible) {
8921 S.Diag(Element->getLocStart(),
8922 diag::warn_objc_collection_literal_element)
8923 << ElementType << ElementKind << TargetElementType
8924 << Element->getSourceRange();
8925 }
8926
8927 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8928 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8929 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8930 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8931}
8932
8933/// Check an Objective-C array literal being converted to the given
8934/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008935void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8936 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008937 if (!S.NSArrayDecl)
8938 return;
8939
8940 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8941 if (!TargetObjCPtr)
8942 return;
8943
8944 if (TargetObjCPtr->isUnspecialized() ||
8945 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8946 != S.NSArrayDecl->getCanonicalDecl())
8947 return;
8948
8949 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8950 if (TypeArgs.size() != 1)
8951 return;
8952
8953 QualType TargetElementType = TypeArgs[0];
8954 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8955 checkObjCCollectionLiteralElement(S, TargetElementType,
8956 ArrayLiteral->getElement(I),
8957 0);
8958 }
8959}
8960
8961/// Check an Objective-C dictionary literal being converted to the given
8962/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008963void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8964 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008965 if (!S.NSDictionaryDecl)
8966 return;
8967
8968 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8969 if (!TargetObjCPtr)
8970 return;
8971
8972 if (TargetObjCPtr->isUnspecialized() ||
8973 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8974 != S.NSDictionaryDecl->getCanonicalDecl())
8975 return;
8976
8977 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8978 if (TypeArgs.size() != 2)
8979 return;
8980
8981 QualType TargetKeyType = TypeArgs[0];
8982 QualType TargetObjectType = TypeArgs[1];
8983 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8984 auto Element = DictionaryLiteral->getKeyValueElement(I);
8985 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8986 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8987 }
8988}
8989
Richard Trieufc404c72016-02-05 23:02:38 +00008990// Helper function to filter out cases for constant width constant conversion.
8991// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008992bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8993 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008994 // If initializing from a constant, and the constant starts with '0',
8995 // then it is a binary, octal, or hexadecimal. Allow these constants
8996 // to fill all the bits, even if there is a sign change.
8997 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8998 const char FirstLiteralCharacter =
8999 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9000 if (FirstLiteralCharacter == '0')
9001 return false;
9002 }
9003
9004 // If the CC location points to a '{', and the type is char, then assume
9005 // assume it is an array initialization.
9006 if (CC.isValid() && T->isCharType()) {
9007 const char FirstContextCharacter =
9008 S.getSourceManager().getCharacterData(CC)[0];
9009 if (FirstContextCharacter == '{')
9010 return false;
9011 }
9012
9013 return true;
9014}
9015
John McCallcc7e5bf2010-05-06 08:58:33 +00009016void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009017 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009018 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009019
John McCallcc7e5bf2010-05-06 08:58:33 +00009020 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9021 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9022 if (Source == Target) return;
9023 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009024
Chandler Carruthc22845a2011-07-26 05:40:03 +00009025 // If the conversion context location is invalid don't complain. We also
9026 // don't want to emit a warning if the issue occurs from the expansion of
9027 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9028 // delay this check as long as possible. Once we detect we are in that
9029 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009030 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009031 return;
9032
Richard Trieu021baa32011-09-23 20:10:00 +00009033 // Diagnose implicit casts to bool.
9034 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9035 if (isa<StringLiteral>(E))
9036 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009037 // and expressions, for instance, assert(0 && "error here"), are
9038 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009039 return DiagnoseImpCast(S, E, T, CC,
9040 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009041 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9042 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9043 // This covers the literal expressions that evaluate to Objective-C
9044 // objects.
9045 return DiagnoseImpCast(S, E, T, CC,
9046 diag::warn_impcast_objective_c_literal_to_bool);
9047 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009048 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9049 // Warn on pointer to bool conversion that is always true.
9050 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9051 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009052 }
Richard Trieu021baa32011-09-23 20:10:00 +00009053 }
John McCall263a48b2010-01-04 23:31:57 +00009054
Douglas Gregor5054cb02015-07-07 03:58:22 +00009055 // Check implicit casts from Objective-C collection literals to specialized
9056 // collection types, e.g., NSArray<NSString *> *.
9057 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9058 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9059 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9060 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9061
John McCall263a48b2010-01-04 23:31:57 +00009062 // Strip vector types.
9063 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009064 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009065 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009066 return;
John McCallacf0ee52010-10-08 02:01:28 +00009067 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009068 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009069
9070 // If the vector cast is cast between two vectors of the same size, it is
9071 // a bitcast, not a conversion.
9072 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9073 return;
John McCall263a48b2010-01-04 23:31:57 +00009074
9075 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9076 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9077 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009078 if (auto VecTy = dyn_cast<VectorType>(Target))
9079 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009080
9081 // Strip complex types.
9082 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009083 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009084 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009085 return;
9086
John McCallacf0ee52010-10-08 02:01:28 +00009087 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009088 }
John McCall263a48b2010-01-04 23:31:57 +00009089
9090 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9091 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9092 }
9093
9094 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9095 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9096
9097 // If the source is floating point...
9098 if (SourceBT && SourceBT->isFloatingPoint()) {
9099 // ...and the target is floating point...
9100 if (TargetBT && TargetBT->isFloatingPoint()) {
9101 // ...then warn if we're dropping FP rank.
9102
9103 // Builtin FP kinds are ordered by increasing FP rank.
9104 if (SourceBT->getKind() > TargetBT->getKind()) {
9105 // Don't warn about float constants that are precisely
9106 // representable in the target type.
9107 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009108 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009109 // Value might be a float, a float vector, or a float complex.
9110 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009111 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9112 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009113 return;
9114 }
9115
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009116 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009117 return;
9118
John McCallacf0ee52010-10-08 02:01:28 +00009119 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009120 }
9121 // ... or possibly if we're increasing rank, too
9122 else if (TargetBT->getKind() > SourceBT->getKind()) {
9123 if (S.SourceMgr.isInSystemMacro(CC))
9124 return;
9125
9126 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009127 }
9128 return;
9129 }
9130
Richard Trieube234c32016-04-21 21:04:55 +00009131 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009132 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009133 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009134 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009135
Richard Trieube234c32016-04-21 21:04:55 +00009136 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009137 }
John McCall263a48b2010-01-04 23:31:57 +00009138
Richard Smith54894fd2015-12-30 01:06:52 +00009139 // Detect the case where a call result is converted from floating-point to
9140 // to bool, and the final argument to the call is converted from bool, to
9141 // discover this typo:
9142 //
9143 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9144 //
9145 // FIXME: This is an incredibly special case; is there some more general
9146 // way to detect this class of misplaced-parentheses bug?
9147 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009148 // Check last argument of function call to see if it is an
9149 // implicit cast from a type matching the type the result
9150 // is being cast to.
9151 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009152 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009153 Expr *LastA = CEx->getArg(NumArgs - 1);
9154 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009155 if (isa<ImplicitCastExpr>(LastA) &&
9156 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009157 // Warn on this floating-point to bool conversion
9158 DiagnoseImpCast(S, E, T, CC,
9159 diag::warn_impcast_floating_point_to_bool);
9160 }
9161 }
9162 }
John McCall263a48b2010-01-04 23:31:57 +00009163 return;
9164 }
9165
Richard Trieu5b993502014-10-15 03:42:06 +00009166 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009167
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009168 S.DiscardMisalignedMemberAddress(Target, E);
9169
David Blaikie9366d2b2012-06-19 21:19:06 +00009170 if (!Source->isIntegerType() || !Target->isIntegerType())
9171 return;
9172
David Blaikie7555b6a2012-05-15 16:56:36 +00009173 // TODO: remove this early return once the false positives for constant->bool
9174 // in templates, macros, etc, are reduced or removed.
9175 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9176 return;
9177
John McCallcc7e5bf2010-05-06 08:58:33 +00009178 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009179 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009180
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009181 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009182 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009183 // TODO: this should happen for bitfield stores, too.
9184 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009185 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009186 if (S.SourceMgr.isInSystemMacro(CC))
9187 return;
9188
John McCall18a2c2c2010-11-09 22:22:12 +00009189 std::string PrettySourceValue = Value.toString(10);
9190 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009191
Ted Kremenek33ba9952011-10-22 02:37:33 +00009192 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9193 S.PDiag(diag::warn_impcast_integer_precision_constant)
9194 << PrettySourceValue << PrettyTargetValue
9195 << E->getType() << T << E->getSourceRange()
9196 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009197 return;
9198 }
9199
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009200 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9201 if (S.SourceMgr.isInSystemMacro(CC))
9202 return;
9203
David Blaikie9455da02012-04-12 22:40:54 +00009204 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009205 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9206 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009207 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009208 }
9209
Richard Trieudcb55572016-01-29 23:51:16 +00009210 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9211 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9212 // Warn when doing a signed to signed conversion, warn if the positive
9213 // source value is exactly the width of the target type, which will
9214 // cause a negative value to be stored.
9215
9216 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009217 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9218 !S.SourceMgr.isInSystemMacro(CC)) {
9219 if (isSameWidthConstantConversion(S, E, T, CC)) {
9220 std::string PrettySourceValue = Value.toString(10);
9221 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009222
Richard Trieufc404c72016-02-05 23:02:38 +00009223 S.DiagRuntimeBehavior(
9224 E->getExprLoc(), E,
9225 S.PDiag(diag::warn_impcast_integer_precision_constant)
9226 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9227 << E->getSourceRange() << clang::SourceRange(CC));
9228 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009229 }
9230 }
Richard Trieufc404c72016-02-05 23:02:38 +00009231
Richard Trieudcb55572016-01-29 23:51:16 +00009232 // Fall through for non-constants to give a sign conversion warning.
9233 }
9234
John McCallcc7e5bf2010-05-06 08:58:33 +00009235 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9236 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9237 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009238 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009239 return;
9240
John McCallcc7e5bf2010-05-06 08:58:33 +00009241 unsigned DiagID = diag::warn_impcast_integer_sign;
9242
9243 // Traditionally, gcc has warned about this under -Wsign-compare.
9244 // We also want to warn about it in -Wconversion.
9245 // So if -Wconversion is off, use a completely identical diagnostic
9246 // in the sign-compare group.
9247 // The conditional-checking code will
9248 if (ICContext) {
9249 DiagID = diag::warn_impcast_integer_sign_conditional;
9250 *ICContext = true;
9251 }
9252
John McCallacf0ee52010-10-08 02:01:28 +00009253 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009254 }
9255
Douglas Gregora78f1932011-02-22 02:45:07 +00009256 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009257 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9258 // type, to give us better diagnostics.
9259 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009260 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009261 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9262 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9263 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9264 SourceType = S.Context.getTypeDeclType(Enum);
9265 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9266 }
9267 }
9268
Douglas Gregora78f1932011-02-22 02:45:07 +00009269 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9270 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009271 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9272 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009273 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009274 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009275 return;
9276
Douglas Gregor364f7db2011-03-12 00:14:31 +00009277 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009278 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009279 }
John McCall263a48b2010-01-04 23:31:57 +00009280}
9281
David Blaikie18e9ac72012-05-15 21:57:38 +00009282void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9283 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009284
9285void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009286 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009287 E = E->IgnoreParenImpCasts();
9288
9289 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009290 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009291
John McCallacf0ee52010-10-08 02:01:28 +00009292 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009293 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009294 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009295}
9296
David Blaikie18e9ac72012-05-15 21:57:38 +00009297void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9298 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009299 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009300
9301 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009302 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9303 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009304
9305 // If -Wconversion would have warned about either of the candidates
9306 // for a signedness conversion to the context type...
9307 if (!Suspicious) return;
9308
9309 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009310 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009311 return;
9312
John McCallcc7e5bf2010-05-06 08:58:33 +00009313 // ...then check whether it would have warned about either of the
9314 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009315 if (E->getType() == T) return;
9316
9317 Suspicious = false;
9318 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9319 E->getType(), CC, &Suspicious);
9320 if (!Suspicious)
9321 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009322 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009323}
9324
Richard Trieu65724892014-11-15 06:37:39 +00009325/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9326/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009327void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009328 if (S.getLangOpts().Bool)
9329 return;
9330 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9331}
9332
John McCallcc7e5bf2010-05-06 08:58:33 +00009333/// AnalyzeImplicitConversions - Find and report any interesting
9334/// implicit conversions in the given expression. There are a couple
9335/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009336void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009337 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009338 Expr *E = OrigE->IgnoreParenImpCasts();
9339
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009340 if (E->isTypeDependent() || E->isValueDependent())
9341 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009342
John McCallcc7e5bf2010-05-06 08:58:33 +00009343 // For conditional operators, we analyze the arguments as if they
9344 // were being fed directly into the output.
9345 if (isa<ConditionalOperator>(E)) {
9346 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009347 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009348 return;
9349 }
9350
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009351 // Check implicit argument conversions for function calls.
9352 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9353 CheckImplicitArgumentConversions(S, Call, CC);
9354
John McCallcc7e5bf2010-05-06 08:58:33 +00009355 // Go ahead and check any implicit conversions we might have skipped.
9356 // The non-canonical typecheck is just an optimization;
9357 // CheckImplicitConversion will filter out dead implicit conversions.
9358 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009359 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009360
9361 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009362
9363 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9364 // The bound subexpressions in a PseudoObjectExpr are not reachable
9365 // as transitive children.
9366 // FIXME: Use a more uniform representation for this.
9367 for (auto *SE : POE->semantics())
9368 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9369 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009370 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009371
John McCallcc7e5bf2010-05-06 08:58:33 +00009372 // Skip past explicit casts.
9373 if (isa<ExplicitCastExpr>(E)) {
9374 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009375 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009376 }
9377
John McCalld2a53122010-11-09 23:24:47 +00009378 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9379 // Do a somewhat different check with comparison operators.
9380 if (BO->isComparisonOp())
9381 return AnalyzeComparison(S, BO);
9382
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009383 // And with simple assignments.
9384 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009385 return AnalyzeAssignment(S, BO);
9386 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009387
9388 // These break the otherwise-useful invariant below. Fortunately,
9389 // we don't really need to recurse into them, because any internal
9390 // expressions should have been analyzed already when they were
9391 // built into statements.
9392 if (isa<StmtExpr>(E)) return;
9393
9394 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009395 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009396
9397 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009398 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009399 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009400 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009401 for (Stmt *SubStmt : E->children()) {
9402 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009403 if (!ChildExpr)
9404 continue;
9405
Richard Trieu955231d2014-01-25 01:10:35 +00009406 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009407 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009408 // Ignore checking string literals that are in logical and operators.
9409 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009410 continue;
9411 AnalyzeImplicitConversions(S, ChildExpr, CC);
9412 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009413
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009414 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009415 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9416 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009417 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009418
9419 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9420 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009421 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009422 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009423
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009424 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9425 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009426 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009427}
9428
9429} // end anonymous namespace
9430
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009431/// Diagnose integer type and any valid implicit convertion to it.
9432static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9433 // Taking into account implicit conversions,
9434 // allow any integer.
9435 if (!E->getType()->isIntegerType()) {
9436 S.Diag(E->getLocStart(),
9437 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9438 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009439 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009440 // Potentially emit standard warnings for implicit conversions if enabled
9441 // using -Wconversion.
9442 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9443 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009444}
9445
Richard Trieuc1888e02014-06-28 23:25:37 +00009446// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9447// Returns true when emitting a warning about taking the address of a reference.
9448static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009449 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009450 E = E->IgnoreParenImpCasts();
9451
9452 const FunctionDecl *FD = nullptr;
9453
9454 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9455 if (!DRE->getDecl()->getType()->isReferenceType())
9456 return false;
9457 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9458 if (!M->getMemberDecl()->getType()->isReferenceType())
9459 return false;
9460 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009461 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009462 return false;
9463 FD = Call->getDirectCallee();
9464 } else {
9465 return false;
9466 }
9467
9468 SemaRef.Diag(E->getExprLoc(), PD);
9469
9470 // If possible, point to location of function.
9471 if (FD) {
9472 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9473 }
9474
9475 return true;
9476}
9477
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009478// Returns true if the SourceLocation is expanded from any macro body.
9479// Returns false if the SourceLocation is invalid, is from not in a macro
9480// expansion, or is from expanded from a top-level macro argument.
9481static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9482 if (Loc.isInvalid())
9483 return false;
9484
9485 while (Loc.isMacroID()) {
9486 if (SM.isMacroBodyExpansion(Loc))
9487 return true;
9488 Loc = SM.getImmediateMacroCallerLoc(Loc);
9489 }
9490
9491 return false;
9492}
9493
Richard Trieu3bb8b562014-02-26 02:36:06 +00009494/// \brief Diagnose pointers that are always non-null.
9495/// \param E the expression containing the pointer
9496/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9497/// compared to a null pointer
9498/// \param IsEqual True when the comparison is equal to a null pointer
9499/// \param Range Extra SourceRange to highlight in the diagnostic
9500void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9501 Expr::NullPointerConstantKind NullKind,
9502 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009503 if (!E)
9504 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009505
9506 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009507 if (E->getExprLoc().isMacroID()) {
9508 const SourceManager &SM = getSourceManager();
9509 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9510 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009511 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009512 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009513 E = E->IgnoreImpCasts();
9514
9515 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9516
Richard Trieuf7432752014-06-06 21:39:26 +00009517 if (isa<CXXThisExpr>(E)) {
9518 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9519 : diag::warn_this_bool_conversion;
9520 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9521 return;
9522 }
9523
Richard Trieu3bb8b562014-02-26 02:36:06 +00009524 bool IsAddressOf = false;
9525
9526 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9527 if (UO->getOpcode() != UO_AddrOf)
9528 return;
9529 IsAddressOf = true;
9530 E = UO->getSubExpr();
9531 }
9532
Richard Trieuc1888e02014-06-28 23:25:37 +00009533 if (IsAddressOf) {
9534 unsigned DiagID = IsCompare
9535 ? diag::warn_address_of_reference_null_compare
9536 : diag::warn_address_of_reference_bool_conversion;
9537 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9538 << IsEqual;
9539 if (CheckForReference(*this, E, PD)) {
9540 return;
9541 }
9542 }
9543
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009544 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9545 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009546 std::string Str;
9547 llvm::raw_string_ostream S(Str);
9548 E->printPretty(S, nullptr, getPrintingPolicy());
9549 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9550 : diag::warn_cast_nonnull_to_bool;
9551 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9552 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009553 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009554 };
9555
9556 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9557 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9558 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009559 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9560 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009561 return;
9562 }
9563 }
9564 }
9565
Richard Trieu3bb8b562014-02-26 02:36:06 +00009566 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009567 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009568 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9569 D = R->getDecl();
9570 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9571 D = M->getMemberDecl();
9572 }
9573
9574 // Weak Decls can be null.
9575 if (!D || D->isWeak())
9576 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009577
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009578 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009579 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9580 if (getCurFunction() &&
9581 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009582 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9583 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009584 return;
9585 }
9586
9587 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009588 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009589 assert(ParamIter != FD->param_end());
9590 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9591
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009592 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9593 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009594 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009595 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009596 }
George Burgess IV850269a2015-12-08 22:02:00 +00009597
9598 for (unsigned ArgNo : NonNull->args()) {
9599 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009600 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009601 return;
9602 }
George Burgess IV850269a2015-12-08 22:02:00 +00009603 }
9604 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009605 }
9606 }
George Burgess IV850269a2015-12-08 22:02:00 +00009607 }
9608
Richard Trieu3bb8b562014-02-26 02:36:06 +00009609 QualType T = D->getType();
9610 const bool IsArray = T->isArrayType();
9611 const bool IsFunction = T->isFunctionType();
9612
Richard Trieuc1888e02014-06-28 23:25:37 +00009613 // Address of function is used to silence the function warning.
9614 if (IsAddressOf && IsFunction) {
9615 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009616 }
9617
9618 // Found nothing.
9619 if (!IsAddressOf && !IsFunction && !IsArray)
9620 return;
9621
9622 // Pretty print the expression for the diagnostic.
9623 std::string Str;
9624 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009625 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009626
9627 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9628 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009629 enum {
9630 AddressOf,
9631 FunctionPointer,
9632 ArrayPointer
9633 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009634 if (IsAddressOf)
9635 DiagType = AddressOf;
9636 else if (IsFunction)
9637 DiagType = FunctionPointer;
9638 else if (IsArray)
9639 DiagType = ArrayPointer;
9640 else
9641 llvm_unreachable("Could not determine diagnostic.");
9642 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9643 << Range << IsEqual;
9644
9645 if (!IsFunction)
9646 return;
9647
9648 // Suggest '&' to silence the function warning.
9649 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9650 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9651
9652 // Check to see if '()' fixit should be emitted.
9653 QualType ReturnType;
9654 UnresolvedSet<4> NonTemplateOverloads;
9655 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9656 if (ReturnType.isNull())
9657 return;
9658
9659 if (IsCompare) {
9660 // There are two cases here. If there is null constant, the only suggest
9661 // for a pointer return type. If the null is 0, then suggest if the return
9662 // type is a pointer or an integer type.
9663 if (!ReturnType->isPointerType()) {
9664 if (NullKind == Expr::NPCK_ZeroExpression ||
9665 NullKind == Expr::NPCK_ZeroLiteral) {
9666 if (!ReturnType->isIntegerType())
9667 return;
9668 } else {
9669 return;
9670 }
9671 }
9672 } else { // !IsCompare
9673 // For function to bool, only suggest if the function pointer has bool
9674 // return type.
9675 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9676 return;
9677 }
9678 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009679 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009680}
9681
John McCallcc7e5bf2010-05-06 08:58:33 +00009682/// Diagnoses "dangerous" implicit conversions within the given
9683/// expression (which is a full expression). Implements -Wconversion
9684/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009685///
9686/// \param CC the "context" location of the implicit conversion, i.e.
9687/// the most location of the syntactic entity requiring the implicit
9688/// conversion
9689void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009690 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009691 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009692 return;
9693
9694 // Don't diagnose for value- or type-dependent expressions.
9695 if (E->isTypeDependent() || E->isValueDependent())
9696 return;
9697
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009698 // Check for array bounds violations in cases where the check isn't triggered
9699 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9700 // ArraySubscriptExpr is on the RHS of a variable initialization.
9701 CheckArrayAccess(E);
9702
John McCallacf0ee52010-10-08 02:01:28 +00009703 // This is not the right CC for (e.g.) a variable initialization.
9704 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009705}
9706
Richard Trieu65724892014-11-15 06:37:39 +00009707/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9708/// Input argument E is a logical expression.
9709void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9710 ::CheckBoolLikeConversion(*this, E, CC);
9711}
9712
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009713/// Diagnose when expression is an integer constant expression and its evaluation
9714/// results in integer overflow
9715void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009716 // Use a work list to deal with nested struct initializers.
9717 SmallVector<Expr *, 2> Exprs(1, E);
9718
9719 do {
9720 Expr *E = Exprs.pop_back_val();
9721
9722 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9723 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9724 continue;
9725 }
9726
9727 if (auto InitList = dyn_cast<InitListExpr>(E))
9728 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9729 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009730}
9731
Richard Smithc406cb72013-01-17 01:17:56 +00009732namespace {
9733/// \brief Visitor for expressions which looks for unsequenced operations on the
9734/// same object.
9735class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009736 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9737
Richard Smithc406cb72013-01-17 01:17:56 +00009738 /// \brief A tree of sequenced regions within an expression. Two regions are
9739 /// unsequenced if one is an ancestor or a descendent of the other. When we
9740 /// finish processing an expression with sequencing, such as a comma
9741 /// expression, we fold its tree nodes into its parent, since they are
9742 /// unsequenced with respect to nodes we will visit later.
9743 class SequenceTree {
9744 struct Value {
9745 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9746 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009747 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009748 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009749 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009750
9751 public:
9752 /// \brief A region within an expression which may be sequenced with respect
9753 /// to some other region.
9754 class Seq {
9755 explicit Seq(unsigned N) : Index(N) {}
9756 unsigned Index;
9757 friend class SequenceTree;
9758 public:
9759 Seq() : Index(0) {}
9760 };
9761
9762 SequenceTree() { Values.push_back(Value(0)); }
9763 Seq root() const { return Seq(0); }
9764
9765 /// \brief Create a new sequence of operations, which is an unsequenced
9766 /// subset of \p Parent. This sequence of operations is sequenced with
9767 /// respect to other children of \p Parent.
9768 Seq allocate(Seq Parent) {
9769 Values.push_back(Value(Parent.Index));
9770 return Seq(Values.size() - 1);
9771 }
9772
9773 /// \brief Merge a sequence of operations into its parent.
9774 void merge(Seq S) {
9775 Values[S.Index].Merged = true;
9776 }
9777
9778 /// \brief Determine whether two operations are unsequenced. This operation
9779 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9780 /// should have been merged into its parent as appropriate.
9781 bool isUnsequenced(Seq Cur, Seq Old) {
9782 unsigned C = representative(Cur.Index);
9783 unsigned Target = representative(Old.Index);
9784 while (C >= Target) {
9785 if (C == Target)
9786 return true;
9787 C = Values[C].Parent;
9788 }
9789 return false;
9790 }
9791
9792 private:
9793 /// \brief Pick a representative for a sequence.
9794 unsigned representative(unsigned K) {
9795 if (Values[K].Merged)
9796 // Perform path compression as we go.
9797 return Values[K].Parent = representative(Values[K].Parent);
9798 return K;
9799 }
9800 };
9801
9802 /// An object for which we can track unsequenced uses.
9803 typedef NamedDecl *Object;
9804
9805 /// Different flavors of object usage which we track. We only track the
9806 /// least-sequenced usage of each kind.
9807 enum UsageKind {
9808 /// A read of an object. Multiple unsequenced reads are OK.
9809 UK_Use,
9810 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009811 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009812 UK_ModAsValue,
9813 /// A modification of an object which is not sequenced before the value
9814 /// computation of the expression, such as n++.
9815 UK_ModAsSideEffect,
9816
9817 UK_Count = UK_ModAsSideEffect + 1
9818 };
9819
9820 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009821 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009822 Expr *Use;
9823 SequenceTree::Seq Seq;
9824 };
9825
9826 struct UsageInfo {
9827 UsageInfo() : Diagnosed(false) {}
9828 Usage Uses[UK_Count];
9829 /// Have we issued a diagnostic for this variable already?
9830 bool Diagnosed;
9831 };
9832 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9833
9834 Sema &SemaRef;
9835 /// Sequenced regions within the expression.
9836 SequenceTree Tree;
9837 /// Declaration modifications and references which we have seen.
9838 UsageInfoMap UsageMap;
9839 /// The region we are currently within.
9840 SequenceTree::Seq Region;
9841 /// Filled in with declarations which were modified as a side-effect
9842 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009843 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009844 /// Expressions to check later. We defer checking these to reduce
9845 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009846 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009847
9848 /// RAII object wrapping the visitation of a sequenced subexpression of an
9849 /// expression. At the end of this process, the side-effects of the evaluation
9850 /// become sequenced with respect to the value computation of the result, so
9851 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9852 /// UK_ModAsValue.
9853 struct SequencedSubexpression {
9854 SequencedSubexpression(SequenceChecker &Self)
9855 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9856 Self.ModAsSideEffect = &ModAsSideEffect;
9857 }
9858 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009859 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9860 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009861 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009862 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9863 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009864 }
9865 Self.ModAsSideEffect = OldModAsSideEffect;
9866 }
9867
9868 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009869 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9870 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009871 };
9872
Richard Smith40238f02013-06-20 22:21:56 +00009873 /// RAII object wrapping the visitation of a subexpression which we might
9874 /// choose to evaluate as a constant. If any subexpression is evaluated and
9875 /// found to be non-constant, this allows us to suppress the evaluation of
9876 /// the outer expression.
9877 class EvaluationTracker {
9878 public:
9879 EvaluationTracker(SequenceChecker &Self)
9880 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9881 Self.EvalTracker = this;
9882 }
9883 ~EvaluationTracker() {
9884 Self.EvalTracker = Prev;
9885 if (Prev)
9886 Prev->EvalOK &= EvalOK;
9887 }
9888
9889 bool evaluate(const Expr *E, bool &Result) {
9890 if (!EvalOK || E->isValueDependent())
9891 return false;
9892 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9893 return EvalOK;
9894 }
9895
9896 private:
9897 SequenceChecker &Self;
9898 EvaluationTracker *Prev;
9899 bool EvalOK;
9900 } *EvalTracker;
9901
Richard Smithc406cb72013-01-17 01:17:56 +00009902 /// \brief Find the object which is produced by the specified expression,
9903 /// if any.
9904 Object getObject(Expr *E, bool Mod) const {
9905 E = E->IgnoreParenCasts();
9906 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9907 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9908 return getObject(UO->getSubExpr(), Mod);
9909 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9910 if (BO->getOpcode() == BO_Comma)
9911 return getObject(BO->getRHS(), Mod);
9912 if (Mod && BO->isAssignmentOp())
9913 return getObject(BO->getLHS(), Mod);
9914 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9915 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9916 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9917 return ME->getMemberDecl();
9918 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9919 // FIXME: If this is a reference, map through to its value.
9920 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009921 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009922 }
9923
9924 /// \brief Note that an object was modified or used by an expression.
9925 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9926 Usage &U = UI.Uses[UK];
9927 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9928 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9929 ModAsSideEffect->push_back(std::make_pair(O, U));
9930 U.Use = Ref;
9931 U.Seq = Region;
9932 }
9933 }
9934 /// \brief Check whether a modification or use conflicts with a prior usage.
9935 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9936 bool IsModMod) {
9937 if (UI.Diagnosed)
9938 return;
9939
9940 const Usage &U = UI.Uses[OtherKind];
9941 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9942 return;
9943
9944 Expr *Mod = U.Use;
9945 Expr *ModOrUse = Ref;
9946 if (OtherKind == UK_Use)
9947 std::swap(Mod, ModOrUse);
9948
9949 SemaRef.Diag(Mod->getExprLoc(),
9950 IsModMod ? diag::warn_unsequenced_mod_mod
9951 : diag::warn_unsequenced_mod_use)
9952 << O << SourceRange(ModOrUse->getExprLoc());
9953 UI.Diagnosed = true;
9954 }
9955
9956 void notePreUse(Object O, Expr *Use) {
9957 UsageInfo &U = UsageMap[O];
9958 // Uses conflict with other modifications.
9959 checkUsage(O, U, Use, UK_ModAsValue, false);
9960 }
9961 void notePostUse(Object O, Expr *Use) {
9962 UsageInfo &U = UsageMap[O];
9963 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9964 addUsage(U, O, Use, UK_Use);
9965 }
9966
9967 void notePreMod(Object O, Expr *Mod) {
9968 UsageInfo &U = UsageMap[O];
9969 // Modifications conflict with other modifications and with uses.
9970 checkUsage(O, U, Mod, UK_ModAsValue, true);
9971 checkUsage(O, U, Mod, UK_Use, false);
9972 }
9973 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9974 UsageInfo &U = UsageMap[O];
9975 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9976 addUsage(U, O, Use, UK);
9977 }
9978
9979public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009980 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009981 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9982 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009983 Visit(E);
9984 }
9985
9986 void VisitStmt(Stmt *S) {
9987 // Skip all statements which aren't expressions for now.
9988 }
9989
9990 void VisitExpr(Expr *E) {
9991 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009992 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009993 }
9994
9995 void VisitCastExpr(CastExpr *E) {
9996 Object O = Object();
9997 if (E->getCastKind() == CK_LValueToRValue)
9998 O = getObject(E->getSubExpr(), false);
9999
10000 if (O)
10001 notePreUse(O, E);
10002 VisitExpr(E);
10003 if (O)
10004 notePostUse(O, E);
10005 }
10006
10007 void VisitBinComma(BinaryOperator *BO) {
10008 // C++11 [expr.comma]p1:
10009 // Every value computation and side effect associated with the left
10010 // expression is sequenced before every value computation and side
10011 // effect associated with the right expression.
10012 SequenceTree::Seq LHS = Tree.allocate(Region);
10013 SequenceTree::Seq RHS = Tree.allocate(Region);
10014 SequenceTree::Seq OldRegion = Region;
10015
10016 {
10017 SequencedSubexpression SeqLHS(*this);
10018 Region = LHS;
10019 Visit(BO->getLHS());
10020 }
10021
10022 Region = RHS;
10023 Visit(BO->getRHS());
10024
10025 Region = OldRegion;
10026
10027 // Forget that LHS and RHS are sequenced. They are both unsequenced
10028 // with respect to other stuff.
10029 Tree.merge(LHS);
10030 Tree.merge(RHS);
10031 }
10032
10033 void VisitBinAssign(BinaryOperator *BO) {
10034 // The modification is sequenced after the value computation of the LHS
10035 // and RHS, so check it before inspecting the operands and update the
10036 // map afterwards.
10037 Object O = getObject(BO->getLHS(), true);
10038 if (!O)
10039 return VisitExpr(BO);
10040
10041 notePreMod(O, BO);
10042
10043 // C++11 [expr.ass]p7:
10044 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10045 // only once.
10046 //
10047 // Therefore, for a compound assignment operator, O is considered used
10048 // everywhere except within the evaluation of E1 itself.
10049 if (isa<CompoundAssignOperator>(BO))
10050 notePreUse(O, BO);
10051
10052 Visit(BO->getLHS());
10053
10054 if (isa<CompoundAssignOperator>(BO))
10055 notePostUse(O, BO);
10056
10057 Visit(BO->getRHS());
10058
Richard Smith83e37bee2013-06-26 23:16:51 +000010059 // C++11 [expr.ass]p1:
10060 // the assignment is sequenced [...] before the value computation of the
10061 // assignment expression.
10062 // C11 6.5.16/3 has no such rule.
10063 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10064 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010065 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010066
Richard Smithc406cb72013-01-17 01:17:56 +000010067 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10068 VisitBinAssign(CAO);
10069 }
10070
10071 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10072 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10073 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10074 Object O = getObject(UO->getSubExpr(), true);
10075 if (!O)
10076 return VisitExpr(UO);
10077
10078 notePreMod(O, UO);
10079 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010080 // C++11 [expr.pre.incr]p1:
10081 // the expression ++x is equivalent to x+=1
10082 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10083 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010084 }
10085
10086 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10087 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10088 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10089 Object O = getObject(UO->getSubExpr(), true);
10090 if (!O)
10091 return VisitExpr(UO);
10092
10093 notePreMod(O, UO);
10094 Visit(UO->getSubExpr());
10095 notePostMod(O, UO, UK_ModAsSideEffect);
10096 }
10097
10098 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10099 void VisitBinLOr(BinaryOperator *BO) {
10100 // The side-effects of the LHS of an '&&' are sequenced before the
10101 // value computation of the RHS, and hence before the value computation
10102 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10103 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010104 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010105 {
10106 SequencedSubexpression Sequenced(*this);
10107 Visit(BO->getLHS());
10108 }
10109
10110 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010111 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010112 if (!Result)
10113 Visit(BO->getRHS());
10114 } else {
10115 // Check for unsequenced operations in the RHS, treating it as an
10116 // entirely separate evaluation.
10117 //
10118 // FIXME: If there are operations in the RHS which are unsequenced
10119 // with respect to operations outside the RHS, and those operations
10120 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010121 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010122 }
Richard Smithc406cb72013-01-17 01:17:56 +000010123 }
10124 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010125 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010126 {
10127 SequencedSubexpression Sequenced(*this);
10128 Visit(BO->getLHS());
10129 }
10130
10131 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010132 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010133 if (Result)
10134 Visit(BO->getRHS());
10135 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010136 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010137 }
Richard Smithc406cb72013-01-17 01:17:56 +000010138 }
10139
10140 // Only visit the condition, unless we can be sure which subexpression will
10141 // be chosen.
10142 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010143 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010144 {
10145 SequencedSubexpression Sequenced(*this);
10146 Visit(CO->getCond());
10147 }
Richard Smithc406cb72013-01-17 01:17:56 +000010148
10149 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010150 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010151 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010152 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010153 WorkList.push_back(CO->getTrueExpr());
10154 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010155 }
Richard Smithc406cb72013-01-17 01:17:56 +000010156 }
10157
Richard Smithe3dbfe02013-06-30 10:40:20 +000010158 void VisitCallExpr(CallExpr *CE) {
10159 // C++11 [intro.execution]p15:
10160 // When calling a function [...], every value computation and side effect
10161 // associated with any argument expression, or with the postfix expression
10162 // designating the called function, is sequenced before execution of every
10163 // expression or statement in the body of the function [and thus before
10164 // the value computation of its result].
10165 SequencedSubexpression Sequenced(*this);
10166 Base::VisitCallExpr(CE);
10167
10168 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10169 }
10170
Richard Smithc406cb72013-01-17 01:17:56 +000010171 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010172 // This is a call, so all subexpressions are sequenced before the result.
10173 SequencedSubexpression Sequenced(*this);
10174
Richard Smithc406cb72013-01-17 01:17:56 +000010175 if (!CCE->isListInitialization())
10176 return VisitExpr(CCE);
10177
10178 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010179 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010180 SequenceTree::Seq Parent = Region;
10181 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10182 E = CCE->arg_end();
10183 I != E; ++I) {
10184 Region = Tree.allocate(Parent);
10185 Elts.push_back(Region);
10186 Visit(*I);
10187 }
10188
10189 // Forget that the initializers are sequenced.
10190 Region = Parent;
10191 for (unsigned I = 0; I < Elts.size(); ++I)
10192 Tree.merge(Elts[I]);
10193 }
10194
10195 void VisitInitListExpr(InitListExpr *ILE) {
10196 if (!SemaRef.getLangOpts().CPlusPlus11)
10197 return VisitExpr(ILE);
10198
10199 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010200 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010201 SequenceTree::Seq Parent = Region;
10202 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10203 Expr *E = ILE->getInit(I);
10204 if (!E) continue;
10205 Region = Tree.allocate(Parent);
10206 Elts.push_back(Region);
10207 Visit(E);
10208 }
10209
10210 // Forget that the initializers are sequenced.
10211 Region = Parent;
10212 for (unsigned I = 0; I < Elts.size(); ++I)
10213 Tree.merge(Elts[I]);
10214 }
10215};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010216} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010217
10218void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010219 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010220 WorkList.push_back(E);
10221 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010222 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010223 SequenceChecker(*this, Item, WorkList);
10224 }
Richard Smithc406cb72013-01-17 01:17:56 +000010225}
10226
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010227void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10228 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010229 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010230 if (!E->isInstantiationDependent())
10231 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010232 if (!IsConstexpr && !E->isValueDependent())
10233 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010234 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010235}
10236
John McCall1f425642010-11-11 03:21:53 +000010237void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10238 FieldDecl *BitField,
10239 Expr *Init) {
10240 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10241}
10242
David Majnemer61a5bbf2015-04-07 22:08:51 +000010243static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10244 SourceLocation Loc) {
10245 if (!PType->isVariablyModifiedType())
10246 return;
10247 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10248 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10249 return;
10250 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010251 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10252 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10253 return;
10254 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010255 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10256 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10257 return;
10258 }
10259
10260 const ArrayType *AT = S.Context.getAsArrayType(PType);
10261 if (!AT)
10262 return;
10263
10264 if (AT->getSizeModifier() != ArrayType::Star) {
10265 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10266 return;
10267 }
10268
10269 S.Diag(Loc, diag::err_array_star_in_function_definition);
10270}
10271
Mike Stump0c2ec772010-01-21 03:59:47 +000010272/// CheckParmsForFunctionDef - Check that the parameters of the given
10273/// function are appropriate for the definition of a function. This
10274/// takes care of any checks that cannot be performed on the
10275/// declaration itself, e.g., that the types of each of the function
10276/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010277bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010278 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010279 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010280 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010281 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10282 // function declarator that is part of a function definition of
10283 // that function shall not have incomplete type.
10284 //
10285 // This is also C++ [dcl.fct]p6.
10286 if (!Param->isInvalidDecl() &&
10287 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010288 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010289 Param->setInvalidDecl();
10290 HasInvalidParm = true;
10291 }
10292
10293 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10294 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010295 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010296 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010297 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010298 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010299 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010300
10301 // C99 6.7.5.3p12:
10302 // If the function declarator is not part of a definition of that
10303 // function, parameters may have incomplete type and may use the [*]
10304 // notation in their sequences of declarator specifiers to specify
10305 // variable length array types.
10306 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010307 // FIXME: This diagnostic should point the '[*]' if source-location
10308 // information is added for it.
10309 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010310
10311 // MSVC destroys objects passed by value in the callee. Therefore a
10312 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010313 // object's destructor. However, we don't perform any direct access check
10314 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010315 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10316 .getCXXABI()
10317 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010318 if (!Param->isInvalidDecl()) {
10319 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10320 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10321 if (!ClassDecl->isInvalidDecl() &&
10322 !ClassDecl->hasIrrelevantDestructor() &&
10323 !ClassDecl->isDependentContext()) {
10324 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10325 MarkFunctionReferenced(Param->getLocation(), Destructor);
10326 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10327 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010328 }
10329 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010330 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010331
10332 // Parameters with the pass_object_size attribute only need to be marked
10333 // constant at function definitions. Because we lack information about
10334 // whether we're on a declaration or definition when we're instantiating the
10335 // attribute, we need to check for constness here.
10336 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10337 if (!Param->getType().isConstQualified())
10338 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10339 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010340 }
10341
10342 return HasInvalidParm;
10343}
John McCall2b5c1b22010-08-12 21:44:57 +000010344
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010345/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10346/// or MemberExpr.
10347static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10348 ASTContext &Context) {
10349 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10350 return Context.getDeclAlign(DRE->getDecl());
10351
10352 if (const auto *ME = dyn_cast<MemberExpr>(E))
10353 return Context.getDeclAlign(ME->getMemberDecl());
10354
10355 return TypeAlign;
10356}
10357
John McCall2b5c1b22010-08-12 21:44:57 +000010358/// CheckCastAlign - Implements -Wcast-align, which warns when a
10359/// pointer cast increases the alignment requirements.
10360void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10361 // This is actually a lot of work to potentially be doing on every
10362 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010363 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010364 return;
10365
10366 // Ignore dependent types.
10367 if (T->isDependentType() || Op->getType()->isDependentType())
10368 return;
10369
10370 // Require that the destination be a pointer type.
10371 const PointerType *DestPtr = T->getAs<PointerType>();
10372 if (!DestPtr) return;
10373
10374 // If the destination has alignment 1, we're done.
10375 QualType DestPointee = DestPtr->getPointeeType();
10376 if (DestPointee->isIncompleteType()) return;
10377 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10378 if (DestAlign.isOne()) return;
10379
10380 // Require that the source be a pointer type.
10381 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10382 if (!SrcPtr) return;
10383 QualType SrcPointee = SrcPtr->getPointeeType();
10384
10385 // Whitelist casts from cv void*. We already implicitly
10386 // whitelisted casts to cv void*, since they have alignment 1.
10387 // Also whitelist casts involving incomplete types, which implicitly
10388 // includes 'void'.
10389 if (SrcPointee->isIncompleteType()) return;
10390
10391 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010392
10393 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10394 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10395 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10396 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10397 if (UO->getOpcode() == UO_AddrOf)
10398 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10399 }
10400
John McCall2b5c1b22010-08-12 21:44:57 +000010401 if (SrcAlign >= DestAlign) return;
10402
10403 Diag(TRange.getBegin(), diag::warn_cast_align)
10404 << Op->getType() << T
10405 << static_cast<unsigned>(SrcAlign.getQuantity())
10406 << static_cast<unsigned>(DestAlign.getQuantity())
10407 << TRange << Op->getSourceRange();
10408}
10409
Chandler Carruth28389f02011-08-05 09:10:50 +000010410/// \brief Check whether this array fits the idiom of a size-one tail padded
10411/// array member of a struct.
10412///
10413/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10414/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010415static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010416 const NamedDecl *ND) {
10417 if (Size != 1 || !ND) return false;
10418
10419 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10420 if (!FD) return false;
10421
10422 // Don't consider sizes resulting from macro expansions or template argument
10423 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010424
10425 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010426 while (TInfo) {
10427 TypeLoc TL = TInfo->getTypeLoc();
10428 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010429 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10430 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010431 TInfo = TDL->getTypeSourceInfo();
10432 continue;
10433 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010434 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10435 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010436 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10437 return false;
10438 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010439 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010440 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010441
10442 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010443 if (!RD) return false;
10444 if (RD->isUnion()) return false;
10445 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10446 if (!CRD->isStandardLayout()) return false;
10447 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010448
Benjamin Kramer8c543672011-08-06 03:04:42 +000010449 // See if this is the last field decl in the record.
10450 const Decl *D = FD;
10451 while ((D = D->getNextDeclInContext()))
10452 if (isa<FieldDecl>(D))
10453 return false;
10454 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010455}
10456
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010457void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010458 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010459 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010460 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010461 if (IndexExpr->isValueDependent())
10462 return;
10463
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010464 const Type *EffectiveType =
10465 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010466 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010467 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010468 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010469 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010470 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010471
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010472 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010473 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010474 return;
Richard Smith13f67182011-12-16 19:31:14 +000010475 if (IndexNegated)
10476 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010477
Craig Topperc3ec1492014-05-26 06:22:03 +000010478 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010479 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10480 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010481 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010482 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010483
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010484 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010485 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010486 if (!size.isStrictlyPositive())
10487 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010488
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010489 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010490 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010491 // Make sure we're comparing apples to apples when comparing index to size
10492 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10493 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010494 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010495 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010496 if (ptrarith_typesize != array_typesize) {
10497 // There's a cast to a different size type involved
10498 uint64_t ratio = array_typesize / ptrarith_typesize;
10499 // TODO: Be smarter about handling cases where array_typesize is not a
10500 // multiple of ptrarith_typesize
10501 if (ptrarith_typesize * ratio == array_typesize)
10502 size *= llvm::APInt(size.getBitWidth(), ratio);
10503 }
10504 }
10505
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010506 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010507 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010508 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010509 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010510
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010511 // For array subscripting the index must be less than size, but for pointer
10512 // arithmetic also allow the index (offset) to be equal to size since
10513 // computing the next address after the end of the array is legal and
10514 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010515 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010516 return;
10517
10518 // Also don't warn for arrays of size 1 which are members of some
10519 // structure. These are often used to approximate flexible arrays in C89
10520 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010521 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010522 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010523
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010524 // Suppress the warning if the subscript expression (as identified by the
10525 // ']' location) and the index expression are both from macro expansions
10526 // within a system header.
10527 if (ASE) {
10528 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10529 ASE->getRBracketLoc());
10530 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10531 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10532 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010533 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010534 return;
10535 }
10536 }
10537
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010538 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010539 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010540 DiagID = diag::warn_array_index_exceeds_bounds;
10541
10542 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10543 PDiag(DiagID) << index.toString(10, true)
10544 << size.toString(10, true)
10545 << (unsigned)size.getLimitedValue(~0U)
10546 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010547 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010548 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010549 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010550 DiagID = diag::warn_ptr_arith_precedes_bounds;
10551 if (index.isNegative()) index = -index;
10552 }
10553
10554 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10555 PDiag(DiagID) << index.toString(10, true)
10556 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010557 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010558
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010559 if (!ND) {
10560 // Try harder to find a NamedDecl to point at in the note.
10561 while (const ArraySubscriptExpr *ASE =
10562 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10563 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10564 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10565 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10566 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10567 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10568 }
10569
Chandler Carruth1af88f12011-02-17 21:10:52 +000010570 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010571 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10572 PDiag(diag::note_array_index_out_of_bounds)
10573 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010574}
10575
Ted Kremenekdf26df72011-03-01 18:41:00 +000010576void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010577 int AllowOnePastEnd = 0;
10578 while (expr) {
10579 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010580 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010581 case Stmt::ArraySubscriptExprClass: {
10582 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010583 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010584 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010585 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010586 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010587 case Stmt::OMPArraySectionExprClass: {
10588 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10589 if (ASE->getLowerBound())
10590 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10591 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10592 return;
10593 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010594 case Stmt::UnaryOperatorClass: {
10595 // Only unwrap the * and & unary operators
10596 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10597 expr = UO->getSubExpr();
10598 switch (UO->getOpcode()) {
10599 case UO_AddrOf:
10600 AllowOnePastEnd++;
10601 break;
10602 case UO_Deref:
10603 AllowOnePastEnd--;
10604 break;
10605 default:
10606 return;
10607 }
10608 break;
10609 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010610 case Stmt::ConditionalOperatorClass: {
10611 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10612 if (const Expr *lhs = cond->getLHS())
10613 CheckArrayAccess(lhs);
10614 if (const Expr *rhs = cond->getRHS())
10615 CheckArrayAccess(rhs);
10616 return;
10617 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010618 case Stmt::CXXOperatorCallExprClass: {
10619 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10620 for (const auto *Arg : OCE->arguments())
10621 CheckArrayAccess(Arg);
10622 return;
10623 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010624 default:
10625 return;
10626 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010627 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010628}
John McCall31168b02011-06-15 23:02:42 +000010629
10630//===--- CHECK: Objective-C retain cycles ----------------------------------//
10631
10632namespace {
10633 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010634 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010635 VarDecl *Variable;
10636 SourceRange Range;
10637 SourceLocation Loc;
10638 bool Indirect;
10639
10640 void setLocsFrom(Expr *e) {
10641 Loc = e->getExprLoc();
10642 Range = e->getSourceRange();
10643 }
10644 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010645} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010646
10647/// Consider whether capturing the given variable can possibly lead to
10648/// a retain cycle.
10649static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010650 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010651 // lifetime. In MRR, it's captured strongly if the variable is
10652 // __block and has an appropriate type.
10653 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10654 return false;
10655
10656 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010657 if (ref)
10658 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010659 return true;
10660}
10661
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010662static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010663 while (true) {
10664 e = e->IgnoreParens();
10665 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10666 switch (cast->getCastKind()) {
10667 case CK_BitCast:
10668 case CK_LValueBitCast:
10669 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010670 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010671 e = cast->getSubExpr();
10672 continue;
10673
John McCall31168b02011-06-15 23:02:42 +000010674 default:
10675 return false;
10676 }
10677 }
10678
10679 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10680 ObjCIvarDecl *ivar = ref->getDecl();
10681 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10682 return false;
10683
10684 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010685 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010686 return false;
10687
10688 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10689 owner.Indirect = true;
10690 return true;
10691 }
10692
10693 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10694 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10695 if (!var) return false;
10696 return considerVariable(var, ref, owner);
10697 }
10698
John McCall31168b02011-06-15 23:02:42 +000010699 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10700 if (member->isArrow()) return false;
10701
10702 // Don't count this as an indirect ownership.
10703 e = member->getBase();
10704 continue;
10705 }
10706
John McCallfe96e0b2011-11-06 09:01:30 +000010707 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10708 // Only pay attention to pseudo-objects on property references.
10709 ObjCPropertyRefExpr *pre
10710 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10711 ->IgnoreParens());
10712 if (!pre) return false;
10713 if (pre->isImplicitProperty()) return false;
10714 ObjCPropertyDecl *property = pre->getExplicitProperty();
10715 if (!property->isRetaining() &&
10716 !(property->getPropertyIvarDecl() &&
10717 property->getPropertyIvarDecl()->getType()
10718 .getObjCLifetime() == Qualifiers::OCL_Strong))
10719 return false;
10720
10721 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010722 if (pre->isSuperReceiver()) {
10723 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10724 if (!owner.Variable)
10725 return false;
10726 owner.Loc = pre->getLocation();
10727 owner.Range = pre->getSourceRange();
10728 return true;
10729 }
John McCallfe96e0b2011-11-06 09:01:30 +000010730 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10731 ->getSourceExpr());
10732 continue;
10733 }
10734
John McCall31168b02011-06-15 23:02:42 +000010735 // Array ivars?
10736
10737 return false;
10738 }
10739}
10740
10741namespace {
10742 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10743 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10744 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010745 Context(Context), Variable(variable), Capturer(nullptr),
10746 VarWillBeReased(false) {}
10747 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010748 VarDecl *Variable;
10749 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010750 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010751
10752 void VisitDeclRefExpr(DeclRefExpr *ref) {
10753 if (ref->getDecl() == Variable && !Capturer)
10754 Capturer = ref;
10755 }
10756
John McCall31168b02011-06-15 23:02:42 +000010757 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10758 if (Capturer) return;
10759 Visit(ref->getBase());
10760 if (Capturer && ref->isFreeIvar())
10761 Capturer = ref;
10762 }
10763
10764 void VisitBlockExpr(BlockExpr *block) {
10765 // Look inside nested blocks
10766 if (block->getBlockDecl()->capturesVariable(Variable))
10767 Visit(block->getBlockDecl()->getBody());
10768 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010769
10770 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10771 if (Capturer) return;
10772 if (OVE->getSourceExpr())
10773 Visit(OVE->getSourceExpr());
10774 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010775 void VisitBinaryOperator(BinaryOperator *BinOp) {
10776 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10777 return;
10778 Expr *LHS = BinOp->getLHS();
10779 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10780 if (DRE->getDecl() != Variable)
10781 return;
10782 if (Expr *RHS = BinOp->getRHS()) {
10783 RHS = RHS->IgnoreParenCasts();
10784 llvm::APSInt Value;
10785 VarWillBeReased =
10786 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10787 }
10788 }
10789 }
John McCall31168b02011-06-15 23:02:42 +000010790 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010791} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010792
10793/// Check whether the given argument is a block which captures a
10794/// variable.
10795static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10796 assert(owner.Variable && owner.Loc.isValid());
10797
10798 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010799
10800 // Look through [^{...} copy] and Block_copy(^{...}).
10801 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10802 Selector Cmd = ME->getSelector();
10803 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10804 e = ME->getInstanceReceiver();
10805 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010806 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010807 e = e->IgnoreParenCasts();
10808 }
10809 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10810 if (CE->getNumArgs() == 1) {
10811 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010812 if (Fn) {
10813 const IdentifierInfo *FnI = Fn->getIdentifier();
10814 if (FnI && FnI->isStr("_Block_copy")) {
10815 e = CE->getArg(0)->IgnoreParenCasts();
10816 }
10817 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010818 }
10819 }
10820
John McCall31168b02011-06-15 23:02:42 +000010821 BlockExpr *block = dyn_cast<BlockExpr>(e);
10822 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010823 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010824
10825 FindCaptureVisitor visitor(S.Context, owner.Variable);
10826 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010827 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010828}
10829
10830static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10831 RetainCycleOwner &owner) {
10832 assert(capturer);
10833 assert(owner.Variable && owner.Loc.isValid());
10834
10835 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10836 << owner.Variable << capturer->getSourceRange();
10837 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10838 << owner.Indirect << owner.Range;
10839}
10840
10841/// Check for a keyword selector that starts with the word 'add' or
10842/// 'set'.
10843static bool isSetterLikeSelector(Selector sel) {
10844 if (sel.isUnarySelector()) return false;
10845
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010846 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010847 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010848 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010849 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010850 else if (str.startswith("add")) {
10851 // Specially whitelist 'addOperationWithBlock:'.
10852 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10853 return false;
10854 str = str.substr(3);
10855 }
John McCall31168b02011-06-15 23:02:42 +000010856 else
10857 return false;
10858
10859 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010860 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010861}
10862
Benjamin Kramer3a743452015-03-09 15:03:32 +000010863static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10864 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010865 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10866 Message->getReceiverInterface(),
10867 NSAPI::ClassId_NSMutableArray);
10868 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010869 return None;
10870 }
10871
10872 Selector Sel = Message->getSelector();
10873
10874 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10875 S.NSAPIObj->getNSArrayMethodKind(Sel);
10876 if (!MKOpt) {
10877 return None;
10878 }
10879
10880 NSAPI::NSArrayMethodKind MK = *MKOpt;
10881
10882 switch (MK) {
10883 case NSAPI::NSMutableArr_addObject:
10884 case NSAPI::NSMutableArr_insertObjectAtIndex:
10885 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10886 return 0;
10887 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10888 return 1;
10889
10890 default:
10891 return None;
10892 }
10893
10894 return None;
10895}
10896
10897static
10898Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10899 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010900 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10901 Message->getReceiverInterface(),
10902 NSAPI::ClassId_NSMutableDictionary);
10903 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010904 return None;
10905 }
10906
10907 Selector Sel = Message->getSelector();
10908
10909 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10910 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10911 if (!MKOpt) {
10912 return None;
10913 }
10914
10915 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10916
10917 switch (MK) {
10918 case NSAPI::NSMutableDict_setObjectForKey:
10919 case NSAPI::NSMutableDict_setValueForKey:
10920 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10921 return 0;
10922
10923 default:
10924 return None;
10925 }
10926
10927 return None;
10928}
10929
10930static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010931 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10932 Message->getReceiverInterface(),
10933 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010934
Alex Denisov5dfac812015-08-06 04:51:14 +000010935 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10936 Message->getReceiverInterface(),
10937 NSAPI::ClassId_NSMutableOrderedSet);
10938 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010939 return None;
10940 }
10941
10942 Selector Sel = Message->getSelector();
10943
10944 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10945 if (!MKOpt) {
10946 return None;
10947 }
10948
10949 NSAPI::NSSetMethodKind MK = *MKOpt;
10950
10951 switch (MK) {
10952 case NSAPI::NSMutableSet_addObject:
10953 case NSAPI::NSOrderedSet_setObjectAtIndex:
10954 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10955 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10956 return 0;
10957 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10958 return 1;
10959 }
10960
10961 return None;
10962}
10963
10964void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10965 if (!Message->isInstanceMessage()) {
10966 return;
10967 }
10968
10969 Optional<int> ArgOpt;
10970
10971 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10972 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10973 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10974 return;
10975 }
10976
10977 int ArgIndex = *ArgOpt;
10978
Alex Denisove1d882c2015-03-04 17:55:52 +000010979 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10980 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10981 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10982 }
10983
Alex Denisov5dfac812015-08-06 04:51:14 +000010984 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010985 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010986 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010987 Diag(Message->getSourceRange().getBegin(),
10988 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010989 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010990 }
10991 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010992 } else {
10993 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10994
10995 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10996 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10997 }
10998
10999 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11000 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11001 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11002 ValueDecl *Decl = ReceiverRE->getDecl();
11003 Diag(Message->getSourceRange().getBegin(),
11004 diag::warn_objc_circular_container)
11005 << Decl->getName() << Decl->getName();
11006 if (!ArgRE->isObjCSelfExpr()) {
11007 Diag(Decl->getLocation(),
11008 diag::note_objc_circular_container_declared_here)
11009 << Decl->getName();
11010 }
11011 }
11012 }
11013 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11014 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11015 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11016 ObjCIvarDecl *Decl = IvarRE->getDecl();
11017 Diag(Message->getSourceRange().getBegin(),
11018 diag::warn_objc_circular_container)
11019 << Decl->getName() << Decl->getName();
11020 Diag(Decl->getLocation(),
11021 diag::note_objc_circular_container_declared_here)
11022 << Decl->getName();
11023 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011024 }
11025 }
11026 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011027}
11028
John McCall31168b02011-06-15 23:02:42 +000011029/// Check a message send to see if it's likely to cause a retain cycle.
11030void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11031 // Only check instance methods whose selector looks like a setter.
11032 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11033 return;
11034
11035 // Try to find a variable that the receiver is strongly owned by.
11036 RetainCycleOwner owner;
11037 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011038 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011039 return;
11040 } else {
11041 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11042 owner.Variable = getCurMethodDecl()->getSelfDecl();
11043 owner.Loc = msg->getSuperLoc();
11044 owner.Range = msg->getSuperLoc();
11045 }
11046
11047 // Check whether the receiver is captured by any of the arguments.
11048 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11049 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11050 return diagnoseRetainCycle(*this, capturer, owner);
11051}
11052
11053/// Check a property assign to see if it's likely to cause a retain cycle.
11054void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11055 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011056 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011057 return;
11058
11059 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11060 diagnoseRetainCycle(*this, capturer, owner);
11061}
11062
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011063void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11064 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011065 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011066 return;
11067
11068 // Because we don't have an expression for the variable, we have to set the
11069 // location explicitly here.
11070 Owner.Loc = Var->getLocation();
11071 Owner.Range = Var->getSourceRange();
11072
11073 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11074 diagnoseRetainCycle(*this, Capturer, Owner);
11075}
11076
Ted Kremenek9304da92012-12-21 08:04:28 +000011077static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11078 Expr *RHS, bool isProperty) {
11079 // Check if RHS is an Objective-C object literal, which also can get
11080 // immediately zapped in a weak reference. Note that we explicitly
11081 // allow ObjCStringLiterals, since those are designed to never really die.
11082 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011083
Ted Kremenek64873352012-12-21 22:46:35 +000011084 // This enum needs to match with the 'select' in
11085 // warn_objc_arc_literal_assign (off-by-1).
11086 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11087 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11088 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011089
11090 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011091 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011092 << (isProperty ? 0 : 1)
11093 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011094
11095 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011096}
11097
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011098static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11099 Qualifiers::ObjCLifetime LT,
11100 Expr *RHS, bool isProperty) {
11101 // Strip off any implicit cast added to get to the one ARC-specific.
11102 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11103 if (cast->getCastKind() == CK_ARCConsumeObject) {
11104 S.Diag(Loc, diag::warn_arc_retained_assign)
11105 << (LT == Qualifiers::OCL_ExplicitNone)
11106 << (isProperty ? 0 : 1)
11107 << RHS->getSourceRange();
11108 return true;
11109 }
11110 RHS = cast->getSubExpr();
11111 }
11112
11113 if (LT == Qualifiers::OCL_Weak &&
11114 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11115 return true;
11116
11117 return false;
11118}
11119
Ted Kremenekb36234d2012-12-21 08:04:20 +000011120bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11121 QualType LHS, Expr *RHS) {
11122 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11123
11124 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11125 return false;
11126
11127 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11128 return true;
11129
11130 return false;
11131}
11132
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011133void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11134 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011135 QualType LHSType;
11136 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011137 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011138 ObjCPropertyRefExpr *PRE
11139 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11140 if (PRE && !PRE->isImplicitProperty()) {
11141 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11142 if (PD)
11143 LHSType = PD->getType();
11144 }
11145
11146 if (LHSType.isNull())
11147 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011148
11149 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11150
11151 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011152 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011153 getCurFunction()->markSafeWeakUse(LHS);
11154 }
11155
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011156 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11157 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011158
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011159 // FIXME. Check for other life times.
11160 if (LT != Qualifiers::OCL_None)
11161 return;
11162
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011163 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011164 if (PRE->isImplicitProperty())
11165 return;
11166 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11167 if (!PD)
11168 return;
11169
Bill Wendling44426052012-12-20 19:22:21 +000011170 unsigned Attributes = PD->getPropertyAttributes();
11171 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011172 // when 'assign' attribute was not explicitly specified
11173 // by user, ignore it and rely on property type itself
11174 // for lifetime info.
11175 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11176 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11177 LHSType->isObjCRetainableType())
11178 return;
11179
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011180 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011181 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011182 Diag(Loc, diag::warn_arc_retained_property_assign)
11183 << RHS->getSourceRange();
11184 return;
11185 }
11186 RHS = cast->getSubExpr();
11187 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011188 }
Bill Wendling44426052012-12-20 19:22:21 +000011189 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011190 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11191 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011192 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011193 }
11194}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011195
11196//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11197
11198namespace {
11199bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11200 SourceLocation StmtLoc,
11201 const NullStmt *Body) {
11202 // Do not warn if the body is a macro that expands to nothing, e.g:
11203 //
11204 // #define CALL(x)
11205 // if (condition)
11206 // CALL(0);
11207 //
11208 if (Body->hasLeadingEmptyMacro())
11209 return false;
11210
11211 // Get line numbers of statement and body.
11212 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011213 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011214 &StmtLineInvalid);
11215 if (StmtLineInvalid)
11216 return false;
11217
11218 bool BodyLineInvalid;
11219 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11220 &BodyLineInvalid);
11221 if (BodyLineInvalid)
11222 return false;
11223
11224 // Warn if null statement and body are on the same line.
11225 if (StmtLine != BodyLine)
11226 return false;
11227
11228 return true;
11229}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011230} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011231
11232void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11233 const Stmt *Body,
11234 unsigned DiagID) {
11235 // Since this is a syntactic check, don't emit diagnostic for template
11236 // instantiations, this just adds noise.
11237 if (CurrentInstantiationScope)
11238 return;
11239
11240 // The body should be a null statement.
11241 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11242 if (!NBody)
11243 return;
11244
11245 // Do the usual checks.
11246 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11247 return;
11248
11249 Diag(NBody->getSemiLoc(), DiagID);
11250 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11251}
11252
11253void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11254 const Stmt *PossibleBody) {
11255 assert(!CurrentInstantiationScope); // Ensured by caller
11256
11257 SourceLocation StmtLoc;
11258 const Stmt *Body;
11259 unsigned DiagID;
11260 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11261 StmtLoc = FS->getRParenLoc();
11262 Body = FS->getBody();
11263 DiagID = diag::warn_empty_for_body;
11264 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11265 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11266 Body = WS->getBody();
11267 DiagID = diag::warn_empty_while_body;
11268 } else
11269 return; // Neither `for' nor `while'.
11270
11271 // The body should be a null statement.
11272 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11273 if (!NBody)
11274 return;
11275
11276 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011277 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011278 return;
11279
11280 // Do the usual checks.
11281 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11282 return;
11283
11284 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11285 // noise level low, emit diagnostics only if for/while is followed by a
11286 // CompoundStmt, e.g.:
11287 // for (int i = 0; i < n; i++);
11288 // {
11289 // a(i);
11290 // }
11291 // or if for/while is followed by a statement with more indentation
11292 // than for/while itself:
11293 // for (int i = 0; i < n; i++);
11294 // a(i);
11295 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11296 if (!ProbableTypo) {
11297 bool BodyColInvalid;
11298 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11299 PossibleBody->getLocStart(),
11300 &BodyColInvalid);
11301 if (BodyColInvalid)
11302 return;
11303
11304 bool StmtColInvalid;
11305 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11306 S->getLocStart(),
11307 &StmtColInvalid);
11308 if (StmtColInvalid)
11309 return;
11310
11311 if (BodyCol > StmtCol)
11312 ProbableTypo = true;
11313 }
11314
11315 if (ProbableTypo) {
11316 Diag(NBody->getSemiLoc(), DiagID);
11317 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11318 }
11319}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011320
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011321//===--- CHECK: Warn on self move with std::move. -------------------------===//
11322
11323/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11324void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11325 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011326 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11327 return;
11328
Richard Smith51ec0cf2017-02-21 01:17:38 +000011329 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011330 return;
11331
11332 // Strip parens and casts away.
11333 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11334 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11335
11336 // Check for a call expression
11337 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11338 if (!CE || CE->getNumArgs() != 1)
11339 return;
11340
11341 // Check for a call to std::move
11342 const FunctionDecl *FD = CE->getDirectCallee();
11343 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11344 !FD->getIdentifier()->isStr("move"))
11345 return;
11346
11347 // Get argument from std::move
11348 RHSExpr = CE->getArg(0);
11349
11350 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11351 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11352
11353 // Two DeclRefExpr's, check that the decls are the same.
11354 if (LHSDeclRef && RHSDeclRef) {
11355 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11356 return;
11357 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11358 RHSDeclRef->getDecl()->getCanonicalDecl())
11359 return;
11360
11361 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11362 << LHSExpr->getSourceRange()
11363 << RHSExpr->getSourceRange();
11364 return;
11365 }
11366
11367 // Member variables require a different approach to check for self moves.
11368 // MemberExpr's are the same if every nested MemberExpr refers to the same
11369 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11370 // the base Expr's are CXXThisExpr's.
11371 const Expr *LHSBase = LHSExpr;
11372 const Expr *RHSBase = RHSExpr;
11373 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11374 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11375 if (!LHSME || !RHSME)
11376 return;
11377
11378 while (LHSME && RHSME) {
11379 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11380 RHSME->getMemberDecl()->getCanonicalDecl())
11381 return;
11382
11383 LHSBase = LHSME->getBase();
11384 RHSBase = RHSME->getBase();
11385 LHSME = dyn_cast<MemberExpr>(LHSBase);
11386 RHSME = dyn_cast<MemberExpr>(RHSBase);
11387 }
11388
11389 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11390 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11391 if (LHSDeclRef && RHSDeclRef) {
11392 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11393 return;
11394 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11395 RHSDeclRef->getDecl()->getCanonicalDecl())
11396 return;
11397
11398 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11399 << LHSExpr->getSourceRange()
11400 << RHSExpr->getSourceRange();
11401 return;
11402 }
11403
11404 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11405 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11406 << LHSExpr->getSourceRange()
11407 << RHSExpr->getSourceRange();
11408}
11409
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011410//===--- Layout compatibility ----------------------------------------------//
11411
11412namespace {
11413
11414bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11415
11416/// \brief Check if two enumeration types are layout-compatible.
11417bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11418 // C++11 [dcl.enum] p8:
11419 // Two enumeration types are layout-compatible if they have the same
11420 // underlying type.
11421 return ED1->isComplete() && ED2->isComplete() &&
11422 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11423}
11424
11425/// \brief Check if two fields are layout-compatible.
11426bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11427 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11428 return false;
11429
11430 if (Field1->isBitField() != Field2->isBitField())
11431 return false;
11432
11433 if (Field1->isBitField()) {
11434 // Make sure that the bit-fields are the same length.
11435 unsigned Bits1 = Field1->getBitWidthValue(C);
11436 unsigned Bits2 = Field2->getBitWidthValue(C);
11437
11438 if (Bits1 != Bits2)
11439 return false;
11440 }
11441
11442 return true;
11443}
11444
11445/// \brief Check if two standard-layout structs are layout-compatible.
11446/// (C++11 [class.mem] p17)
11447bool isLayoutCompatibleStruct(ASTContext &C,
11448 RecordDecl *RD1,
11449 RecordDecl *RD2) {
11450 // If both records are C++ classes, check that base classes match.
11451 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11452 // If one of records is a CXXRecordDecl we are in C++ mode,
11453 // thus the other one is a CXXRecordDecl, too.
11454 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11455 // Check number of base classes.
11456 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11457 return false;
11458
11459 // Check the base classes.
11460 for (CXXRecordDecl::base_class_const_iterator
11461 Base1 = D1CXX->bases_begin(),
11462 BaseEnd1 = D1CXX->bases_end(),
11463 Base2 = D2CXX->bases_begin();
11464 Base1 != BaseEnd1;
11465 ++Base1, ++Base2) {
11466 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11467 return false;
11468 }
11469 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11470 // If only RD2 is a C++ class, it should have zero base classes.
11471 if (D2CXX->getNumBases() > 0)
11472 return false;
11473 }
11474
11475 // Check the fields.
11476 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11477 Field2End = RD2->field_end(),
11478 Field1 = RD1->field_begin(),
11479 Field1End = RD1->field_end();
11480 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11481 if (!isLayoutCompatible(C, *Field1, *Field2))
11482 return false;
11483 }
11484 if (Field1 != Field1End || Field2 != Field2End)
11485 return false;
11486
11487 return true;
11488}
11489
11490/// \brief Check if two standard-layout unions are layout-compatible.
11491/// (C++11 [class.mem] p18)
11492bool isLayoutCompatibleUnion(ASTContext &C,
11493 RecordDecl *RD1,
11494 RecordDecl *RD2) {
11495 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011496 for (auto *Field2 : RD2->fields())
11497 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011498
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011499 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011500 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11501 I = UnmatchedFields.begin(),
11502 E = UnmatchedFields.end();
11503
11504 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011505 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011506 bool Result = UnmatchedFields.erase(*I);
11507 (void) Result;
11508 assert(Result);
11509 break;
11510 }
11511 }
11512 if (I == E)
11513 return false;
11514 }
11515
11516 return UnmatchedFields.empty();
11517}
11518
11519bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11520 if (RD1->isUnion() != RD2->isUnion())
11521 return false;
11522
11523 if (RD1->isUnion())
11524 return isLayoutCompatibleUnion(C, RD1, RD2);
11525 else
11526 return isLayoutCompatibleStruct(C, RD1, RD2);
11527}
11528
11529/// \brief Check if two types are layout-compatible in C++11 sense.
11530bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11531 if (T1.isNull() || T2.isNull())
11532 return false;
11533
11534 // C++11 [basic.types] p11:
11535 // If two types T1 and T2 are the same type, then T1 and T2 are
11536 // layout-compatible types.
11537 if (C.hasSameType(T1, T2))
11538 return true;
11539
11540 T1 = T1.getCanonicalType().getUnqualifiedType();
11541 T2 = T2.getCanonicalType().getUnqualifiedType();
11542
11543 const Type::TypeClass TC1 = T1->getTypeClass();
11544 const Type::TypeClass TC2 = T2->getTypeClass();
11545
11546 if (TC1 != TC2)
11547 return false;
11548
11549 if (TC1 == Type::Enum) {
11550 return isLayoutCompatible(C,
11551 cast<EnumType>(T1)->getDecl(),
11552 cast<EnumType>(T2)->getDecl());
11553 } else if (TC1 == Type::Record) {
11554 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11555 return false;
11556
11557 return isLayoutCompatible(C,
11558 cast<RecordType>(T1)->getDecl(),
11559 cast<RecordType>(T2)->getDecl());
11560 }
11561
11562 return false;
11563}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011564} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011565
11566//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11567
11568namespace {
11569/// \brief Given a type tag expression find the type tag itself.
11570///
11571/// \param TypeExpr Type tag expression, as it appears in user's code.
11572///
11573/// \param VD Declaration of an identifier that appears in a type tag.
11574///
11575/// \param MagicValue Type tag magic value.
11576bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11577 const ValueDecl **VD, uint64_t *MagicValue) {
11578 while(true) {
11579 if (!TypeExpr)
11580 return false;
11581
11582 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11583
11584 switch (TypeExpr->getStmtClass()) {
11585 case Stmt::UnaryOperatorClass: {
11586 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11587 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11588 TypeExpr = UO->getSubExpr();
11589 continue;
11590 }
11591 return false;
11592 }
11593
11594 case Stmt::DeclRefExprClass: {
11595 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11596 *VD = DRE->getDecl();
11597 return true;
11598 }
11599
11600 case Stmt::IntegerLiteralClass: {
11601 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11602 llvm::APInt MagicValueAPInt = IL->getValue();
11603 if (MagicValueAPInt.getActiveBits() <= 64) {
11604 *MagicValue = MagicValueAPInt.getZExtValue();
11605 return true;
11606 } else
11607 return false;
11608 }
11609
11610 case Stmt::BinaryConditionalOperatorClass:
11611 case Stmt::ConditionalOperatorClass: {
11612 const AbstractConditionalOperator *ACO =
11613 cast<AbstractConditionalOperator>(TypeExpr);
11614 bool Result;
11615 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11616 if (Result)
11617 TypeExpr = ACO->getTrueExpr();
11618 else
11619 TypeExpr = ACO->getFalseExpr();
11620 continue;
11621 }
11622 return false;
11623 }
11624
11625 case Stmt::BinaryOperatorClass: {
11626 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11627 if (BO->getOpcode() == BO_Comma) {
11628 TypeExpr = BO->getRHS();
11629 continue;
11630 }
11631 return false;
11632 }
11633
11634 default:
11635 return false;
11636 }
11637 }
11638}
11639
11640/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11641///
11642/// \param TypeExpr Expression that specifies a type tag.
11643///
11644/// \param MagicValues Registered magic values.
11645///
11646/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11647/// kind.
11648///
11649/// \param TypeInfo Information about the corresponding C type.
11650///
11651/// \returns true if the corresponding C type was found.
11652bool GetMatchingCType(
11653 const IdentifierInfo *ArgumentKind,
11654 const Expr *TypeExpr, const ASTContext &Ctx,
11655 const llvm::DenseMap<Sema::TypeTagMagicValue,
11656 Sema::TypeTagData> *MagicValues,
11657 bool &FoundWrongKind,
11658 Sema::TypeTagData &TypeInfo) {
11659 FoundWrongKind = false;
11660
11661 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011662 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011663
11664 uint64_t MagicValue;
11665
11666 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11667 return false;
11668
11669 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011670 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011671 if (I->getArgumentKind() != ArgumentKind) {
11672 FoundWrongKind = true;
11673 return false;
11674 }
11675 TypeInfo.Type = I->getMatchingCType();
11676 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11677 TypeInfo.MustBeNull = I->getMustBeNull();
11678 return true;
11679 }
11680 return false;
11681 }
11682
11683 if (!MagicValues)
11684 return false;
11685
11686 llvm::DenseMap<Sema::TypeTagMagicValue,
11687 Sema::TypeTagData>::const_iterator I =
11688 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11689 if (I == MagicValues->end())
11690 return false;
11691
11692 TypeInfo = I->second;
11693 return true;
11694}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011695} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011696
11697void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11698 uint64_t MagicValue, QualType Type,
11699 bool LayoutCompatible,
11700 bool MustBeNull) {
11701 if (!TypeTagForDatatypeMagicValues)
11702 TypeTagForDatatypeMagicValues.reset(
11703 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11704
11705 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11706 (*TypeTagForDatatypeMagicValues)[Magic] =
11707 TypeTagData(Type, LayoutCompatible, MustBeNull);
11708}
11709
11710namespace {
11711bool IsSameCharType(QualType T1, QualType T2) {
11712 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11713 if (!BT1)
11714 return false;
11715
11716 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11717 if (!BT2)
11718 return false;
11719
11720 BuiltinType::Kind T1Kind = BT1->getKind();
11721 BuiltinType::Kind T2Kind = BT2->getKind();
11722
11723 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11724 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11725 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11726 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11727}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011728} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011729
11730void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11731 const Expr * const *ExprArgs) {
11732 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11733 bool IsPointerAttr = Attr->getIsPointer();
11734
11735 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11736 bool FoundWrongKind;
11737 TypeTagData TypeInfo;
11738 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11739 TypeTagForDatatypeMagicValues.get(),
11740 FoundWrongKind, TypeInfo)) {
11741 if (FoundWrongKind)
11742 Diag(TypeTagExpr->getExprLoc(),
11743 diag::warn_type_tag_for_datatype_wrong_kind)
11744 << TypeTagExpr->getSourceRange();
11745 return;
11746 }
11747
11748 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11749 if (IsPointerAttr) {
11750 // Skip implicit cast of pointer to `void *' (as a function argument).
11751 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011752 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011753 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011754 ArgumentExpr = ICE->getSubExpr();
11755 }
11756 QualType ArgumentType = ArgumentExpr->getType();
11757
11758 // Passing a `void*' pointer shouldn't trigger a warning.
11759 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11760 return;
11761
11762 if (TypeInfo.MustBeNull) {
11763 // Type tag with matching void type requires a null pointer.
11764 if (!ArgumentExpr->isNullPointerConstant(Context,
11765 Expr::NPC_ValueDependentIsNotNull)) {
11766 Diag(ArgumentExpr->getExprLoc(),
11767 diag::warn_type_safety_null_pointer_required)
11768 << ArgumentKind->getName()
11769 << ArgumentExpr->getSourceRange()
11770 << TypeTagExpr->getSourceRange();
11771 }
11772 return;
11773 }
11774
11775 QualType RequiredType = TypeInfo.Type;
11776 if (IsPointerAttr)
11777 RequiredType = Context.getPointerType(RequiredType);
11778
11779 bool mismatch = false;
11780 if (!TypeInfo.LayoutCompatible) {
11781 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11782
11783 // C++11 [basic.fundamental] p1:
11784 // Plain char, signed char, and unsigned char are three distinct types.
11785 //
11786 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11787 // char' depending on the current char signedness mode.
11788 if (mismatch)
11789 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11790 RequiredType->getPointeeType())) ||
11791 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11792 mismatch = false;
11793 } else
11794 if (IsPointerAttr)
11795 mismatch = !isLayoutCompatible(Context,
11796 ArgumentType->getPointeeType(),
11797 RequiredType->getPointeeType());
11798 else
11799 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11800
11801 if (mismatch)
11802 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011803 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011804 << TypeInfo.LayoutCompatible << RequiredType
11805 << ArgumentExpr->getSourceRange()
11806 << TypeTagExpr->getSourceRange();
11807}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011808
11809void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11810 CharUnits Alignment) {
11811 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11812}
11813
11814void Sema::DiagnoseMisalignedMembers() {
11815 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011816 const NamedDecl *ND = m.RD;
11817 if (ND->getName().empty()) {
11818 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11819 ND = TD;
11820 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011821 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011822 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011823 }
11824 MisalignedMembers.clear();
11825}
11826
11827void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011828 E = E->IgnoreParens();
11829 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011830 return;
11831 if (isa<UnaryOperator>(E) &&
11832 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11833 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11834 if (isa<MemberExpr>(Op)) {
11835 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11836 MisalignedMember(Op));
11837 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011838 (T->isIntegerType() ||
11839 (T->isPointerType() &&
11840 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011841 MisalignedMembers.erase(MA);
11842 }
11843 }
11844}
11845
11846void Sema::RefersToMemberWithReducedAlignment(
11847 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000011848 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
11849 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011850 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011851 if (!ME)
11852 return;
11853
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000011854 // No need to check expressions with an __unaligned-qualified type.
11855 if (E->getType().getQualifiers().hasUnaligned())
11856 return;
11857
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011858 // For a chain of MemberExpr like "a.b.c.d" this list
11859 // will keep FieldDecl's like [d, c, b].
11860 SmallVector<FieldDecl *, 4> ReverseMemberChain;
11861 const MemberExpr *TopME = nullptr;
11862 bool AnyIsPacked = false;
11863 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011864 QualType BaseType = ME->getBase()->getType();
11865 if (ME->isArrow())
11866 BaseType = BaseType->getPointeeType();
11867 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11868
11869 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011870 auto *FD = dyn_cast<FieldDecl>(MD);
11871 // We do not care about non-data members.
11872 if (!FD || FD->isInvalidDecl())
11873 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011874
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011875 AnyIsPacked =
11876 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
11877 ReverseMemberChain.push_back(FD);
11878
11879 TopME = ME;
11880 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
11881 } while (ME);
11882 assert(TopME && "We did not compute a topmost MemberExpr!");
11883
11884 // Not the scope of this diagnostic.
11885 if (!AnyIsPacked)
11886 return;
11887
11888 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
11889 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
11890 // TODO: The innermost base of the member expression may be too complicated.
11891 // For now, just disregard these cases. This is left for future
11892 // improvement.
11893 if (!DRE && !isa<CXXThisExpr>(TopBase))
11894 return;
11895
11896 // Alignment expected by the whole expression.
11897 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
11898
11899 // No need to do anything else with this case.
11900 if (ExpectedAlignment.isOne())
11901 return;
11902
11903 // Synthesize offset of the whole access.
11904 CharUnits Offset;
11905 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
11906 I++) {
11907 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
11908 }
11909
11910 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
11911 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
11912 ReverseMemberChain.back()->getParent()->getTypeForDecl());
11913
11914 // The base expression of the innermost MemberExpr may give
11915 // stronger guarantees than the class containing the member.
11916 if (DRE && !TopME->isArrow()) {
11917 const ValueDecl *VD = DRE->getDecl();
11918 if (!VD->getType()->isReferenceType())
11919 CompleteObjectAlignment =
11920 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
11921 }
11922
11923 // Check if the synthesized offset fulfills the alignment.
11924 if (Offset % ExpectedAlignment != 0 ||
11925 // It may fulfill the offset it but the effective alignment may still be
11926 // lower than the expected expression alignment.
11927 CompleteObjectAlignment < ExpectedAlignment) {
11928 // If this happens, we want to determine a sensible culprit of this.
11929 // Intuitively, watching the chain of member expressions from right to
11930 // left, we start with the required alignment (as required by the field
11931 // type) but some packed attribute in that chain has reduced the alignment.
11932 // It may happen that another packed structure increases it again. But if
11933 // we are here such increase has not been enough. So pointing the first
11934 // FieldDecl that either is packed or else its RecordDecl is,
11935 // seems reasonable.
11936 FieldDecl *FD = nullptr;
11937 CharUnits Alignment;
11938 for (FieldDecl *FDI : ReverseMemberChain) {
11939 if (FDI->hasAttr<PackedAttr>() ||
11940 FDI->getParent()->hasAttr<PackedAttr>()) {
11941 FD = FDI;
11942 Alignment = std::min(
11943 Context.getTypeAlignInChars(FD->getType()),
11944 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
11945 break;
11946 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011947 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000011948 assert(FD && "We did not find a packed FieldDecl!");
11949 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011950 }
11951}
11952
11953void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11954 using namespace std::placeholders;
11955 RefersToMemberWithReducedAlignment(
11956 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11957 _2, _3, _4));
11958}
11959