blob: 6956b0633bc227d14791c910663f946453de630f [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
247 if (!SemaRef.ActiveTemplateInstantiations.empty())
248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
312 diag::err_opencl_enqueue_kernel_expected_type) << "block";
313 return true;
314 }
315 return checkOpenCLBlockArgs(S, BlockArg);
316}
317
318static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319 unsigned Start, unsigned End);
320
321/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322/// 'local void*' parameter of passed block.
323static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324 Expr *BlockArg,
325 unsigned NumNonVarArgs) {
326 const BlockPointerType *BPT =
327 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328 unsigned NumBlockParams =
329 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330 unsigned TotalNumArgs = TheCall->getNumArgs();
331
332 // For each argument passed to the block, a corresponding uint needs to
333 // be passed to describe the size of the local memory.
334 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335 S.Diag(TheCall->getLocStart(),
336 diag::err_opencl_enqueue_kernel_local_size_args);
337 return true;
338 }
339
340 // Check that the sizes of the local memory are specified by integers.
341 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342 TotalNumArgs - 1);
343}
344
345/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346/// overload formats specified in Table 6.13.17.1.
347/// int enqueue_kernel(queue_t queue,
348/// kernel_enqueue_flags_t flags,
349/// const ndrange_t ndrange,
350/// void (^block)(void))
351/// int enqueue_kernel(queue_t queue,
352/// kernel_enqueue_flags_t flags,
353/// const ndrange_t ndrange,
354/// uint num_events_in_wait_list,
355/// clk_event_t *event_wait_list,
356/// clk_event_t *event_ret,
357/// void (^block)(void))
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(local void*, ...),
362/// uint size0, ...)
363/// int enqueue_kernel(queue_t queue,
364/// kernel_enqueue_flags_t flags,
365/// const ndrange_t ndrange,
366/// uint num_events_in_wait_list,
367/// clk_event_t *event_wait_list,
368/// clk_event_t *event_ret,
369/// void (^block)(local void*, ...),
370/// uint size0, ...)
371static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372 unsigned NumArgs = TheCall->getNumArgs();
373
374 if (NumArgs < 4) {
375 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376 return true;
377 }
378
379 Expr *Arg0 = TheCall->getArg(0);
380 Expr *Arg1 = TheCall->getArg(1);
381 Expr *Arg2 = TheCall->getArg(2);
382 Expr *Arg3 = TheCall->getArg(3);
383
384 // First argument always needs to be a queue_t type.
385 if (!Arg0->getType()->isQueueT()) {
386 S.Diag(TheCall->getArg(0)->getLocStart(),
387 diag::err_opencl_enqueue_kernel_expected_type)
388 << S.Context.OCLQueueTy;
389 return true;
390 }
391
392 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393 if (!Arg1->getType()->isIntegerType()) {
394 S.Diag(TheCall->getArg(1)->getLocStart(),
395 diag::err_opencl_enqueue_kernel_expected_type)
396 << "'kernel_enqueue_flags_t' (i.e. uint)";
397 return true;
398 }
399
400 // Third argument is always an ndrange_t type.
401 if (!Arg2->getType()->isNDRangeT()) {
402 S.Diag(TheCall->getArg(2)->getLocStart(),
403 diag::err_opencl_enqueue_kernel_expected_type)
404 << S.Context.OCLNDRangeTy;
405 return true;
406 }
407
408 // With four arguments, there is only one form that the function could be
409 // called in: no events and no variable arguments.
410 if (NumArgs == 4) {
411 // check that the last argument is the right block type.
412 if (!isBlockPointer(Arg3)) {
413 S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414 << "block";
415 return true;
416 }
417 // we have a block type, check the prototype
418 const BlockPointerType *BPT =
419 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421 S.Diag(Arg3->getLocStart(),
422 diag::err_opencl_enqueue_kernel_blocks_no_args);
423 return true;
424 }
425 return false;
426 }
427 // we can have block + varargs.
428 if (isBlockPointer(Arg3))
429 return (checkOpenCLBlockArgs(S, Arg3) ||
430 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431 // last two cases with either exactly 7 args or 7 args and varargs.
432 if (NumArgs >= 7) {
433 // check common block argument.
434 Expr *Arg6 = TheCall->getArg(6);
435 if (!isBlockPointer(Arg6)) {
436 S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437 << "block";
438 return true;
439 }
440 if (checkOpenCLBlockArgs(S, Arg6))
441 return true;
442
443 // Forth argument has to be any integer type.
444 if (!Arg3->getType()->isIntegerType()) {
445 S.Diag(TheCall->getArg(3)->getLocStart(),
446 diag::err_opencl_enqueue_kernel_expected_type)
447 << "integer";
448 return true;
449 }
450 // check remaining common arguments.
451 Expr *Arg4 = TheCall->getArg(4);
452 Expr *Arg5 = TheCall->getArg(5);
453
454 // Fith argument is always passed as pointers to clk_event_t.
455 if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456 S.Diag(TheCall->getArg(4)->getLocStart(),
457 diag::err_opencl_enqueue_kernel_expected_type)
458 << S.Context.getPointerType(S.Context.OCLClkEventTy);
459 return true;
460 }
461
462 // Sixth argument is always passed as pointers to clk_event_t.
463 if (!(Arg5->getType()->isPointerType() &&
464 Arg5->getType()->getPointeeType()->isClkEventT())) {
465 S.Diag(TheCall->getArg(5)->getLocStart(),
466 diag::err_opencl_enqueue_kernel_expected_type)
467 << S.Context.getPointerType(S.Context.OCLClkEventTy);
468 return true;
469 }
470
471 if (NumArgs == 7)
472 return false;
473
474 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475 }
476
477 // None of the specific case has been detected, give generic error
478 S.Diag(TheCall->getLocStart(),
479 diag::err_opencl_enqueue_kernel_incorrect_args);
480 return true;
481}
482
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000483/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000484static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000485 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000486}
487
488/// Returns true if pipe element type is different from the pointer.
489static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490 const Expr *Arg0 = Call->getArg(0);
491 // First argument type should always be pipe.
492 if (!Arg0->getType()->isPipeType()) {
493 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000494 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000495 return true;
496 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000497 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000498 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499 // Validates the access qualifier is compatible with the call.
500 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501 // read_only and write_only, and assumed to be read_only if no qualifier is
502 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000503 switch (Call->getDirectCallee()->getBuiltinID()) {
504 case Builtin::BIread_pipe:
505 case Builtin::BIreserve_read_pipe:
506 case Builtin::BIcommit_read_pipe:
507 case Builtin::BIwork_group_reserve_read_pipe:
508 case Builtin::BIsub_group_reserve_read_pipe:
509 case Builtin::BIwork_group_commit_read_pipe:
510 case Builtin::BIsub_group_commit_read_pipe:
511 if (!(!AccessQual || AccessQual->isReadOnly())) {
512 S.Diag(Arg0->getLocStart(),
513 diag::err_opencl_builtin_pipe_invalid_access_modifier)
514 << "read_only" << Arg0->getSourceRange();
515 return true;
516 }
517 break;
518 case Builtin::BIwrite_pipe:
519 case Builtin::BIreserve_write_pipe:
520 case Builtin::BIcommit_write_pipe:
521 case Builtin::BIwork_group_reserve_write_pipe:
522 case Builtin::BIsub_group_reserve_write_pipe:
523 case Builtin::BIwork_group_commit_write_pipe:
524 case Builtin::BIsub_group_commit_write_pipe:
525 if (!(AccessQual && AccessQual->isWriteOnly())) {
526 S.Diag(Arg0->getLocStart(),
527 diag::err_opencl_builtin_pipe_invalid_access_modifier)
528 << "write_only" << Arg0->getSourceRange();
529 return true;
530 }
531 break;
532 default:
533 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000534 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000535 return false;
536}
537
538/// Returns true if pipe element type is different from the pointer.
539static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540 const Expr *Arg0 = Call->getArg(0);
541 const Expr *ArgIdx = Call->getArg(Idx);
542 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000543 const QualType EltTy = PipeTy->getElementType();
544 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000545 // The Idx argument should be a pointer and the type of the pointer and
546 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000547 if (!ArgTy ||
548 !S.Context.hasSameType(
549 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000550 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000551 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000552 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000553 return true;
554 }
555 return false;
556}
557
558// \brief Performs semantic analysis for the read/write_pipe call.
559// \param S Reference to the semantic analyzer.
560// \param Call A pointer to the builtin call.
561// \return True if a semantic error has been found, false otherwise.
562static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000563 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000565 switch (Call->getNumArgs()) {
566 case 2: {
567 if (checkOpenCLPipeArg(S, Call))
568 return true;
569 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000570 // read/write_pipe(pipe T, T*).
571 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000572 if (checkOpenCLPipePacketType(S, Call, 1))
573 return true;
574 } break;
575
576 case 4: {
577 if (checkOpenCLPipeArg(S, Call))
578 return true;
579 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 if (!Call->getArg(1)->getType()->isReserveIDT()) {
583 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000584 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000585 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000586 return true;
587 }
588
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000589 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000590 const Expr *Arg2 = Call->getArg(2);
591 if (!Arg2->getType()->isIntegerType() &&
592 !Arg2->getType()->isUnsignedIntegerType()) {
593 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000594 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000595 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000596 return true;
597 }
598
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000599 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000600 if (checkOpenCLPipePacketType(S, Call, 3))
601 return true;
602 } break;
603 default:
604 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000605 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000606 return true;
607 }
608
609 return false;
610}
611
612// \brief Performs a semantic analysis on the {work_group_/sub_group_
613// /_}reserve_{read/write}_pipe
614// \param S Reference to the semantic analyzer.
615// \param Call The call to the builtin function to be analyzed.
616// \return True if a semantic error was found, false otherwise.
617static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618 if (checkArgCount(S, Call, 2))
619 return true;
620
621 if (checkOpenCLPipeArg(S, Call))
622 return true;
623
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000624 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 if (!Call->getArg(1)->getType()->isIntegerType() &&
626 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000628 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000629 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000630 return true;
631 }
632
633 return false;
634}
635
636// \brief Performs a semantic analysis on {work_group_/sub_group_
637// /_}commit_{read/write}_pipe
638// \param S Reference to the semantic analyzer.
639// \param Call The call to the builtin function to be analyzed.
640// \return True if a semantic error was found, false otherwise.
641static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642 if (checkArgCount(S, Call, 2))
643 return true;
644
645 if (checkOpenCLPipeArg(S, Call))
646 return true;
647
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000648 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000649 if (!Call->getArg(1)->getType()->isReserveIDT()) {
650 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000651 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000652 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000653 return true;
654 }
655
656 return false;
657}
658
659// \brief Performs a semantic analysis on the call to built-in Pipe
660// Query Functions.
661// \param S Reference to the semantic analyzer.
662// \param Call The call to the builtin function to be analyzed.
663// \return True if a semantic error was found, false otherwise.
664static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665 if (checkArgCount(S, Call, 1))
666 return true;
667
668 if (!Call->getArg(0)->getType()->isPipeType()) {
669 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000670 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
674 return false;
675}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000676// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000677// \brief Performs semantic analysis for the to_global/local/private call.
678// \param S Reference to the semantic analyzer.
679// \param BuiltinID ID of the builtin function.
680// \param Call A pointer to the builtin call.
681// \return True if a semantic error has been found, false otherwise.
682static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000684 if (Call->getNumArgs() != 1) {
685 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686 << Call->getDirectCallee() << Call->getSourceRange();
687 return true;
688 }
689
690 auto RT = Call->getArg(0)->getType();
691 if (!RT->isPointerType() || RT->getPointeeType()
692 .getAddressSpace() == LangAS::opencl_constant) {
693 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695 return true;
696 }
697
698 RT = RT->getPointeeType();
699 auto Qual = RT.getQualifiers();
700 switch (BuiltinID) {
701 case Builtin::BIto_global:
702 Qual.setAddressSpace(LangAS::opencl_global);
703 break;
704 case Builtin::BIto_local:
705 Qual.setAddressSpace(LangAS::opencl_local);
706 break;
707 default:
708 Qual.removeAddressSpace();
709 }
710 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711 RT.getUnqualifiedType(), Qual)));
712
713 return false;
714}
715
John McCalldadc5752010-08-24 06:29:42 +0000716ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000717Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000720
Chris Lattner3be167f2010-10-01 23:23:24 +0000721 // Find out if any arguments are required to be integer constant expressions.
722 unsigned ICEArguments = 0;
723 ASTContext::GetBuiltinTypeError Error;
724 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725 if (Error != ASTContext::GE_None)
726 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
727
728 // If any arguments are required to be ICE's, check and diagnose.
729 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730 // Skip arguments not required to be ICE's.
731 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732
733 llvm::APSInt Result;
734 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735 return true;
736 ICEArguments &= ~(1 << ArgNo);
737 }
738
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000739 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000740 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000741 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000742 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000743 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000744 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000745 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000746 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000747 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000748 if (SemaBuiltinVAStart(TheCall))
749 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000750 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000751 case Builtin::BI__va_start: {
752 switch (Context.getTargetInfo().getTriple().getArch()) {
753 case llvm::Triple::arm:
754 case llvm::Triple::thumb:
755 if (SemaBuiltinVAStartARM(TheCall))
756 return ExprError();
757 break;
758 default:
759 if (SemaBuiltinVAStart(TheCall))
760 return ExprError();
761 break;
762 }
763 break;
764 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000765 case Builtin::BI__builtin_isgreater:
766 case Builtin::BI__builtin_isgreaterequal:
767 case Builtin::BI__builtin_isless:
768 case Builtin::BI__builtin_islessequal:
769 case Builtin::BI__builtin_islessgreater:
770 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000771 if (SemaBuiltinUnorderedCompare(TheCall))
772 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000773 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000774 case Builtin::BI__builtin_fpclassify:
775 if (SemaBuiltinFPClassification(TheCall, 6))
776 return ExprError();
777 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000778 case Builtin::BI__builtin_isfinite:
779 case Builtin::BI__builtin_isinf:
780 case Builtin::BI__builtin_isinf_sign:
781 case Builtin::BI__builtin_isnan:
782 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000783 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000784 return ExprError();
785 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000786 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000787 return SemaBuiltinShuffleVector(TheCall);
788 // TheCall will be freed by the smart pointer here, but that's fine, since
789 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000790 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000791 if (SemaBuiltinPrefetch(TheCall))
792 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000793 break;
David Majnemer51169932016-10-31 05:37:48 +0000794 case Builtin::BI__builtin_alloca_with_align:
795 if (SemaBuiltinAllocaWithAlign(TheCall))
796 return ExprError();
797 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000798 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000799 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000800 if (SemaBuiltinAssume(TheCall))
801 return ExprError();
802 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000803 case Builtin::BI__builtin_assume_aligned:
804 if (SemaBuiltinAssumeAligned(TheCall))
805 return ExprError();
806 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000807 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000808 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000811 case Builtin::BI__builtin_longjmp:
812 if (SemaBuiltinLongjmp(TheCall))
813 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000814 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000815 case Builtin::BI__builtin_setjmp:
816 if (SemaBuiltinSetjmp(TheCall))
817 return ExprError();
818 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000819 case Builtin::BI_setjmp:
820 case Builtin::BI_setjmpex:
821 if (checkArgCount(*this, TheCall, 1))
822 return true;
823 break;
John McCallbebede42011-02-26 05:39:39 +0000824
825 case Builtin::BI__builtin_classify_type:
826 if (checkArgCount(*this, TheCall, 1)) return true;
827 TheCall->setType(Context.IntTy);
828 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000829 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000830 if (checkArgCount(*this, TheCall, 1)) return true;
831 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000832 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000833 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000834 case Builtin::BI__sync_fetch_and_add_1:
835 case Builtin::BI__sync_fetch_and_add_2:
836 case Builtin::BI__sync_fetch_and_add_4:
837 case Builtin::BI__sync_fetch_and_add_8:
838 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000839 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000840 case Builtin::BI__sync_fetch_and_sub_1:
841 case Builtin::BI__sync_fetch_and_sub_2:
842 case Builtin::BI__sync_fetch_and_sub_4:
843 case Builtin::BI__sync_fetch_and_sub_8:
844 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000845 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000846 case Builtin::BI__sync_fetch_and_or_1:
847 case Builtin::BI__sync_fetch_and_or_2:
848 case Builtin::BI__sync_fetch_and_or_4:
849 case Builtin::BI__sync_fetch_and_or_8:
850 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000851 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000852 case Builtin::BI__sync_fetch_and_and_1:
853 case Builtin::BI__sync_fetch_and_and_2:
854 case Builtin::BI__sync_fetch_and_and_4:
855 case Builtin::BI__sync_fetch_and_and_8:
856 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000857 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000858 case Builtin::BI__sync_fetch_and_xor_1:
859 case Builtin::BI__sync_fetch_and_xor_2:
860 case Builtin::BI__sync_fetch_and_xor_4:
861 case Builtin::BI__sync_fetch_and_xor_8:
862 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000863 case Builtin::BI__sync_fetch_and_nand:
864 case Builtin::BI__sync_fetch_and_nand_1:
865 case Builtin::BI__sync_fetch_and_nand_2:
866 case Builtin::BI__sync_fetch_and_nand_4:
867 case Builtin::BI__sync_fetch_and_nand_8:
868 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000869 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000870 case Builtin::BI__sync_add_and_fetch_1:
871 case Builtin::BI__sync_add_and_fetch_2:
872 case Builtin::BI__sync_add_and_fetch_4:
873 case Builtin::BI__sync_add_and_fetch_8:
874 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000875 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000876 case Builtin::BI__sync_sub_and_fetch_1:
877 case Builtin::BI__sync_sub_and_fetch_2:
878 case Builtin::BI__sync_sub_and_fetch_4:
879 case Builtin::BI__sync_sub_and_fetch_8:
880 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000881 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000882 case Builtin::BI__sync_and_and_fetch_1:
883 case Builtin::BI__sync_and_and_fetch_2:
884 case Builtin::BI__sync_and_and_fetch_4:
885 case Builtin::BI__sync_and_and_fetch_8:
886 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000887 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000888 case Builtin::BI__sync_or_and_fetch_1:
889 case Builtin::BI__sync_or_and_fetch_2:
890 case Builtin::BI__sync_or_and_fetch_4:
891 case Builtin::BI__sync_or_and_fetch_8:
892 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000893 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000894 case Builtin::BI__sync_xor_and_fetch_1:
895 case Builtin::BI__sync_xor_and_fetch_2:
896 case Builtin::BI__sync_xor_and_fetch_4:
897 case Builtin::BI__sync_xor_and_fetch_8:
898 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000899 case Builtin::BI__sync_nand_and_fetch:
900 case Builtin::BI__sync_nand_and_fetch_1:
901 case Builtin::BI__sync_nand_and_fetch_2:
902 case Builtin::BI__sync_nand_and_fetch_4:
903 case Builtin::BI__sync_nand_and_fetch_8:
904 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000905 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000906 case Builtin::BI__sync_val_compare_and_swap_1:
907 case Builtin::BI__sync_val_compare_and_swap_2:
908 case Builtin::BI__sync_val_compare_and_swap_4:
909 case Builtin::BI__sync_val_compare_and_swap_8:
910 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000911 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000912 case Builtin::BI__sync_bool_compare_and_swap_1:
913 case Builtin::BI__sync_bool_compare_and_swap_2:
914 case Builtin::BI__sync_bool_compare_and_swap_4:
915 case Builtin::BI__sync_bool_compare_and_swap_8:
916 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000917 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000918 case Builtin::BI__sync_lock_test_and_set_1:
919 case Builtin::BI__sync_lock_test_and_set_2:
920 case Builtin::BI__sync_lock_test_and_set_4:
921 case Builtin::BI__sync_lock_test_and_set_8:
922 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000923 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000924 case Builtin::BI__sync_lock_release_1:
925 case Builtin::BI__sync_lock_release_2:
926 case Builtin::BI__sync_lock_release_4:
927 case Builtin::BI__sync_lock_release_8:
928 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000929 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000930 case Builtin::BI__sync_swap_1:
931 case Builtin::BI__sync_swap_2:
932 case Builtin::BI__sync_swap_4:
933 case Builtin::BI__sync_swap_8:
934 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000935 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000936 case Builtin::BI__builtin_nontemporal_load:
937 case Builtin::BI__builtin_nontemporal_store:
938 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000939#define BUILTIN(ID, TYPE, ATTRS)
940#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
941 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000942 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000943#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000944 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000945 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000946 return ExprError();
947 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000948 case Builtin::BI__builtin_addressof:
949 if (SemaBuiltinAddressof(*this, TheCall))
950 return ExprError();
951 break;
John McCall03107a42015-10-29 20:48:01 +0000952 case Builtin::BI__builtin_add_overflow:
953 case Builtin::BI__builtin_sub_overflow:
954 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000955 if (SemaBuiltinOverflow(*this, TheCall))
956 return ExprError();
957 break;
Richard Smith760520b2014-06-03 23:27:44 +0000958 case Builtin::BI__builtin_operator_new:
959 case Builtin::BI__builtin_operator_delete:
960 if (!getLangOpts().CPlusPlus) {
961 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
962 << (BuiltinID == Builtin::BI__builtin_operator_new
963 ? "__builtin_operator_new"
964 : "__builtin_operator_delete")
965 << "C++";
966 return ExprError();
967 }
968 // CodeGen assumes it can find the global new and delete to call,
969 // so ensure that they are declared.
970 DeclareGlobalNewDelete();
971 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000972
973 // check secure string manipulation functions where overflows
974 // are detectable at compile time
975 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000976 case Builtin::BI__builtin___memmove_chk:
977 case Builtin::BI__builtin___memset_chk:
978 case Builtin::BI__builtin___strlcat_chk:
979 case Builtin::BI__builtin___strlcpy_chk:
980 case Builtin::BI__builtin___strncat_chk:
981 case Builtin::BI__builtin___strncpy_chk:
982 case Builtin::BI__builtin___stpncpy_chk:
983 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
984 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000985 case Builtin::BI__builtin___memccpy_chk:
986 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
987 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000988 case Builtin::BI__builtin___snprintf_chk:
989 case Builtin::BI__builtin___vsnprintf_chk:
990 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
991 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000992 case Builtin::BI__builtin_call_with_static_chain:
993 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
994 return ExprError();
995 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000996 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000997 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000998 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
999 diag::err_seh___except_block))
1000 return ExprError();
1001 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001002 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001003 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001004 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1005 diag::err_seh___except_filter))
1006 return ExprError();
1007 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001008 case Builtin::BI__GetExceptionInfo:
1009 if (checkArgCount(*this, TheCall, 1))
1010 return ExprError();
1011
1012 if (CheckCXXThrowOperand(
1013 TheCall->getLocStart(),
1014 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1015 TheCall))
1016 return ExprError();
1017
1018 TheCall->setType(Context.VoidPtrTy);
1019 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001020 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001021 case Builtin::BIread_pipe:
1022 case Builtin::BIwrite_pipe:
1023 // Since those two functions are declared with var args, we need a semantic
1024 // check for the argument.
1025 if (SemaBuiltinRWPipe(*this, TheCall))
1026 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001027 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001028 break;
1029 case Builtin::BIreserve_read_pipe:
1030 case Builtin::BIreserve_write_pipe:
1031 case Builtin::BIwork_group_reserve_read_pipe:
1032 case Builtin::BIwork_group_reserve_write_pipe:
1033 case Builtin::BIsub_group_reserve_read_pipe:
1034 case Builtin::BIsub_group_reserve_write_pipe:
1035 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1036 return ExprError();
1037 // Since return type of reserve_read/write_pipe built-in function is
1038 // reserve_id_t, which is not defined in the builtin def file , we used int
1039 // as return type and need to override the return type of these functions.
1040 TheCall->setType(Context.OCLReserveIDTy);
1041 break;
1042 case Builtin::BIcommit_read_pipe:
1043 case Builtin::BIcommit_write_pipe:
1044 case Builtin::BIwork_group_commit_read_pipe:
1045 case Builtin::BIwork_group_commit_write_pipe:
1046 case Builtin::BIsub_group_commit_read_pipe:
1047 case Builtin::BIsub_group_commit_write_pipe:
1048 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1049 return ExprError();
1050 break;
1051 case Builtin::BIget_pipe_num_packets:
1052 case Builtin::BIget_pipe_max_packets:
1053 if (SemaBuiltinPipePackets(*this, TheCall))
1054 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001055 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001056 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001057 case Builtin::BIto_global:
1058 case Builtin::BIto_local:
1059 case Builtin::BIto_private:
1060 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1061 return ExprError();
1062 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001063 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1064 case Builtin::BIenqueue_kernel:
1065 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1066 return ExprError();
1067 break;
1068 case Builtin::BIget_kernel_work_group_size:
1069 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1070 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1071 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001072 break;
1073 case Builtin::BI__builtin_os_log_format:
1074 case Builtin::BI__builtin_os_log_format_buffer_size:
1075 if (SemaBuiltinOSLogFormat(TheCall)) {
1076 return ExprError();
1077 }
1078 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001079 }
Richard Smith760520b2014-06-03 23:27:44 +00001080
Nate Begeman4904e322010-06-08 02:47:44 +00001081 // Since the target specific builtins for each arch overlap, only check those
1082 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001083 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001084 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001085 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001086 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001087 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001088 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001089 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1090 return ExprError();
1091 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001092 case llvm::Triple::aarch64:
1093 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001094 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001095 return ExprError();
1096 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001097 case llvm::Triple::mips:
1098 case llvm::Triple::mipsel:
1099 case llvm::Triple::mips64:
1100 case llvm::Triple::mips64el:
1101 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1102 return ExprError();
1103 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001104 case llvm::Triple::systemz:
1105 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1106 return ExprError();
1107 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001108 case llvm::Triple::x86:
1109 case llvm::Triple::x86_64:
1110 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1111 return ExprError();
1112 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001113 case llvm::Triple::ppc:
1114 case llvm::Triple::ppc64:
1115 case llvm::Triple::ppc64le:
1116 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1117 return ExprError();
1118 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001119 default:
1120 break;
1121 }
1122 }
1123
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001124 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001125}
1126
Nate Begeman91e1fea2010-06-14 05:21:25 +00001127// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001128static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001129 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001130 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001131 switch (Type.getEltType()) {
1132 case NeonTypeFlags::Int8:
1133 case NeonTypeFlags::Poly8:
1134 return shift ? 7 : (8 << IsQuad) - 1;
1135 case NeonTypeFlags::Int16:
1136 case NeonTypeFlags::Poly16:
1137 return shift ? 15 : (4 << IsQuad) - 1;
1138 case NeonTypeFlags::Int32:
1139 return shift ? 31 : (2 << IsQuad) - 1;
1140 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001141 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001142 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001143 case NeonTypeFlags::Poly128:
1144 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001145 case NeonTypeFlags::Float16:
1146 assert(!shift && "cannot shift float types!");
1147 return (4 << IsQuad) - 1;
1148 case NeonTypeFlags::Float32:
1149 assert(!shift && "cannot shift float types!");
1150 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001151 case NeonTypeFlags::Float64:
1152 assert(!shift && "cannot shift float types!");
1153 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001154 }
David Blaikie8a40f702012-01-17 06:56:22 +00001155 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001156}
1157
Bob Wilsone4d77232011-11-08 05:04:11 +00001158/// getNeonEltType - Return the QualType corresponding to the elements of
1159/// the vector type specified by the NeonTypeFlags. This is used to check
1160/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001161static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001162 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001163 switch (Flags.getEltType()) {
1164 case NeonTypeFlags::Int8:
1165 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1166 case NeonTypeFlags::Int16:
1167 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1168 case NeonTypeFlags::Int32:
1169 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1170 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001171 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001172 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1173 else
1174 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1175 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001176 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001177 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001178 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001179 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001180 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001181 if (IsInt64Long)
1182 return Context.UnsignedLongTy;
1183 else
1184 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001185 case NeonTypeFlags::Poly128:
1186 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001187 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001188 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001189 case NeonTypeFlags::Float32:
1190 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001191 case NeonTypeFlags::Float64:
1192 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001193 }
David Blaikie8a40f702012-01-17 06:56:22 +00001194 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001195}
1196
Tim Northover12670412014-02-19 10:37:05 +00001197bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001198 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001199 uint64_t mask = 0;
1200 unsigned TV = 0;
1201 int PtrArgNum = -1;
1202 bool HasConstPtr = false;
1203 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001204#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001205#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001206#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001207 }
1208
1209 // For NEON intrinsics which are overloaded on vector element type, validate
1210 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001211 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001212 if (mask) {
1213 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1214 return true;
1215
1216 TV = Result.getLimitedValue(64);
1217 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1218 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001219 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001220 }
1221
1222 if (PtrArgNum >= 0) {
1223 // Check that pointer arguments have the specified type.
1224 Expr *Arg = TheCall->getArg(PtrArgNum);
1225 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1226 Arg = ICE->getSubExpr();
1227 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1228 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001229
Tim Northovera2ee4332014-03-29 15:09:45 +00001230 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +00001231 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +00001232 bool IsInt64Long =
1233 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1234 QualType EltTy =
1235 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001236 if (HasConstPtr)
1237 EltTy = EltTy.withConst();
1238 QualType LHSTy = Context.getPointerType(EltTy);
1239 AssignConvertType ConvTy;
1240 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1241 if (RHS.isInvalid())
1242 return true;
1243 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1244 RHS.get(), AA_Assigning))
1245 return true;
1246 }
1247
1248 // For NEON intrinsics which take an immediate value as part of the
1249 // instruction, range check them here.
1250 unsigned i = 0, l = 0, u = 0;
1251 switch (BuiltinID) {
1252 default:
1253 return false;
Tim Northover12670412014-02-19 10:37:05 +00001254#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001255#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001256#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001257 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001258
Richard Sandiford28940af2014-04-16 08:47:51 +00001259 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001260}
1261
Tim Northovera2ee4332014-03-29 15:09:45 +00001262bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1263 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001264 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001265 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001266 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001267 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001268 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001269 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1270 BuiltinID == AArch64::BI__builtin_arm_strex ||
1271 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001272 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001273 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001274 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1275 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1276 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001277
1278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1279
1280 // Ensure that we have the proper number of arguments.
1281 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1282 return true;
1283
1284 // Inspect the pointer argument of the atomic builtin. This should always be
1285 // a pointer type, whose element is an integral scalar or pointer type.
1286 // Because it is a pointer type, we don't have to worry about any implicit
1287 // casts here.
1288 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1289 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1290 if (PointerArgRes.isInvalid())
1291 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001292 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001293
1294 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1295 if (!pointerType) {
1296 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1297 << PointerArg->getType() << PointerArg->getSourceRange();
1298 return true;
1299 }
1300
1301 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1302 // task is to insert the appropriate casts into the AST. First work out just
1303 // what the appropriate type is.
1304 QualType ValType = pointerType->getPointeeType();
1305 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1306 if (IsLdrex)
1307 AddrType.addConst();
1308
1309 // Issue a warning if the cast is dodgy.
1310 CastKind CastNeeded = CK_NoOp;
1311 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1312 CastNeeded = CK_BitCast;
1313 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1314 << PointerArg->getType()
1315 << Context.getPointerType(AddrType)
1316 << AA_Passing << PointerArg->getSourceRange();
1317 }
1318
1319 // Finally, do the cast and replace the argument with the corrected version.
1320 AddrType = Context.getPointerType(AddrType);
1321 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1322 if (PointerArgRes.isInvalid())
1323 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001324 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001325
1326 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1327
1328 // In general, we allow ints, floats and pointers to be loaded and stored.
1329 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1330 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1331 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1332 << PointerArg->getType() << PointerArg->getSourceRange();
1333 return true;
1334 }
1335
1336 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001337 if (Context.getTypeSize(ValType) > MaxWidth) {
1338 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001339 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1340 << PointerArg->getType() << PointerArg->getSourceRange();
1341 return true;
1342 }
1343
1344 switch (ValType.getObjCLifetime()) {
1345 case Qualifiers::OCL_None:
1346 case Qualifiers::OCL_ExplicitNone:
1347 // okay
1348 break;
1349
1350 case Qualifiers::OCL_Weak:
1351 case Qualifiers::OCL_Strong:
1352 case Qualifiers::OCL_Autoreleasing:
1353 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1354 << ValType << PointerArg->getSourceRange();
1355 return true;
1356 }
1357
Tim Northover6aacd492013-07-16 09:47:53 +00001358 if (IsLdrex) {
1359 TheCall->setType(ValType);
1360 return false;
1361 }
1362
1363 // Initialize the argument to be stored.
1364 ExprResult ValArg = TheCall->getArg(0);
1365 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1366 Context, ValType, /*consume*/ false);
1367 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1368 if (ValArg.isInvalid())
1369 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001370 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001371
1372 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1373 // but the custom checker bypasses all default analysis.
1374 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001375 return false;
1376}
1377
Nate Begeman4904e322010-06-08 02:47:44 +00001378bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001379 llvm::APSInt Result;
1380
Tim Northover6aacd492013-07-16 09:47:53 +00001381 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001382 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1383 BuiltinID == ARM::BI__builtin_arm_strex ||
1384 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001385 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001386 }
1387
Yi Kong26d104a2014-08-13 19:18:14 +00001388 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1389 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1390 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1391 }
1392
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001393 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1394 BuiltinID == ARM::BI__builtin_arm_wsr64)
1395 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1396
1397 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1398 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1399 BuiltinID == ARM::BI__builtin_arm_wsr ||
1400 BuiltinID == ARM::BI__builtin_arm_wsrp)
1401 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1402
Tim Northover12670412014-02-19 10:37:05 +00001403 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1404 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001405
Yi Kong4efadfb2014-07-03 16:01:25 +00001406 // For intrinsics which take an immediate value as part of the instruction,
1407 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001408 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001409 switch (BuiltinID) {
1410 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001411 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1412 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001413 case ARM::BI__builtin_arm_vcvtr_f:
1414 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001415 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001416 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001417 case ARM::BI__builtin_arm_isb:
1418 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001419 }
Nate Begemand773fe62010-06-13 04:47:52 +00001420
Nate Begemanf568b072010-08-03 21:32:34 +00001421 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001422 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001423}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001424
Tim Northover573cbee2014-05-24 12:52:07 +00001425bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001426 CallExpr *TheCall) {
1427 llvm::APSInt Result;
1428
Tim Northover573cbee2014-05-24 12:52:07 +00001429 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001430 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1431 BuiltinID == AArch64::BI__builtin_arm_strex ||
1432 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001433 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1434 }
1435
Yi Konga5548432014-08-13 19:18:20 +00001436 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1437 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1438 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1439 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1440 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1441 }
1442
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001443 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1444 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001445 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001446
1447 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1448 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1449 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1450 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1451 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1452
Tim Northovera2ee4332014-03-29 15:09:45 +00001453 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1454 return true;
1455
Yi Kong19a29ac2014-07-17 10:52:06 +00001456 // For intrinsics which take an immediate value as part of the instruction,
1457 // range check them here.
1458 unsigned i = 0, l = 0, u = 0;
1459 switch (BuiltinID) {
1460 default: return false;
1461 case AArch64::BI__builtin_arm_dmb:
1462 case AArch64::BI__builtin_arm_dsb:
1463 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1464 }
1465
Yi Kong19a29ac2014-07-17 10:52:06 +00001466 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001467}
1468
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001469// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1470// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1471// ordering for DSP is unspecified. MSA is ordered by the data format used
1472// by the underlying instruction i.e., df/m, df/n and then by size.
1473//
1474// FIXME: The size tests here should instead be tablegen'd along with the
1475// definitions from include/clang/Basic/BuiltinsMips.def.
1476// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1477// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001478bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001479 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001480 switch (BuiltinID) {
1481 default: return false;
1482 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1483 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001484 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1485 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1486 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1487 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1488 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001489 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1490 // df/m field.
1491 // These intrinsics take an unsigned 3 bit immediate.
1492 case Mips::BI__builtin_msa_bclri_b:
1493 case Mips::BI__builtin_msa_bnegi_b:
1494 case Mips::BI__builtin_msa_bseti_b:
1495 case Mips::BI__builtin_msa_sat_s_b:
1496 case Mips::BI__builtin_msa_sat_u_b:
1497 case Mips::BI__builtin_msa_slli_b:
1498 case Mips::BI__builtin_msa_srai_b:
1499 case Mips::BI__builtin_msa_srari_b:
1500 case Mips::BI__builtin_msa_srli_b:
1501 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1502 case Mips::BI__builtin_msa_binsli_b:
1503 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1504 // These intrinsics take an unsigned 4 bit immediate.
1505 case Mips::BI__builtin_msa_bclri_h:
1506 case Mips::BI__builtin_msa_bnegi_h:
1507 case Mips::BI__builtin_msa_bseti_h:
1508 case Mips::BI__builtin_msa_sat_s_h:
1509 case Mips::BI__builtin_msa_sat_u_h:
1510 case Mips::BI__builtin_msa_slli_h:
1511 case Mips::BI__builtin_msa_srai_h:
1512 case Mips::BI__builtin_msa_srari_h:
1513 case Mips::BI__builtin_msa_srli_h:
1514 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1515 case Mips::BI__builtin_msa_binsli_h:
1516 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1517 // These intrinsics take an unsigned 5 bit immedate.
1518 // The first block of intrinsics actually have an unsigned 5 bit field,
1519 // not a df/n field.
1520 case Mips::BI__builtin_msa_clei_u_b:
1521 case Mips::BI__builtin_msa_clei_u_h:
1522 case Mips::BI__builtin_msa_clei_u_w:
1523 case Mips::BI__builtin_msa_clei_u_d:
1524 case Mips::BI__builtin_msa_clti_u_b:
1525 case Mips::BI__builtin_msa_clti_u_h:
1526 case Mips::BI__builtin_msa_clti_u_w:
1527 case Mips::BI__builtin_msa_clti_u_d:
1528 case Mips::BI__builtin_msa_maxi_u_b:
1529 case Mips::BI__builtin_msa_maxi_u_h:
1530 case Mips::BI__builtin_msa_maxi_u_w:
1531 case Mips::BI__builtin_msa_maxi_u_d:
1532 case Mips::BI__builtin_msa_mini_u_b:
1533 case Mips::BI__builtin_msa_mini_u_h:
1534 case Mips::BI__builtin_msa_mini_u_w:
1535 case Mips::BI__builtin_msa_mini_u_d:
1536 case Mips::BI__builtin_msa_addvi_b:
1537 case Mips::BI__builtin_msa_addvi_h:
1538 case Mips::BI__builtin_msa_addvi_w:
1539 case Mips::BI__builtin_msa_addvi_d:
1540 case Mips::BI__builtin_msa_bclri_w:
1541 case Mips::BI__builtin_msa_bnegi_w:
1542 case Mips::BI__builtin_msa_bseti_w:
1543 case Mips::BI__builtin_msa_sat_s_w:
1544 case Mips::BI__builtin_msa_sat_u_w:
1545 case Mips::BI__builtin_msa_slli_w:
1546 case Mips::BI__builtin_msa_srai_w:
1547 case Mips::BI__builtin_msa_srari_w:
1548 case Mips::BI__builtin_msa_srli_w:
1549 case Mips::BI__builtin_msa_srlri_w:
1550 case Mips::BI__builtin_msa_subvi_b:
1551 case Mips::BI__builtin_msa_subvi_h:
1552 case Mips::BI__builtin_msa_subvi_w:
1553 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1554 case Mips::BI__builtin_msa_binsli_w:
1555 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1556 // These intrinsics take an unsigned 6 bit immediate.
1557 case Mips::BI__builtin_msa_bclri_d:
1558 case Mips::BI__builtin_msa_bnegi_d:
1559 case Mips::BI__builtin_msa_bseti_d:
1560 case Mips::BI__builtin_msa_sat_s_d:
1561 case Mips::BI__builtin_msa_sat_u_d:
1562 case Mips::BI__builtin_msa_slli_d:
1563 case Mips::BI__builtin_msa_srai_d:
1564 case Mips::BI__builtin_msa_srari_d:
1565 case Mips::BI__builtin_msa_srli_d:
1566 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1567 case Mips::BI__builtin_msa_binsli_d:
1568 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1569 // These intrinsics take a signed 5 bit immediate.
1570 case Mips::BI__builtin_msa_ceqi_b:
1571 case Mips::BI__builtin_msa_ceqi_h:
1572 case Mips::BI__builtin_msa_ceqi_w:
1573 case Mips::BI__builtin_msa_ceqi_d:
1574 case Mips::BI__builtin_msa_clti_s_b:
1575 case Mips::BI__builtin_msa_clti_s_h:
1576 case Mips::BI__builtin_msa_clti_s_w:
1577 case Mips::BI__builtin_msa_clti_s_d:
1578 case Mips::BI__builtin_msa_clei_s_b:
1579 case Mips::BI__builtin_msa_clei_s_h:
1580 case Mips::BI__builtin_msa_clei_s_w:
1581 case Mips::BI__builtin_msa_clei_s_d:
1582 case Mips::BI__builtin_msa_maxi_s_b:
1583 case Mips::BI__builtin_msa_maxi_s_h:
1584 case Mips::BI__builtin_msa_maxi_s_w:
1585 case Mips::BI__builtin_msa_maxi_s_d:
1586 case Mips::BI__builtin_msa_mini_s_b:
1587 case Mips::BI__builtin_msa_mini_s_h:
1588 case Mips::BI__builtin_msa_mini_s_w:
1589 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1590 // These intrinsics take an unsigned 8 bit immediate.
1591 case Mips::BI__builtin_msa_andi_b:
1592 case Mips::BI__builtin_msa_nori_b:
1593 case Mips::BI__builtin_msa_ori_b:
1594 case Mips::BI__builtin_msa_shf_b:
1595 case Mips::BI__builtin_msa_shf_h:
1596 case Mips::BI__builtin_msa_shf_w:
1597 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1598 case Mips::BI__builtin_msa_bseli_b:
1599 case Mips::BI__builtin_msa_bmnzi_b:
1600 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1601 // df/n format
1602 // These intrinsics take an unsigned 4 bit immediate.
1603 case Mips::BI__builtin_msa_copy_s_b:
1604 case Mips::BI__builtin_msa_copy_u_b:
1605 case Mips::BI__builtin_msa_insve_b:
1606 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1607 case Mips::BI__builtin_msa_sld_b:
1608 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1609 // These intrinsics take an unsigned 3 bit immediate.
1610 case Mips::BI__builtin_msa_copy_s_h:
1611 case Mips::BI__builtin_msa_copy_u_h:
1612 case Mips::BI__builtin_msa_insve_h:
1613 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1614 case Mips::BI__builtin_msa_sld_h:
1615 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1616 // These intrinsics take an unsigned 2 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_w:
1618 case Mips::BI__builtin_msa_copy_u_w:
1619 case Mips::BI__builtin_msa_insve_w:
1620 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1621 case Mips::BI__builtin_msa_sld_w:
1622 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1623 // These intrinsics take an unsigned 1 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_d:
1625 case Mips::BI__builtin_msa_copy_u_d:
1626 case Mips::BI__builtin_msa_insve_d:
1627 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1628 case Mips::BI__builtin_msa_sld_d:
1629 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1630 // Memory offsets and immediate loads.
1631 // These intrinsics take a signed 10 bit immediate.
1632 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 127; break;
1633 case Mips::BI__builtin_msa_ldi_h:
1634 case Mips::BI__builtin_msa_ldi_w:
1635 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1636 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1637 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1638 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1639 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1640 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1641 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1642 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1643 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001644 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001645
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001646 if (!m)
1647 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1648
1649 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1650 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001651}
1652
Kit Bartone50adcb2015-03-30 19:40:59 +00001653bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1654 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001655 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1656 BuiltinID == PPC::BI__builtin_divdeu ||
1657 BuiltinID == PPC::BI__builtin_bpermd;
1658 bool IsTarget64Bit = Context.getTargetInfo()
1659 .getTypeWidth(Context
1660 .getTargetInfo()
1661 .getIntPtrType()) == 64;
1662 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1663 BuiltinID == PPC::BI__builtin_divweu ||
1664 BuiltinID == PPC::BI__builtin_divde ||
1665 BuiltinID == PPC::BI__builtin_divdeu;
1666
1667 if (Is64BitBltin && !IsTarget64Bit)
1668 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1669 << TheCall->getSourceRange();
1670
1671 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1672 (BuiltinID == PPC::BI__builtin_bpermd &&
1673 !Context.getTargetInfo().hasFeature("bpermd")))
1674 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1675 << TheCall->getSourceRange();
1676
Kit Bartone50adcb2015-03-30 19:40:59 +00001677 switch (BuiltinID) {
1678 default: return false;
1679 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1680 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1681 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1682 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1683 case PPC::BI__builtin_tbegin:
1684 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1685 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1686 case PPC::BI__builtin_tabortwc:
1687 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1688 case PPC::BI__builtin_tabortwci:
1689 case PPC::BI__builtin_tabortdci:
1690 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1691 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1692 }
1693 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1694}
1695
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001696bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1697 CallExpr *TheCall) {
1698 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1699 Expr *Arg = TheCall->getArg(0);
1700 llvm::APSInt AbortCode(32);
1701 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1702 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1703 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1704 << Arg->getSourceRange();
1705 }
1706
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001707 // For intrinsics which take an immediate value as part of the instruction,
1708 // range check them here.
1709 unsigned i = 0, l = 0, u = 0;
1710 switch (BuiltinID) {
1711 default: return false;
1712 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1713 case SystemZ::BI__builtin_s390_verimb:
1714 case SystemZ::BI__builtin_s390_verimh:
1715 case SystemZ::BI__builtin_s390_verimf:
1716 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1717 case SystemZ::BI__builtin_s390_vfaeb:
1718 case SystemZ::BI__builtin_s390_vfaeh:
1719 case SystemZ::BI__builtin_s390_vfaef:
1720 case SystemZ::BI__builtin_s390_vfaebs:
1721 case SystemZ::BI__builtin_s390_vfaehs:
1722 case SystemZ::BI__builtin_s390_vfaefs:
1723 case SystemZ::BI__builtin_s390_vfaezb:
1724 case SystemZ::BI__builtin_s390_vfaezh:
1725 case SystemZ::BI__builtin_s390_vfaezf:
1726 case SystemZ::BI__builtin_s390_vfaezbs:
1727 case SystemZ::BI__builtin_s390_vfaezhs:
1728 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1729 case SystemZ::BI__builtin_s390_vfidb:
1730 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1731 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1732 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1733 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1734 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1735 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1736 case SystemZ::BI__builtin_s390_vstrcb:
1737 case SystemZ::BI__builtin_s390_vstrch:
1738 case SystemZ::BI__builtin_s390_vstrcf:
1739 case SystemZ::BI__builtin_s390_vstrczb:
1740 case SystemZ::BI__builtin_s390_vstrczh:
1741 case SystemZ::BI__builtin_s390_vstrczf:
1742 case SystemZ::BI__builtin_s390_vstrcbs:
1743 case SystemZ::BI__builtin_s390_vstrchs:
1744 case SystemZ::BI__builtin_s390_vstrcfs:
1745 case SystemZ::BI__builtin_s390_vstrczbs:
1746 case SystemZ::BI__builtin_s390_vstrczhs:
1747 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1748 }
1749 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001750}
1751
Craig Topper5ba2c502015-11-07 08:08:31 +00001752/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1753/// This checks that the target supports __builtin_cpu_supports and
1754/// that the string argument is constant and valid.
1755static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1756 Expr *Arg = TheCall->getArg(0);
1757
1758 // Check if the argument is a string literal.
1759 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1760 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1761 << Arg->getSourceRange();
1762
1763 // Check the contents of the string.
1764 StringRef Feature =
1765 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1766 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1767 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1768 << Arg->getSourceRange();
1769 return false;
1770}
1771
Craig Toppera7e253e2016-09-23 04:48:31 +00001772// Check if the rounding mode is legal.
1773bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1774 // Indicates if this instruction has rounding control or just SAE.
1775 bool HasRC = false;
1776
1777 unsigned ArgNum = 0;
1778 switch (BuiltinID) {
1779 default:
1780 return false;
1781 case X86::BI__builtin_ia32_vcvttsd2si32:
1782 case X86::BI__builtin_ia32_vcvttsd2si64:
1783 case X86::BI__builtin_ia32_vcvttsd2usi32:
1784 case X86::BI__builtin_ia32_vcvttsd2usi64:
1785 case X86::BI__builtin_ia32_vcvttss2si32:
1786 case X86::BI__builtin_ia32_vcvttss2si64:
1787 case X86::BI__builtin_ia32_vcvttss2usi32:
1788 case X86::BI__builtin_ia32_vcvttss2usi64:
1789 ArgNum = 1;
1790 break;
1791 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1792 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1793 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1794 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1795 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1796 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1797 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1798 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1799 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1800 case X86::BI__builtin_ia32_exp2pd_mask:
1801 case X86::BI__builtin_ia32_exp2ps_mask:
1802 case X86::BI__builtin_ia32_getexppd512_mask:
1803 case X86::BI__builtin_ia32_getexpps512_mask:
1804 case X86::BI__builtin_ia32_rcp28pd_mask:
1805 case X86::BI__builtin_ia32_rcp28ps_mask:
1806 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1807 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1808 case X86::BI__builtin_ia32_vcomisd:
1809 case X86::BI__builtin_ia32_vcomiss:
1810 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1811 ArgNum = 3;
1812 break;
1813 case X86::BI__builtin_ia32_cmppd512_mask:
1814 case X86::BI__builtin_ia32_cmpps512_mask:
1815 case X86::BI__builtin_ia32_cmpsd_mask:
1816 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001817 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001818 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1819 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001820 case X86::BI__builtin_ia32_maxpd512_mask:
1821 case X86::BI__builtin_ia32_maxps512_mask:
1822 case X86::BI__builtin_ia32_maxsd_round_mask:
1823 case X86::BI__builtin_ia32_maxss_round_mask:
1824 case X86::BI__builtin_ia32_minpd512_mask:
1825 case X86::BI__builtin_ia32_minps512_mask:
1826 case X86::BI__builtin_ia32_minsd_round_mask:
1827 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001828 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1829 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1830 case X86::BI__builtin_ia32_reducepd512_mask:
1831 case X86::BI__builtin_ia32_reduceps512_mask:
1832 case X86::BI__builtin_ia32_rndscalepd_mask:
1833 case X86::BI__builtin_ia32_rndscaleps_mask:
1834 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1835 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1836 ArgNum = 4;
1837 break;
1838 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001839 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001840 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001841 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001842 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001843 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001844 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001845 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001846 case X86::BI__builtin_ia32_rangepd512_mask:
1847 case X86::BI__builtin_ia32_rangeps512_mask:
1848 case X86::BI__builtin_ia32_rangesd128_round_mask:
1849 case X86::BI__builtin_ia32_rangess128_round_mask:
1850 case X86::BI__builtin_ia32_reducesd_mask:
1851 case X86::BI__builtin_ia32_reducess_mask:
1852 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1853 case X86::BI__builtin_ia32_rndscaless_round_mask:
1854 ArgNum = 5;
1855 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_vcvtsd2si64:
1857 case X86::BI__builtin_ia32_vcvtsd2si32:
1858 case X86::BI__builtin_ia32_vcvtsd2usi32:
1859 case X86::BI__builtin_ia32_vcvtsd2usi64:
1860 case X86::BI__builtin_ia32_vcvtss2si32:
1861 case X86::BI__builtin_ia32_vcvtss2si64:
1862 case X86::BI__builtin_ia32_vcvtss2usi32:
1863 case X86::BI__builtin_ia32_vcvtss2usi64:
1864 ArgNum = 1;
1865 HasRC = true;
1866 break;
Craig Topper8e066312016-11-07 07:01:09 +00001867 case X86::BI__builtin_ia32_cvtsi2sd64:
1868 case X86::BI__builtin_ia32_cvtsi2ss32:
1869 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001870 case X86::BI__builtin_ia32_cvtusi2sd64:
1871 case X86::BI__builtin_ia32_cvtusi2ss32:
1872 case X86::BI__builtin_ia32_cvtusi2ss64:
1873 ArgNum = 2;
1874 HasRC = true;
1875 break;
1876 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1877 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1878 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1879 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1880 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1881 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1882 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1883 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1884 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1885 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1886 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001887 case X86::BI__builtin_ia32_sqrtpd512_mask:
1888 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001889 ArgNum = 3;
1890 HasRC = true;
1891 break;
1892 case X86::BI__builtin_ia32_addpd512_mask:
1893 case X86::BI__builtin_ia32_addps512_mask:
1894 case X86::BI__builtin_ia32_divpd512_mask:
1895 case X86::BI__builtin_ia32_divps512_mask:
1896 case X86::BI__builtin_ia32_mulpd512_mask:
1897 case X86::BI__builtin_ia32_mulps512_mask:
1898 case X86::BI__builtin_ia32_subpd512_mask:
1899 case X86::BI__builtin_ia32_subps512_mask:
1900 case X86::BI__builtin_ia32_addss_round_mask:
1901 case X86::BI__builtin_ia32_addsd_round_mask:
1902 case X86::BI__builtin_ia32_divss_round_mask:
1903 case X86::BI__builtin_ia32_divsd_round_mask:
1904 case X86::BI__builtin_ia32_mulss_round_mask:
1905 case X86::BI__builtin_ia32_mulsd_round_mask:
1906 case X86::BI__builtin_ia32_subss_round_mask:
1907 case X86::BI__builtin_ia32_subsd_round_mask:
1908 case X86::BI__builtin_ia32_scalefpd512_mask:
1909 case X86::BI__builtin_ia32_scalefps512_mask:
1910 case X86::BI__builtin_ia32_scalefsd_round_mask:
1911 case X86::BI__builtin_ia32_scalefss_round_mask:
1912 case X86::BI__builtin_ia32_getmantpd512_mask:
1913 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001914 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1915 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1916 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001917 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1918 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1919 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1920 case X86::BI__builtin_ia32_vfmaddps512_mask:
1921 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1922 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1923 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1924 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1925 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1926 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1927 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1928 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1929 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1930 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1931 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1932 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1933 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1934 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1935 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1936 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1937 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1938 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1939 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1940 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1941 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1942 case X86::BI__builtin_ia32_vfmaddss3_mask:
1943 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1944 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1945 ArgNum = 4;
1946 HasRC = true;
1947 break;
1948 case X86::BI__builtin_ia32_getmantsd_round_mask:
1949 case X86::BI__builtin_ia32_getmantss_round_mask:
1950 ArgNum = 5;
1951 HasRC = true;
1952 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001953 }
1954
1955 llvm::APSInt Result;
1956
1957 // We can't check the value of a dependent argument.
1958 Expr *Arg = TheCall->getArg(ArgNum);
1959 if (Arg->isTypeDependent() || Arg->isValueDependent())
1960 return false;
1961
1962 // Check constant-ness first.
1963 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1964 return true;
1965
1966 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1967 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1968 // combined with ROUND_NO_EXC.
1969 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1970 Result == 8/*ROUND_NO_EXC*/ ||
1971 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1972 return false;
1973
1974 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1975 << Arg->getSourceRange();
1976}
1977
Craig Topperf0ddc892016-09-23 04:48:27 +00001978bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1979 if (BuiltinID == X86::BI__builtin_cpu_supports)
1980 return SemaBuiltinCpuSupports(*this, TheCall);
1981
1982 if (BuiltinID == X86::BI__builtin_ms_va_start)
1983 return SemaBuiltinMSVAStart(TheCall);
1984
Craig Toppera7e253e2016-09-23 04:48:31 +00001985 // If the intrinsic has rounding or SAE make sure its valid.
1986 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1987 return true;
1988
Craig Topperf0ddc892016-09-23 04:48:27 +00001989 // For intrinsics which take an immediate value as part of the instruction,
1990 // range check them here.
1991 int i = 0, l = 0, u = 0;
1992 switch (BuiltinID) {
1993 default:
1994 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00001995 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00001996 i = 1; l = 0; u = 3;
1997 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00001998 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00001999 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2000 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2001 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2002 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002003 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002004 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002005 case X86::BI__builtin_ia32_vpermil2pd:
2006 case X86::BI__builtin_ia32_vpermil2pd256:
2007 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002008 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002009 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002010 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002011 case X86::BI__builtin_ia32_cmpb128_mask:
2012 case X86::BI__builtin_ia32_cmpw128_mask:
2013 case X86::BI__builtin_ia32_cmpd128_mask:
2014 case X86::BI__builtin_ia32_cmpq128_mask:
2015 case X86::BI__builtin_ia32_cmpb256_mask:
2016 case X86::BI__builtin_ia32_cmpw256_mask:
2017 case X86::BI__builtin_ia32_cmpd256_mask:
2018 case X86::BI__builtin_ia32_cmpq256_mask:
2019 case X86::BI__builtin_ia32_cmpb512_mask:
2020 case X86::BI__builtin_ia32_cmpw512_mask:
2021 case X86::BI__builtin_ia32_cmpd512_mask:
2022 case X86::BI__builtin_ia32_cmpq512_mask:
2023 case X86::BI__builtin_ia32_ucmpb128_mask:
2024 case X86::BI__builtin_ia32_ucmpw128_mask:
2025 case X86::BI__builtin_ia32_ucmpd128_mask:
2026 case X86::BI__builtin_ia32_ucmpq128_mask:
2027 case X86::BI__builtin_ia32_ucmpb256_mask:
2028 case X86::BI__builtin_ia32_ucmpw256_mask:
2029 case X86::BI__builtin_ia32_ucmpd256_mask:
2030 case X86::BI__builtin_ia32_ucmpq256_mask:
2031 case X86::BI__builtin_ia32_ucmpb512_mask:
2032 case X86::BI__builtin_ia32_ucmpw512_mask:
2033 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002034 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002035 case X86::BI__builtin_ia32_vpcomub:
2036 case X86::BI__builtin_ia32_vpcomuw:
2037 case X86::BI__builtin_ia32_vpcomud:
2038 case X86::BI__builtin_ia32_vpcomuq:
2039 case X86::BI__builtin_ia32_vpcomb:
2040 case X86::BI__builtin_ia32_vpcomw:
2041 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002042 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002043 i = 2; l = 0; u = 7;
2044 break;
2045 case X86::BI__builtin_ia32_roundps:
2046 case X86::BI__builtin_ia32_roundpd:
2047 case X86::BI__builtin_ia32_roundps256:
2048 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002049 i = 1; l = 0; u = 15;
2050 break;
2051 case X86::BI__builtin_ia32_roundss:
2052 case X86::BI__builtin_ia32_roundsd:
2053 case X86::BI__builtin_ia32_rangepd128_mask:
2054 case X86::BI__builtin_ia32_rangepd256_mask:
2055 case X86::BI__builtin_ia32_rangepd512_mask:
2056 case X86::BI__builtin_ia32_rangeps128_mask:
2057 case X86::BI__builtin_ia32_rangeps256_mask:
2058 case X86::BI__builtin_ia32_rangeps512_mask:
2059 case X86::BI__builtin_ia32_getmantsd_round_mask:
2060 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002061 i = 2; l = 0; u = 15;
2062 break;
2063 case X86::BI__builtin_ia32_cmpps:
2064 case X86::BI__builtin_ia32_cmpss:
2065 case X86::BI__builtin_ia32_cmppd:
2066 case X86::BI__builtin_ia32_cmpsd:
2067 case X86::BI__builtin_ia32_cmpps256:
2068 case X86::BI__builtin_ia32_cmppd256:
2069 case X86::BI__builtin_ia32_cmpps128_mask:
2070 case X86::BI__builtin_ia32_cmppd128_mask:
2071 case X86::BI__builtin_ia32_cmpps256_mask:
2072 case X86::BI__builtin_ia32_cmppd256_mask:
2073 case X86::BI__builtin_ia32_cmpps512_mask:
2074 case X86::BI__builtin_ia32_cmppd512_mask:
2075 case X86::BI__builtin_ia32_cmpsd_mask:
2076 case X86::BI__builtin_ia32_cmpss_mask:
2077 i = 2; l = 0; u = 31;
2078 break;
2079 case X86::BI__builtin_ia32_xabort:
2080 i = 0; l = -128; u = 255;
2081 break;
2082 case X86::BI__builtin_ia32_pshufw:
2083 case X86::BI__builtin_ia32_aeskeygenassist128:
2084 i = 1; l = -128; u = 255;
2085 break;
2086 case X86::BI__builtin_ia32_vcvtps2ph:
2087 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002088 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2089 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2090 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2091 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2092 case X86::BI__builtin_ia32_rndscaleps_mask:
2093 case X86::BI__builtin_ia32_rndscalepd_mask:
2094 case X86::BI__builtin_ia32_reducepd128_mask:
2095 case X86::BI__builtin_ia32_reducepd256_mask:
2096 case X86::BI__builtin_ia32_reducepd512_mask:
2097 case X86::BI__builtin_ia32_reduceps128_mask:
2098 case X86::BI__builtin_ia32_reduceps256_mask:
2099 case X86::BI__builtin_ia32_reduceps512_mask:
2100 case X86::BI__builtin_ia32_prold512_mask:
2101 case X86::BI__builtin_ia32_prolq512_mask:
2102 case X86::BI__builtin_ia32_prold128_mask:
2103 case X86::BI__builtin_ia32_prold256_mask:
2104 case X86::BI__builtin_ia32_prolq128_mask:
2105 case X86::BI__builtin_ia32_prolq256_mask:
2106 case X86::BI__builtin_ia32_prord128_mask:
2107 case X86::BI__builtin_ia32_prord256_mask:
2108 case X86::BI__builtin_ia32_prorq128_mask:
2109 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002110 case X86::BI__builtin_ia32_fpclasspd128_mask:
2111 case X86::BI__builtin_ia32_fpclasspd256_mask:
2112 case X86::BI__builtin_ia32_fpclassps128_mask:
2113 case X86::BI__builtin_ia32_fpclassps256_mask:
2114 case X86::BI__builtin_ia32_fpclassps512_mask:
2115 case X86::BI__builtin_ia32_fpclasspd512_mask:
2116 case X86::BI__builtin_ia32_fpclasssd_mask:
2117 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002118 i = 1; l = 0; u = 255;
2119 break;
2120 case X86::BI__builtin_ia32_palignr:
2121 case X86::BI__builtin_ia32_insertps128:
2122 case X86::BI__builtin_ia32_dpps:
2123 case X86::BI__builtin_ia32_dppd:
2124 case X86::BI__builtin_ia32_dpps256:
2125 case X86::BI__builtin_ia32_mpsadbw128:
2126 case X86::BI__builtin_ia32_mpsadbw256:
2127 case X86::BI__builtin_ia32_pcmpistrm128:
2128 case X86::BI__builtin_ia32_pcmpistri128:
2129 case X86::BI__builtin_ia32_pcmpistria128:
2130 case X86::BI__builtin_ia32_pcmpistric128:
2131 case X86::BI__builtin_ia32_pcmpistrio128:
2132 case X86::BI__builtin_ia32_pcmpistris128:
2133 case X86::BI__builtin_ia32_pcmpistriz128:
2134 case X86::BI__builtin_ia32_pclmulqdq128:
2135 case X86::BI__builtin_ia32_vperm2f128_pd256:
2136 case X86::BI__builtin_ia32_vperm2f128_ps256:
2137 case X86::BI__builtin_ia32_vperm2f128_si256:
2138 case X86::BI__builtin_ia32_permti256:
2139 i = 2; l = -128; u = 255;
2140 break;
2141 case X86::BI__builtin_ia32_palignr128:
2142 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002143 case X86::BI__builtin_ia32_palignr512_mask:
2144 case X86::BI__builtin_ia32_alignq512_mask:
2145 case X86::BI__builtin_ia32_alignd512_mask:
2146 case X86::BI__builtin_ia32_alignd128_mask:
2147 case X86::BI__builtin_ia32_alignd256_mask:
2148 case X86::BI__builtin_ia32_alignq128_mask:
2149 case X86::BI__builtin_ia32_alignq256_mask:
2150 case X86::BI__builtin_ia32_vcomisd:
2151 case X86::BI__builtin_ia32_vcomiss:
2152 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2153 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2154 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2155 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002156 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2157 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2158 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2159 i = 2; l = 0; u = 255;
2160 break;
2161 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2162 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2163 case X86::BI__builtin_ia32_fixupimmps512_mask:
2164 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2165 case X86::BI__builtin_ia32_fixupimmsd_mask:
2166 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2167 case X86::BI__builtin_ia32_fixupimmss_mask:
2168 case X86::BI__builtin_ia32_fixupimmss_maskz:
2169 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2170 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2171 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2172 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2173 case X86::BI__builtin_ia32_fixupimmps128_mask:
2174 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2175 case X86::BI__builtin_ia32_fixupimmps256_mask:
2176 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2177 case X86::BI__builtin_ia32_pternlogd512_mask:
2178 case X86::BI__builtin_ia32_pternlogd512_maskz:
2179 case X86::BI__builtin_ia32_pternlogq512_mask:
2180 case X86::BI__builtin_ia32_pternlogq512_maskz:
2181 case X86::BI__builtin_ia32_pternlogd128_mask:
2182 case X86::BI__builtin_ia32_pternlogd128_maskz:
2183 case X86::BI__builtin_ia32_pternlogd256_mask:
2184 case X86::BI__builtin_ia32_pternlogd256_maskz:
2185 case X86::BI__builtin_ia32_pternlogq128_mask:
2186 case X86::BI__builtin_ia32_pternlogq128_maskz:
2187 case X86::BI__builtin_ia32_pternlogq256_mask:
2188 case X86::BI__builtin_ia32_pternlogq256_maskz:
2189 i = 3; l = 0; u = 255;
2190 break;
2191 case X86::BI__builtin_ia32_pcmpestrm128:
2192 case X86::BI__builtin_ia32_pcmpestri128:
2193 case X86::BI__builtin_ia32_pcmpestria128:
2194 case X86::BI__builtin_ia32_pcmpestric128:
2195 case X86::BI__builtin_ia32_pcmpestrio128:
2196 case X86::BI__builtin_ia32_pcmpestris128:
2197 case X86::BI__builtin_ia32_pcmpestriz128:
2198 i = 4; l = -128; u = 255;
2199 break;
2200 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2201 case X86::BI__builtin_ia32_rndscaless_round_mask:
2202 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002203 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002204 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002205 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002206}
2207
Richard Smith55ce3522012-06-25 20:30:08 +00002208/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2209/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2210/// Returns true when the format fits the function and the FormatStringInfo has
2211/// been populated.
2212bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2213 FormatStringInfo *FSI) {
2214 FSI->HasVAListArg = Format->getFirstArg() == 0;
2215 FSI->FormatIdx = Format->getFormatIdx() - 1;
2216 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002217
Richard Smith55ce3522012-06-25 20:30:08 +00002218 // The way the format attribute works in GCC, the implicit this argument
2219 // of member functions is counted. However, it doesn't appear in our own
2220 // lists, so decrement format_idx in that case.
2221 if (IsCXXMember) {
2222 if(FSI->FormatIdx == 0)
2223 return false;
2224 --FSI->FormatIdx;
2225 if (FSI->FirstDataArg != 0)
2226 --FSI->FirstDataArg;
2227 }
2228 return true;
2229}
Mike Stump11289f42009-09-09 15:08:12 +00002230
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002231/// Checks if a the given expression evaluates to null.
2232///
2233/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002234static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002235 // If the expression has non-null type, it doesn't evaluate to null.
2236 if (auto nullability
2237 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2238 if (*nullability == NullabilityKind::NonNull)
2239 return false;
2240 }
2241
Ted Kremeneka146db32014-01-17 06:24:47 +00002242 // As a special case, transparent unions initialized with zero are
2243 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002244 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002245 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2246 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002247 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002248 if (const InitListExpr *ILE =
2249 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002250 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002251 }
2252
2253 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002254 return (!Expr->isValueDependent() &&
2255 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2256 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002257}
2258
2259static void CheckNonNullArgument(Sema &S,
2260 const Expr *ArgExpr,
2261 SourceLocation CallSiteLoc) {
2262 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002263 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2264 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002265}
2266
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002267bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2268 FormatStringInfo FSI;
2269 if ((GetFormatStringType(Format) == FST_NSString) &&
2270 getFormatStringInfo(Format, false, &FSI)) {
2271 Idx = FSI.FormatIdx;
2272 return true;
2273 }
2274 return false;
2275}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002276/// \brief Diagnose use of %s directive in an NSString which is being passed
2277/// as formatting string to formatting method.
2278static void
2279DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2280 const NamedDecl *FDecl,
2281 Expr **Args,
2282 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002283 unsigned Idx = 0;
2284 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002285 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2286 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002287 Idx = 2;
2288 Format = true;
2289 }
2290 else
2291 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2292 if (S.GetFormatNSStringIdx(I, Idx)) {
2293 Format = true;
2294 break;
2295 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002296 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002297 if (!Format || NumArgs <= Idx)
2298 return;
2299 const Expr *FormatExpr = Args[Idx];
2300 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2301 FormatExpr = CSCE->getSubExpr();
2302 const StringLiteral *FormatString;
2303 if (const ObjCStringLiteral *OSL =
2304 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2305 FormatString = OSL->getString();
2306 else
2307 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2308 if (!FormatString)
2309 return;
2310 if (S.FormatStringHasSArg(FormatString)) {
2311 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2312 << "%s" << 1 << 1;
2313 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2314 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002315 }
2316}
2317
Douglas Gregorb4866e82015-06-19 18:13:19 +00002318/// Determine whether the given type has a non-null nullability annotation.
2319static bool isNonNullType(ASTContext &ctx, QualType type) {
2320 if (auto nullability = type->getNullability(ctx))
2321 return *nullability == NullabilityKind::NonNull;
2322
2323 return false;
2324}
2325
Ted Kremenek2bc73332014-01-17 06:24:43 +00002326static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002327 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002328 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002329 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002330 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002331 assert((FDecl || Proto) && "Need a function declaration or prototype");
2332
Ted Kremenek9aedc152014-01-17 06:24:56 +00002333 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002334 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002335 if (FDecl) {
2336 // Handle the nonnull attribute on the function/method declaration itself.
2337 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2338 if (!NonNull->args_size()) {
2339 // Easy case: all pointer arguments are nonnull.
2340 for (const auto *Arg : Args)
2341 if (S.isValidPointerAttrType(Arg->getType()))
2342 CheckNonNullArgument(S, Arg, CallSiteLoc);
2343 return;
2344 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002345
Douglas Gregorb4866e82015-06-19 18:13:19 +00002346 for (unsigned Val : NonNull->args()) {
2347 if (Val >= Args.size())
2348 continue;
2349 if (NonNullArgs.empty())
2350 NonNullArgs.resize(Args.size());
2351 NonNullArgs.set(Val);
2352 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002353 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002354 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002355
Douglas Gregorb4866e82015-06-19 18:13:19 +00002356 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2357 // Handle the nonnull attribute on the parameters of the
2358 // function/method.
2359 ArrayRef<ParmVarDecl*> parms;
2360 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2361 parms = FD->parameters();
2362 else
2363 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2364
2365 unsigned ParamIndex = 0;
2366 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2367 I != E; ++I, ++ParamIndex) {
2368 const ParmVarDecl *PVD = *I;
2369 if (PVD->hasAttr<NonNullAttr>() ||
2370 isNonNullType(S.Context, PVD->getType())) {
2371 if (NonNullArgs.empty())
2372 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002373
Douglas Gregorb4866e82015-06-19 18:13:19 +00002374 NonNullArgs.set(ParamIndex);
2375 }
2376 }
2377 } else {
2378 // If we have a non-function, non-method declaration but no
2379 // function prototype, try to dig out the function prototype.
2380 if (!Proto) {
2381 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2382 QualType type = VD->getType().getNonReferenceType();
2383 if (auto pointerType = type->getAs<PointerType>())
2384 type = pointerType->getPointeeType();
2385 else if (auto blockType = type->getAs<BlockPointerType>())
2386 type = blockType->getPointeeType();
2387 // FIXME: data member pointers?
2388
2389 // Dig out the function prototype, if there is one.
2390 Proto = type->getAs<FunctionProtoType>();
2391 }
2392 }
2393
2394 // Fill in non-null argument information from the nullability
2395 // information on the parameter types (if we have them).
2396 if (Proto) {
2397 unsigned Index = 0;
2398 for (auto paramType : Proto->getParamTypes()) {
2399 if (isNonNullType(S.Context, paramType)) {
2400 if (NonNullArgs.empty())
2401 NonNullArgs.resize(Args.size());
2402
2403 NonNullArgs.set(Index);
2404 }
2405
2406 ++Index;
2407 }
2408 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002409 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002410
Douglas Gregorb4866e82015-06-19 18:13:19 +00002411 // Check for non-null arguments.
2412 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2413 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002414 if (NonNullArgs[ArgIndex])
2415 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002416 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002417}
2418
Richard Smith55ce3522012-06-25 20:30:08 +00002419/// Handles the checks for format strings, non-POD arguments to vararg
2420/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002421void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2422 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00002423 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00002424 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002425 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002426 if (CurContext->isDependentContext())
2427 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002428
Ted Kremenekb8176da2010-09-09 04:33:05 +00002429 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002430 llvm::SmallBitVector CheckedVarArgs;
2431 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002432 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002433 // Only create vector if there are format attributes.
2434 CheckedVarArgs.resize(Args.size());
2435
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002436 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002437 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002438 }
Richard Smithd7293d72013-08-05 18:49:43 +00002439 }
Richard Smith55ce3522012-06-25 20:30:08 +00002440
2441 // Refuse POD arguments that weren't caught by the format string
2442 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00002443 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002444 unsigned NumParams = Proto ? Proto->getNumParams()
2445 : FDecl && isa<FunctionDecl>(FDecl)
2446 ? cast<FunctionDecl>(FDecl)->getNumParams()
2447 : FDecl && isa<ObjCMethodDecl>(FDecl)
2448 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2449 : 0;
2450
Alp Toker9cacbab2014-01-20 20:26:09 +00002451 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002452 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002453 if (const Expr *Arg = Args[ArgIdx]) {
2454 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2455 checkVariadicArgument(Arg, CallType);
2456 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002457 }
Richard Smithd7293d72013-08-05 18:49:43 +00002458 }
Mike Stump11289f42009-09-09 15:08:12 +00002459
Douglas Gregorb4866e82015-06-19 18:13:19 +00002460 if (FDecl || Proto) {
2461 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002462
Richard Trieu41bc0992013-06-22 00:20:41 +00002463 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002464 if (FDecl) {
2465 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2466 CheckArgumentWithTypeTag(I, Args.data());
2467 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002468 }
Richard Smith55ce3522012-06-25 20:30:08 +00002469}
2470
2471/// CheckConstructorCall - Check a constructor call for correctness and safety
2472/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002473void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2474 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002475 const FunctionProtoType *Proto,
2476 SourceLocation Loc) {
2477 VariadicCallType CallType =
2478 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002479 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2480 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002481}
2482
2483/// CheckFunctionCall - Check a direct function call for various correctness
2484/// and safety properties not strictly enforced by the C type system.
2485bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2486 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002487 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2488 isa<CXXMethodDecl>(FDecl);
2489 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2490 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002491 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2492 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002493 Expr** Args = TheCall->getArgs();
2494 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00002495 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002496 // If this is a call to a member operator, hide the first argument
2497 // from checkCall.
2498 // FIXME: Our choice of AST representation here is less than ideal.
2499 ++Args;
2500 --NumArgs;
2501 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00002502 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002503 IsMemberFunction, TheCall->getRParenLoc(),
2504 TheCall->getCallee()->getSourceRange(), CallType);
2505
2506 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2507 // None of the checks below are needed for functions that don't have
2508 // simple names (e.g., C++ conversion functions).
2509 if (!FnInfo)
2510 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002511
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002512 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002513 if (getLangOpts().ObjC1)
2514 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002515
Anna Zaks22122702012-01-17 00:37:07 +00002516 unsigned CMId = FDecl->getMemoryFunctionKind();
2517 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002518 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002519
Anna Zaks201d4892012-01-13 21:52:01 +00002520 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002521 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002522 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002523 else if (CMId == Builtin::BIstrncat)
2524 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002525 else
Anna Zaks22122702012-01-17 00:37:07 +00002526 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002527
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002528 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002529}
2530
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002531bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002532 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002533 VariadicCallType CallType =
2534 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002535
Douglas Gregorb4866e82015-06-19 18:13:19 +00002536 checkCall(Method, nullptr, Args,
2537 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2538 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002539
2540 return false;
2541}
2542
Richard Trieu664c4c62013-06-20 21:03:13 +00002543bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2544 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002545 QualType Ty;
2546 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002547 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002548 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002549 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002550 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002551 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002552
Douglas Gregorb4866e82015-06-19 18:13:19 +00002553 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2554 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002555 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Richard Trieu664c4c62013-06-20 21:03:13 +00002557 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002558 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002559 CallType = VariadicDoesNotApply;
2560 } else if (Ty->isBlockPointerType()) {
2561 CallType = VariadicBlock;
2562 } else { // Ty->isFunctionPointerType()
2563 CallType = VariadicFunction;
2564 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002565
Douglas Gregorb4866e82015-06-19 18:13:19 +00002566 checkCall(NDecl, Proto,
2567 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2568 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002569 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002570
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002571 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002572}
2573
Richard Trieu41bc0992013-06-22 00:20:41 +00002574/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2575/// such as function pointers returned from functions.
2576bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002577 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002578 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00002579 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002580 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002581 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002582 TheCall->getCallee()->getSourceRange(), CallType);
2583
2584 return false;
2585}
2586
Tim Northovere94a34c2014-03-11 10:49:14 +00002587static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002588 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002589 return false;
2590
JF Bastiendda2cb12016-04-18 18:01:49 +00002591 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002592 switch (Op) {
2593 case AtomicExpr::AO__c11_atomic_init:
2594 llvm_unreachable("There is no ordering argument for an init");
2595
2596 case AtomicExpr::AO__c11_atomic_load:
2597 case AtomicExpr::AO__atomic_load_n:
2598 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002599 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2600 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002601
2602 case AtomicExpr::AO__c11_atomic_store:
2603 case AtomicExpr::AO__atomic_store:
2604 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002605 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2606 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2607 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002608
2609 default:
2610 return true;
2611 }
2612}
2613
Richard Smithfeea8832012-04-12 05:08:17 +00002614ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2615 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002616 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2617 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002618
Richard Smithfeea8832012-04-12 05:08:17 +00002619 // All these operations take one of the following forms:
2620 enum {
2621 // C __c11_atomic_init(A *, C)
2622 Init,
2623 // C __c11_atomic_load(A *, int)
2624 Load,
2625 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002626 LoadCopy,
2627 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002628 Copy,
2629 // C __c11_atomic_add(A *, M, int)
2630 Arithmetic,
2631 // C __atomic_exchange_n(A *, CP, int)
2632 Xchg,
2633 // void __atomic_exchange(A *, C *, CP, int)
2634 GNUXchg,
2635 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2636 C11CmpXchg,
2637 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2638 GNUCmpXchg
2639 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002640 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2641 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002642 // where:
2643 // C is an appropriate type,
2644 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2645 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2646 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2647 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002648
Gabor Horvath98bd0982015-03-16 09:59:54 +00002649 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2650 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2651 AtomicExpr::AO__atomic_load,
2652 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002653 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2654 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2655 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2656 Op == AtomicExpr::AO__atomic_store_n ||
2657 Op == AtomicExpr::AO__atomic_exchange_n ||
2658 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2659 bool IsAddSub = false;
2660
2661 switch (Op) {
2662 case AtomicExpr::AO__c11_atomic_init:
2663 Form = Init;
2664 break;
2665
2666 case AtomicExpr::AO__c11_atomic_load:
2667 case AtomicExpr::AO__atomic_load_n:
2668 Form = Load;
2669 break;
2670
Richard Smithfeea8832012-04-12 05:08:17 +00002671 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002672 Form = LoadCopy;
2673 break;
2674
2675 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002676 case AtomicExpr::AO__atomic_store:
2677 case AtomicExpr::AO__atomic_store_n:
2678 Form = Copy;
2679 break;
2680
2681 case AtomicExpr::AO__c11_atomic_fetch_add:
2682 case AtomicExpr::AO__c11_atomic_fetch_sub:
2683 case AtomicExpr::AO__atomic_fetch_add:
2684 case AtomicExpr::AO__atomic_fetch_sub:
2685 case AtomicExpr::AO__atomic_add_fetch:
2686 case AtomicExpr::AO__atomic_sub_fetch:
2687 IsAddSub = true;
2688 // Fall through.
2689 case AtomicExpr::AO__c11_atomic_fetch_and:
2690 case AtomicExpr::AO__c11_atomic_fetch_or:
2691 case AtomicExpr::AO__c11_atomic_fetch_xor:
2692 case AtomicExpr::AO__atomic_fetch_and:
2693 case AtomicExpr::AO__atomic_fetch_or:
2694 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002695 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002696 case AtomicExpr::AO__atomic_and_fetch:
2697 case AtomicExpr::AO__atomic_or_fetch:
2698 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002699 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002700 Form = Arithmetic;
2701 break;
2702
2703 case AtomicExpr::AO__c11_atomic_exchange:
2704 case AtomicExpr::AO__atomic_exchange_n:
2705 Form = Xchg;
2706 break;
2707
2708 case AtomicExpr::AO__atomic_exchange:
2709 Form = GNUXchg;
2710 break;
2711
2712 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2713 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2714 Form = C11CmpXchg;
2715 break;
2716
2717 case AtomicExpr::AO__atomic_compare_exchange:
2718 case AtomicExpr::AO__atomic_compare_exchange_n:
2719 Form = GNUCmpXchg;
2720 break;
2721 }
2722
2723 // Check we have the right number of arguments.
2724 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002725 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002726 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002727 << TheCall->getCallee()->getSourceRange();
2728 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002729 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2730 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002731 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002732 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002733 << TheCall->getCallee()->getSourceRange();
2734 return ExprError();
2735 }
2736
Richard Smithfeea8832012-04-12 05:08:17 +00002737 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002738 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002739 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2740 if (ConvertedPtr.isInvalid())
2741 return ExprError();
2742
2743 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002744 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2745 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002746 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002747 << Ptr->getType() << Ptr->getSourceRange();
2748 return ExprError();
2749 }
2750
Richard Smithfeea8832012-04-12 05:08:17 +00002751 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2752 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2753 QualType ValType = AtomTy; // 'C'
2754 if (IsC11) {
2755 if (!AtomTy->isAtomicType()) {
2756 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2757 << Ptr->getType() << Ptr->getSourceRange();
2758 return ExprError();
2759 }
Richard Smithe00921a2012-09-15 06:09:58 +00002760 if (AtomTy.isConstQualified()) {
2761 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2762 << Ptr->getType() << Ptr->getSourceRange();
2763 return ExprError();
2764 }
Richard Smithfeea8832012-04-12 05:08:17 +00002765 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002766 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002767 if (ValType.isConstQualified()) {
2768 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2769 << Ptr->getType() << Ptr->getSourceRange();
2770 return ExprError();
2771 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002772 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002773
Richard Smithfeea8832012-04-12 05:08:17 +00002774 // For an arithmetic operation, the implied arithmetic must be well-formed.
2775 if (Form == Arithmetic) {
2776 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2777 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2778 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2779 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2780 return ExprError();
2781 }
2782 if (!IsAddSub && !ValType->isIntegerType()) {
2783 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2784 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2785 return ExprError();
2786 }
David Majnemere85cff82015-01-28 05:48:06 +00002787 if (IsC11 && ValType->isPointerType() &&
2788 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2789 diag::err_incomplete_type)) {
2790 return ExprError();
2791 }
Richard Smithfeea8832012-04-12 05:08:17 +00002792 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2793 // For __atomic_*_n operations, the value type must be a scalar integral or
2794 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002795 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002796 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2797 return ExprError();
2798 }
2799
Eli Friedmanaa769812013-09-11 03:49:34 +00002800 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2801 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002802 // For GNU atomics, require a trivially-copyable type. This is not part of
2803 // the GNU atomics specification, but we enforce it for sanity.
2804 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002805 << Ptr->getType() << Ptr->getSourceRange();
2806 return ExprError();
2807 }
2808
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002809 switch (ValType.getObjCLifetime()) {
2810 case Qualifiers::OCL_None:
2811 case Qualifiers::OCL_ExplicitNone:
2812 // okay
2813 break;
2814
2815 case Qualifiers::OCL_Weak:
2816 case Qualifiers::OCL_Strong:
2817 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002818 // FIXME: Can this happen? By this point, ValType should be known
2819 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002820 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2821 << ValType << Ptr->getSourceRange();
2822 return ExprError();
2823 }
2824
David Majnemerc6eb6502015-06-03 00:26:35 +00002825 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2826 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002827 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002828 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002829 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002830 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002831 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002832 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002833 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002834 ResultType = Context.BoolTy;
2835
Richard Smithfeea8832012-04-12 05:08:17 +00002836 // The type of a parameter passed 'by value'. In the GNU atomics, such
2837 // arguments are actually passed as pointers.
2838 QualType ByValType = ValType; // 'CP'
2839 if (!IsC11 && !IsN)
2840 ByValType = Ptr->getType();
2841
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002842 // The first argument --- the pointer --- has a fixed type; we
2843 // deduce the types of the rest of the arguments accordingly. Walk
2844 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002845 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002846 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002847 if (i < NumVals[Form] + 1) {
2848 switch (i) {
2849 case 1:
2850 // The second argument is the non-atomic operand. For arithmetic, this
2851 // is always passed by value, and for a compare_exchange it is always
2852 // passed by address. For the rest, GNU uses by-address and C11 uses
2853 // by-value.
2854 assert(Form != Load);
2855 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2856 Ty = ValType;
2857 else if (Form == Copy || Form == Xchg)
2858 Ty = ByValType;
2859 else if (Form == Arithmetic)
2860 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002861 else {
2862 Expr *ValArg = TheCall->getArg(i);
2863 unsigned AS = 0;
2864 // Keep address space of non-atomic pointer type.
2865 if (const PointerType *PtrTy =
2866 ValArg->getType()->getAs<PointerType>()) {
2867 AS = PtrTy->getPointeeType().getAddressSpace();
2868 }
2869 Ty = Context.getPointerType(
2870 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2871 }
Richard Smithfeea8832012-04-12 05:08:17 +00002872 break;
2873 case 2:
2874 // The third argument to compare_exchange / GNU exchange is a
2875 // (pointer to a) desired value.
2876 Ty = ByValType;
2877 break;
2878 case 3:
2879 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2880 Ty = Context.BoolTy;
2881 break;
2882 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002883 } else {
2884 // The order(s) are always converted to int.
2885 Ty = Context.IntTy;
2886 }
Richard Smithfeea8832012-04-12 05:08:17 +00002887
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002888 InitializedEntity Entity =
2889 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002890 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002891 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2892 if (Arg.isInvalid())
2893 return true;
2894 TheCall->setArg(i, Arg.get());
2895 }
2896
Richard Smithfeea8832012-04-12 05:08:17 +00002897 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002898 SmallVector<Expr*, 5> SubExprs;
2899 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002900 switch (Form) {
2901 case Init:
2902 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002903 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002904 break;
2905 case Load:
2906 SubExprs.push_back(TheCall->getArg(1)); // Order
2907 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00002908 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00002909 case Copy:
2910 case Arithmetic:
2911 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002912 SubExprs.push_back(TheCall->getArg(2)); // Order
2913 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002914 break;
2915 case GNUXchg:
2916 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2917 SubExprs.push_back(TheCall->getArg(3)); // Order
2918 SubExprs.push_back(TheCall->getArg(1)); // Val1
2919 SubExprs.push_back(TheCall->getArg(2)); // Val2
2920 break;
2921 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002922 SubExprs.push_back(TheCall->getArg(3)); // Order
2923 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002924 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002925 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002926 break;
2927 case GNUCmpXchg:
2928 SubExprs.push_back(TheCall->getArg(4)); // Order
2929 SubExprs.push_back(TheCall->getArg(1)); // Val1
2930 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2931 SubExprs.push_back(TheCall->getArg(2)); // Val2
2932 SubExprs.push_back(TheCall->getArg(3)); // Weak
2933 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002934 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002935
2936 if (SubExprs.size() >= 2 && Form != Init) {
2937 llvm::APSInt Result(32);
2938 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2939 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002940 Diag(SubExprs[1]->getLocStart(),
2941 diag::warn_atomic_op_has_invalid_memory_order)
2942 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002943 }
2944
Fariborz Jahanian615de762013-05-28 17:37:39 +00002945 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2946 SubExprs, ResultType, Op,
2947 TheCall->getRParenLoc());
2948
2949 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2950 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2951 Context.AtomicUsesUnsupportedLibcall(AE))
2952 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2953 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002954
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002955 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002956}
2957
John McCall29ad95b2011-08-27 01:09:30 +00002958/// checkBuiltinArgument - Given a call to a builtin function, perform
2959/// normal type-checking on the given argument, updating the call in
2960/// place. This is useful when a builtin function requires custom
2961/// type-checking for some of its arguments but not necessarily all of
2962/// them.
2963///
2964/// Returns true on error.
2965static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2966 FunctionDecl *Fn = E->getDirectCallee();
2967 assert(Fn && "builtin call without direct callee!");
2968
2969 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2970 InitializedEntity Entity =
2971 InitializedEntity::InitializeParameter(S.Context, Param);
2972
2973 ExprResult Arg = E->getArg(0);
2974 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2975 if (Arg.isInvalid())
2976 return true;
2977
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002978 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002979 return false;
2980}
2981
Chris Lattnerdc046542009-05-08 06:58:22 +00002982/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2983/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2984/// type of its first argument. The main ActOnCallExpr routines have already
2985/// promoted the types of arguments because all of these calls are prototyped as
2986/// void(...).
2987///
2988/// This function goes through and does final semantic checking for these
2989/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002990ExprResult
2991Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002992 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002993 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2994 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2995
2996 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002997 if (TheCall->getNumArgs() < 1) {
2998 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2999 << 0 << 1 << TheCall->getNumArgs()
3000 << TheCall->getCallee()->getSourceRange();
3001 return ExprError();
3002 }
Mike Stump11289f42009-09-09 15:08:12 +00003003
Chris Lattnerdc046542009-05-08 06:58:22 +00003004 // Inspect the first argument of the atomic builtin. This should always be
3005 // a pointer type, whose element is an integral scalar or pointer type.
3006 // Because it is a pointer type, we don't have to worry about any implicit
3007 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003008 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003009 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003010 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3011 if (FirstArgResult.isInvalid())
3012 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003013 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003014 TheCall->setArg(0, FirstArg);
3015
John McCall31168b02011-06-15 23:02:42 +00003016 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3017 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003018 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3019 << FirstArg->getType() << FirstArg->getSourceRange();
3020 return ExprError();
3021 }
Mike Stump11289f42009-09-09 15:08:12 +00003022
John McCall31168b02011-06-15 23:02:42 +00003023 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003024 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003025 !ValType->isBlockPointerType()) {
3026 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3027 << FirstArg->getType() << FirstArg->getSourceRange();
3028 return ExprError();
3029 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003030
John McCall31168b02011-06-15 23:02:42 +00003031 switch (ValType.getObjCLifetime()) {
3032 case Qualifiers::OCL_None:
3033 case Qualifiers::OCL_ExplicitNone:
3034 // okay
3035 break;
3036
3037 case Qualifiers::OCL_Weak:
3038 case Qualifiers::OCL_Strong:
3039 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003040 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003041 << ValType << FirstArg->getSourceRange();
3042 return ExprError();
3043 }
3044
John McCallb50451a2011-10-05 07:41:44 +00003045 // Strip any qualifiers off ValType.
3046 ValType = ValType.getUnqualifiedType();
3047
Chandler Carruth3973af72010-07-18 20:54:12 +00003048 // The majority of builtins return a value, but a few have special return
3049 // types, so allow them to override appropriately below.
3050 QualType ResultType = ValType;
3051
Chris Lattnerdc046542009-05-08 06:58:22 +00003052 // We need to figure out which concrete builtin this maps onto. For example,
3053 // __sync_fetch_and_add with a 2 byte object turns into
3054 // __sync_fetch_and_add_2.
3055#define BUILTIN_ROW(x) \
3056 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3057 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003058
Chris Lattnerdc046542009-05-08 06:58:22 +00003059 static const unsigned BuiltinIndices[][5] = {
3060 BUILTIN_ROW(__sync_fetch_and_add),
3061 BUILTIN_ROW(__sync_fetch_and_sub),
3062 BUILTIN_ROW(__sync_fetch_and_or),
3063 BUILTIN_ROW(__sync_fetch_and_and),
3064 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003065 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003066
Chris Lattnerdc046542009-05-08 06:58:22 +00003067 BUILTIN_ROW(__sync_add_and_fetch),
3068 BUILTIN_ROW(__sync_sub_and_fetch),
3069 BUILTIN_ROW(__sync_and_and_fetch),
3070 BUILTIN_ROW(__sync_or_and_fetch),
3071 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003072 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003073
Chris Lattnerdc046542009-05-08 06:58:22 +00003074 BUILTIN_ROW(__sync_val_compare_and_swap),
3075 BUILTIN_ROW(__sync_bool_compare_and_swap),
3076 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003077 BUILTIN_ROW(__sync_lock_release),
3078 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003079 };
Mike Stump11289f42009-09-09 15:08:12 +00003080#undef BUILTIN_ROW
3081
Chris Lattnerdc046542009-05-08 06:58:22 +00003082 // Determine the index of the size.
3083 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003084 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003085 case 1: SizeIndex = 0; break;
3086 case 2: SizeIndex = 1; break;
3087 case 4: SizeIndex = 2; break;
3088 case 8: SizeIndex = 3; break;
3089 case 16: SizeIndex = 4; break;
3090 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003091 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3092 << FirstArg->getType() << FirstArg->getSourceRange();
3093 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
Chris Lattnerdc046542009-05-08 06:58:22 +00003096 // Each of these builtins has one pointer argument, followed by some number of
3097 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3098 // that we ignore. Find out which row of BuiltinIndices to read from as well
3099 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003100 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003101 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003102 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003103 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003104 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003105 case Builtin::BI__sync_fetch_and_add:
3106 case Builtin::BI__sync_fetch_and_add_1:
3107 case Builtin::BI__sync_fetch_and_add_2:
3108 case Builtin::BI__sync_fetch_and_add_4:
3109 case Builtin::BI__sync_fetch_and_add_8:
3110 case Builtin::BI__sync_fetch_and_add_16:
3111 BuiltinIndex = 0;
3112 break;
3113
3114 case Builtin::BI__sync_fetch_and_sub:
3115 case Builtin::BI__sync_fetch_and_sub_1:
3116 case Builtin::BI__sync_fetch_and_sub_2:
3117 case Builtin::BI__sync_fetch_and_sub_4:
3118 case Builtin::BI__sync_fetch_and_sub_8:
3119 case Builtin::BI__sync_fetch_and_sub_16:
3120 BuiltinIndex = 1;
3121 break;
3122
3123 case Builtin::BI__sync_fetch_and_or:
3124 case Builtin::BI__sync_fetch_and_or_1:
3125 case Builtin::BI__sync_fetch_and_or_2:
3126 case Builtin::BI__sync_fetch_and_or_4:
3127 case Builtin::BI__sync_fetch_and_or_8:
3128 case Builtin::BI__sync_fetch_and_or_16:
3129 BuiltinIndex = 2;
3130 break;
3131
3132 case Builtin::BI__sync_fetch_and_and:
3133 case Builtin::BI__sync_fetch_and_and_1:
3134 case Builtin::BI__sync_fetch_and_and_2:
3135 case Builtin::BI__sync_fetch_and_and_4:
3136 case Builtin::BI__sync_fetch_and_and_8:
3137 case Builtin::BI__sync_fetch_and_and_16:
3138 BuiltinIndex = 3;
3139 break;
Mike Stump11289f42009-09-09 15:08:12 +00003140
Douglas Gregor73722482011-11-28 16:30:08 +00003141 case Builtin::BI__sync_fetch_and_xor:
3142 case Builtin::BI__sync_fetch_and_xor_1:
3143 case Builtin::BI__sync_fetch_and_xor_2:
3144 case Builtin::BI__sync_fetch_and_xor_4:
3145 case Builtin::BI__sync_fetch_and_xor_8:
3146 case Builtin::BI__sync_fetch_and_xor_16:
3147 BuiltinIndex = 4;
3148 break;
3149
Hal Finkeld2208b52014-10-02 20:53:50 +00003150 case Builtin::BI__sync_fetch_and_nand:
3151 case Builtin::BI__sync_fetch_and_nand_1:
3152 case Builtin::BI__sync_fetch_and_nand_2:
3153 case Builtin::BI__sync_fetch_and_nand_4:
3154 case Builtin::BI__sync_fetch_and_nand_8:
3155 case Builtin::BI__sync_fetch_and_nand_16:
3156 BuiltinIndex = 5;
3157 WarnAboutSemanticsChange = true;
3158 break;
3159
Douglas Gregor73722482011-11-28 16:30:08 +00003160 case Builtin::BI__sync_add_and_fetch:
3161 case Builtin::BI__sync_add_and_fetch_1:
3162 case Builtin::BI__sync_add_and_fetch_2:
3163 case Builtin::BI__sync_add_and_fetch_4:
3164 case Builtin::BI__sync_add_and_fetch_8:
3165 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003166 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003167 break;
3168
3169 case Builtin::BI__sync_sub_and_fetch:
3170 case Builtin::BI__sync_sub_and_fetch_1:
3171 case Builtin::BI__sync_sub_and_fetch_2:
3172 case Builtin::BI__sync_sub_and_fetch_4:
3173 case Builtin::BI__sync_sub_and_fetch_8:
3174 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003175 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003176 break;
3177
3178 case Builtin::BI__sync_and_and_fetch:
3179 case Builtin::BI__sync_and_and_fetch_1:
3180 case Builtin::BI__sync_and_and_fetch_2:
3181 case Builtin::BI__sync_and_and_fetch_4:
3182 case Builtin::BI__sync_and_and_fetch_8:
3183 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003184 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003185 break;
3186
3187 case Builtin::BI__sync_or_and_fetch:
3188 case Builtin::BI__sync_or_and_fetch_1:
3189 case Builtin::BI__sync_or_and_fetch_2:
3190 case Builtin::BI__sync_or_and_fetch_4:
3191 case Builtin::BI__sync_or_and_fetch_8:
3192 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003193 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003194 break;
3195
3196 case Builtin::BI__sync_xor_and_fetch:
3197 case Builtin::BI__sync_xor_and_fetch_1:
3198 case Builtin::BI__sync_xor_and_fetch_2:
3199 case Builtin::BI__sync_xor_and_fetch_4:
3200 case Builtin::BI__sync_xor_and_fetch_8:
3201 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003202 BuiltinIndex = 10;
3203 break;
3204
3205 case Builtin::BI__sync_nand_and_fetch:
3206 case Builtin::BI__sync_nand_and_fetch_1:
3207 case Builtin::BI__sync_nand_and_fetch_2:
3208 case Builtin::BI__sync_nand_and_fetch_4:
3209 case Builtin::BI__sync_nand_and_fetch_8:
3210 case Builtin::BI__sync_nand_and_fetch_16:
3211 BuiltinIndex = 11;
3212 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003213 break;
Mike Stump11289f42009-09-09 15:08:12 +00003214
Chris Lattnerdc046542009-05-08 06:58:22 +00003215 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003216 case Builtin::BI__sync_val_compare_and_swap_1:
3217 case Builtin::BI__sync_val_compare_and_swap_2:
3218 case Builtin::BI__sync_val_compare_and_swap_4:
3219 case Builtin::BI__sync_val_compare_and_swap_8:
3220 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003221 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003222 NumFixed = 2;
3223 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003224
Chris Lattnerdc046542009-05-08 06:58:22 +00003225 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003226 case Builtin::BI__sync_bool_compare_and_swap_1:
3227 case Builtin::BI__sync_bool_compare_and_swap_2:
3228 case Builtin::BI__sync_bool_compare_and_swap_4:
3229 case Builtin::BI__sync_bool_compare_and_swap_8:
3230 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003231 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003232 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003233 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003234 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003235
3236 case Builtin::BI__sync_lock_test_and_set:
3237 case Builtin::BI__sync_lock_test_and_set_1:
3238 case Builtin::BI__sync_lock_test_and_set_2:
3239 case Builtin::BI__sync_lock_test_and_set_4:
3240 case Builtin::BI__sync_lock_test_and_set_8:
3241 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003242 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003243 break;
3244
Chris Lattnerdc046542009-05-08 06:58:22 +00003245 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003246 case Builtin::BI__sync_lock_release_1:
3247 case Builtin::BI__sync_lock_release_2:
3248 case Builtin::BI__sync_lock_release_4:
3249 case Builtin::BI__sync_lock_release_8:
3250 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003251 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003252 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003253 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003254 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003255
3256 case Builtin::BI__sync_swap:
3257 case Builtin::BI__sync_swap_1:
3258 case Builtin::BI__sync_swap_2:
3259 case Builtin::BI__sync_swap_4:
3260 case Builtin::BI__sync_swap_8:
3261 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003262 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003263 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003264 }
Mike Stump11289f42009-09-09 15:08:12 +00003265
Chris Lattnerdc046542009-05-08 06:58:22 +00003266 // Now that we know how many fixed arguments we expect, first check that we
3267 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003268 if (TheCall->getNumArgs() < 1+NumFixed) {
3269 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3270 << 0 << 1+NumFixed << TheCall->getNumArgs()
3271 << TheCall->getCallee()->getSourceRange();
3272 return ExprError();
3273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
Hal Finkeld2208b52014-10-02 20:53:50 +00003275 if (WarnAboutSemanticsChange) {
3276 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3277 << TheCall->getCallee()->getSourceRange();
3278 }
3279
Chris Lattner5b9241b2009-05-08 15:36:58 +00003280 // Get the decl for the concrete builtin from this, we can tell what the
3281 // concrete integer type we should convert to is.
3282 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003283 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003284 FunctionDecl *NewBuiltinDecl;
3285 if (NewBuiltinID == BuiltinID)
3286 NewBuiltinDecl = FDecl;
3287 else {
3288 // Perform builtin lookup to avoid redeclaring it.
3289 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3290 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3291 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3292 assert(Res.getFoundDecl());
3293 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003294 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003295 return ExprError();
3296 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003297
John McCallcf142162010-08-07 06:22:56 +00003298 // The first argument --- the pointer --- has a fixed type; we
3299 // deduce the types of the rest of the arguments accordingly. Walk
3300 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003301 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003302 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003303
Chris Lattnerdc046542009-05-08 06:58:22 +00003304 // GCC does an implicit conversion to the pointer or integer ValType. This
3305 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003306 // Initialize the argument.
3307 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3308 ValType, /*consume*/ false);
3309 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003310 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003311 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003312
Chris Lattnerdc046542009-05-08 06:58:22 +00003313 // Okay, we have something that *can* be converted to the right type. Check
3314 // to see if there is a potentially weird extension going on here. This can
3315 // happen when you do an atomic operation on something like an char* and
3316 // pass in 42. The 42 gets converted to char. This is even more strange
3317 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003318 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003319 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003322 ASTContext& Context = this->getASTContext();
3323
3324 // Create a new DeclRefExpr to refer to the new decl.
3325 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3326 Context,
3327 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003328 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003329 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003330 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003331 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003332 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003333 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003334
Chris Lattnerdc046542009-05-08 06:58:22 +00003335 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003336 // FIXME: This loses syntactic information.
3337 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3338 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3339 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003340 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003341
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003342 // Change the result type of the call to match the original value type. This
3343 // is arbitrary, but the codegen for these builtins ins design to handle it
3344 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003345 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003346
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003347 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003348}
3349
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003350/// SemaBuiltinNontemporalOverloaded - We have a call to
3351/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3352/// overloaded function based on the pointer type of its last argument.
3353///
3354/// This function goes through and does final semantic checking for these
3355/// builtins.
3356ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3358 DeclRefExpr *DRE =
3359 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3360 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3361 unsigned BuiltinID = FDecl->getBuiltinID();
3362 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3363 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3364 "Unexpected nontemporal load/store builtin!");
3365 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3366 unsigned numArgs = isStore ? 2 : 1;
3367
3368 // Ensure that we have the proper number of arguments.
3369 if (checkArgCount(*this, TheCall, numArgs))
3370 return ExprError();
3371
3372 // Inspect the last argument of the nontemporal builtin. This should always
3373 // be a pointer type, from which we imply the type of the memory access.
3374 // Because it is a pointer type, we don't have to worry about any implicit
3375 // casts here.
3376 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3377 ExprResult PointerArgResult =
3378 DefaultFunctionArrayLvalueConversion(PointerArg);
3379
3380 if (PointerArgResult.isInvalid())
3381 return ExprError();
3382 PointerArg = PointerArgResult.get();
3383 TheCall->setArg(numArgs - 1, PointerArg);
3384
3385 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3386 if (!pointerType) {
3387 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3388 << PointerArg->getType() << PointerArg->getSourceRange();
3389 return ExprError();
3390 }
3391
3392 QualType ValType = pointerType->getPointeeType();
3393
3394 // Strip any qualifiers off ValType.
3395 ValType = ValType.getUnqualifiedType();
3396 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3397 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3398 !ValType->isVectorType()) {
3399 Diag(DRE->getLocStart(),
3400 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3401 << PointerArg->getType() << PointerArg->getSourceRange();
3402 return ExprError();
3403 }
3404
3405 if (!isStore) {
3406 TheCall->setType(ValType);
3407 return TheCallResult;
3408 }
3409
3410 ExprResult ValArg = TheCall->getArg(0);
3411 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3412 Context, ValType, /*consume*/ false);
3413 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3414 if (ValArg.isInvalid())
3415 return ExprError();
3416
3417 TheCall->setArg(0, ValArg.get());
3418 TheCall->setType(Context.VoidTy);
3419 return TheCallResult;
3420}
3421
Chris Lattner6436fb62009-02-18 06:01:06 +00003422/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003423/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003424/// Note: It might also make sense to do the UTF-16 conversion here (would
3425/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003426bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003427 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003428 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3429
Douglas Gregorfb65e592011-07-27 05:40:30 +00003430 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003431 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3432 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003433 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003434 }
Mike Stump11289f42009-09-09 15:08:12 +00003435
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003436 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003437 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003438 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003439 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3440 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3441 llvm::UTF16 *ToPtr = &ToBuf[0];
3442
3443 llvm::ConversionResult Result =
3444 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3445 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003446 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003447 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003448 Diag(Arg->getLocStart(),
3449 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3450 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003451 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003452}
3453
Mehdi Amini06d367c2016-10-24 20:39:34 +00003454/// CheckObjCString - Checks that the format string argument to the os_log()
3455/// and os_trace() functions is correct, and converts it to const char *.
3456ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3457 Arg = Arg->IgnoreParenCasts();
3458 auto *Literal = dyn_cast<StringLiteral>(Arg);
3459 if (!Literal) {
3460 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3461 Literal = ObjcLiteral->getString();
3462 }
3463 }
3464
3465 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3466 return ExprError(
3467 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3468 << Arg->getSourceRange());
3469 }
3470
3471 ExprResult Result(Literal);
3472 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3473 InitializedEntity Entity =
3474 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3475 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3476 return Result;
3477}
3478
Charles Davisc7d5c942015-09-17 20:55:33 +00003479/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3480/// for validity. Emit an error and return true on failure; return false
3481/// on success.
3482bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003483 Expr *Fn = TheCall->getCallee();
3484 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003485 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003486 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003487 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3488 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003489 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003490 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003491 return true;
3492 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003493
3494 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003495 return Diag(TheCall->getLocEnd(),
3496 diag::err_typecheck_call_too_few_args_at_least)
3497 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003498 }
3499
John McCall29ad95b2011-08-27 01:09:30 +00003500 // Type-check the first argument normally.
3501 if (checkBuiltinArgument(*this, TheCall, 0))
3502 return true;
3503
Chris Lattnere202e6a2007-12-20 00:05:45 +00003504 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00003505 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00003506 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00003507 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00003508 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00003509 else if (FunctionDecl *FD = getCurFunctionDecl())
3510 isVariadic = FD->isVariadic();
3511 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00003512 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00003513
Chris Lattnere202e6a2007-12-20 00:05:45 +00003514 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003515 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3516 return true;
3517 }
Mike Stump11289f42009-09-09 15:08:12 +00003518
Chris Lattner43be2e62007-12-19 23:59:04 +00003519 // Verify that the second argument to the builtin is the last argument of the
3520 // current function or method.
3521 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003522 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003523
Nico Weber9eea7642013-05-24 23:31:57 +00003524 // These are valid if SecondArgIsLastNamedArgument is false after the next
3525 // block.
3526 QualType Type;
3527 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003528 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003529
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003530 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3531 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00003532 // FIXME: This isn't correct for methods (results in bogus warning).
3533 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003534 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00003535 if (CurBlock)
David Majnemera3debed2016-06-24 05:33:44 +00003536 LastArg = CurBlock->TheDecl->parameters().back();
Steve Naroff439a3e42009-04-15 19:33:47 +00003537 else if (FunctionDecl *FD = getCurFunctionDecl())
David Majnemera3debed2016-06-24 05:33:44 +00003538 LastArg = FD->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003539 else
David Majnemera3debed2016-06-24 05:33:44 +00003540 LastArg = getCurMethodDecl()->parameters().back();
Chris Lattner43be2e62007-12-19 23:59:04 +00003541 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00003542
3543 Type = PV->getType();
3544 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003545 IsCRegister =
3546 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003547 }
3548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
Chris Lattner43be2e62007-12-19 23:59:04 +00003550 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003551 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003552 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003553 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003554 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3555 // Promotable integers are UB, but enumerations need a bit of
3556 // extra checking to see what their promotable type actually is.
3557 if (!Type->isPromotableIntegerType())
3558 return false;
3559 if (!Type->isEnumeralType())
3560 return true;
3561 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3562 return !(ED &&
3563 Context.typesAreCompatible(ED->getPromotionType(), Type));
3564 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003565 unsigned Reason = 0;
3566 if (Type->isReferenceType()) Reason = 1;
3567 else if (IsCRegister) Reason = 2;
3568 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003569 Diag(ParamLoc, diag::note_parameter_type) << Type;
3570 }
3571
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003572 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003573 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003574}
Chris Lattner43be2e62007-12-19 23:59:04 +00003575
Charles Davisc7d5c942015-09-17 20:55:33 +00003576/// Check the arguments to '__builtin_va_start' for validity, and that
3577/// it was called from a function of the native ABI.
3578/// Emit an error and return true on failure; return false on success.
3579bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3580 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3581 // On x64 Windows, don't allow this in System V ABI functions.
3582 // (Yes, that means there's no corresponding way to support variadic
3583 // System V ABI functions on Windows.)
3584 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3585 unsigned OS = Context.getTargetInfo().getTriple().getOS();
3586 clang::CallingConv CC = CC_C;
3587 if (const FunctionDecl *FD = getCurFunctionDecl())
3588 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3589 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3590 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3591 return Diag(TheCall->getCallee()->getLocStart(),
3592 diag::err_va_start_used_in_wrong_abi_function)
3593 << (OS != llvm::Triple::Win32);
3594 }
3595 return SemaBuiltinVAStartImpl(TheCall);
3596}
3597
3598/// Check the arguments to '__builtin_ms_va_start' for validity, and that
3599/// it was called from a Win64 ABI function.
3600/// Emit an error and return true on failure; return false on success.
3601bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3602 // This only makes sense for x86-64.
3603 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3604 Expr *Callee = TheCall->getCallee();
3605 if (TT.getArch() != llvm::Triple::x86_64)
3606 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3607 // Don't allow this in System V ABI functions.
3608 clang::CallingConv CC = CC_C;
3609 if (const FunctionDecl *FD = getCurFunctionDecl())
3610 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3611 if (CC == CC_X86_64SysV ||
3612 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3613 return Diag(Callee->getLocStart(),
3614 diag::err_ms_va_start_used_in_sysv_function);
3615 return SemaBuiltinVAStartImpl(TheCall);
3616}
3617
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003618bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3619 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3620 // const char *named_addr);
3621
3622 Expr *Func = Call->getCallee();
3623
3624 if (Call->getNumArgs() < 3)
3625 return Diag(Call->getLocEnd(),
3626 diag::err_typecheck_call_too_few_args_at_least)
3627 << 0 /*function call*/ << 3 << Call->getNumArgs();
3628
3629 // Determine whether the current function is variadic or not.
3630 bool IsVariadic;
3631 if (BlockScopeInfo *CurBlock = getCurBlock())
3632 IsVariadic = CurBlock->TheDecl->isVariadic();
3633 else if (FunctionDecl *FD = getCurFunctionDecl())
3634 IsVariadic = FD->isVariadic();
3635 else if (ObjCMethodDecl *MD = getCurMethodDecl())
3636 IsVariadic = MD->isVariadic();
3637 else
3638 llvm_unreachable("unexpected statement type");
3639
3640 if (!IsVariadic) {
3641 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3642 return true;
3643 }
3644
3645 // Type-check the first argument normally.
3646 if (checkBuiltinArgument(*this, Call, 0))
3647 return true;
3648
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003649 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003650 unsigned ArgNo;
3651 QualType Type;
3652 } ArgumentTypes[] = {
3653 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3654 { 2, Context.getSizeType() },
3655 };
3656
3657 for (const auto &AT : ArgumentTypes) {
3658 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3659 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3660 continue;
3661 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3662 << Arg->getType() << AT.Type << 1 /* different class */
3663 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3664 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3665 }
3666
3667 return false;
3668}
3669
Chris Lattner2da14fb2007-12-20 00:26:33 +00003670/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3671/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003672bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3673 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003674 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003675 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003676 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003677 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003678 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003679 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003680 << SourceRange(TheCall->getArg(2)->getLocStart(),
3681 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003682
John Wiegley01296292011-04-08 18:41:53 +00003683 ExprResult OrigArg0 = TheCall->getArg(0);
3684 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003685
Chris Lattner2da14fb2007-12-20 00:26:33 +00003686 // Do standard promotions between the two arguments, returning their common
3687 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003688 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003689 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3690 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003691
3692 // Make sure any conversions are pushed back into the call; this is
3693 // type safe since unordered compare builtins are declared as "_Bool
3694 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003695 TheCall->setArg(0, OrigArg0.get());
3696 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003697
John Wiegley01296292011-04-08 18:41:53 +00003698 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003699 return false;
3700
Chris Lattner2da14fb2007-12-20 00:26:33 +00003701 // If the common type isn't a real floating type, then the arguments were
3702 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003703 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003704 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003705 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003706 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3707 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003708
Chris Lattner2da14fb2007-12-20 00:26:33 +00003709 return false;
3710}
3711
Benjamin Kramer634fc102010-02-15 22:42:31 +00003712/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3713/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003714/// to check everything. We expect the last argument to be a floating point
3715/// value.
3716bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3717 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003718 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003719 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003720 if (TheCall->getNumArgs() > NumArgs)
3721 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003722 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003723 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003724 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003725 (*(TheCall->arg_end()-1))->getLocEnd());
3726
Benjamin Kramer64aae502010-02-16 10:07:31 +00003727 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003728
Eli Friedman7e4faac2009-08-31 20:06:00 +00003729 if (OrigArg->isTypeDependent())
3730 return false;
3731
Chris Lattner68784ef2010-05-06 05:50:07 +00003732 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003733 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003734 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003735 diag::err_typecheck_call_invalid_unary_fp)
3736 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003737
Chris Lattner68784ef2010-05-06 05:50:07 +00003738 // If this is an implicit conversion from float -> double, remove it.
3739 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3740 Expr *CastArg = Cast->getSubExpr();
3741 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3742 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3743 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00003744 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00003745 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00003746 }
3747 }
3748
Eli Friedman7e4faac2009-08-31 20:06:00 +00003749 return false;
3750}
3751
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003752/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3753// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003754ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003755 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003756 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003757 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003758 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3759 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003760
Nate Begemana0110022010-06-08 00:16:34 +00003761 // Determine which of the following types of shufflevector we're checking:
3762 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003763 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003764 QualType resType = TheCall->getArg(0)->getType();
3765 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003766
Douglas Gregorc25f7662009-05-19 22:10:17 +00003767 if (!TheCall->getArg(0)->isTypeDependent() &&
3768 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003769 QualType LHSType = TheCall->getArg(0)->getType();
3770 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003771
Craig Topperbaca3892013-07-29 06:47:04 +00003772 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3773 return ExprError(Diag(TheCall->getLocStart(),
3774 diag::err_shufflevector_non_vector)
3775 << SourceRange(TheCall->getArg(0)->getLocStart(),
3776 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003777
Nate Begemana0110022010-06-08 00:16:34 +00003778 numElements = LHSType->getAs<VectorType>()->getNumElements();
3779 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003780
Nate Begemana0110022010-06-08 00:16:34 +00003781 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3782 // with mask. If so, verify that RHS is an integer vector type with the
3783 // same number of elts as lhs.
3784 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003785 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003786 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003787 return ExprError(Diag(TheCall->getLocStart(),
3788 diag::err_shufflevector_incompatible_vector)
3789 << SourceRange(TheCall->getArg(1)->getLocStart(),
3790 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003791 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00003792 return ExprError(Diag(TheCall->getLocStart(),
3793 diag::err_shufflevector_incompatible_vector)
3794 << SourceRange(TheCall->getArg(0)->getLocStart(),
3795 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00003796 } else if (numElements != numResElements) {
3797 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00003798 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003799 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003800 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003801 }
3802
3803 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00003804 if (TheCall->getArg(i)->isTypeDependent() ||
3805 TheCall->getArg(i)->isValueDependent())
3806 continue;
3807
Nate Begemana0110022010-06-08 00:16:34 +00003808 llvm::APSInt Result(32);
3809 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3810 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003811 diag::err_shufflevector_nonconstant_argument)
3812 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003813
Craig Topper50ad5b72013-08-03 17:40:38 +00003814 // Allow -1 which will be translated to undef in the IR.
3815 if (Result.isSigned() && Result.isAllOnesValue())
3816 continue;
3817
Chris Lattner7ab824e2008-08-10 02:05:13 +00003818 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003819 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00003820 diag::err_shufflevector_argument_too_large)
3821 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003822 }
3823
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003824 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003825
Chris Lattner7ab824e2008-08-10 02:05:13 +00003826 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003827 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00003828 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003829 }
3830
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003831 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3832 TheCall->getCallee()->getLocStart(),
3833 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003834}
Chris Lattner43be2e62007-12-19 23:59:04 +00003835
Hal Finkelc4d7c822013-09-18 03:29:45 +00003836/// SemaConvertVectorExpr - Handle __builtin_convertvector
3837ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3838 SourceLocation BuiltinLoc,
3839 SourceLocation RParenLoc) {
3840 ExprValueKind VK = VK_RValue;
3841 ExprObjectKind OK = OK_Ordinary;
3842 QualType DstTy = TInfo->getType();
3843 QualType SrcTy = E->getType();
3844
3845 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3846 return ExprError(Diag(BuiltinLoc,
3847 diag::err_convertvector_non_vector)
3848 << E->getSourceRange());
3849 if (!DstTy->isVectorType() && !DstTy->isDependentType())
3850 return ExprError(Diag(BuiltinLoc,
3851 diag::err_convertvector_non_vector_type));
3852
3853 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3854 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3855 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3856 if (SrcElts != DstElts)
3857 return ExprError(Diag(BuiltinLoc,
3858 diag::err_convertvector_incompatible_vector)
3859 << E->getSourceRange());
3860 }
3861
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003862 return new (Context)
3863 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003864}
3865
Daniel Dunbarb7257262008-07-21 22:59:13 +00003866/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3867// This is declared to take (const void*, ...) and can take two
3868// optional constant int args.
3869bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003870 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003871
Chris Lattner3b054132008-11-19 05:08:23 +00003872 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003873 return Diag(TheCall->getLocEnd(),
3874 diag::err_typecheck_call_too_many_args_at_most)
3875 << 0 /*function call*/ << 3 << NumArgs
3876 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003877
3878 // Argument 0 is checked for us and the remaining arguments must be
3879 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003880 for (unsigned i = 1; i != NumArgs; ++i)
3881 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003882 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003883
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003884 return false;
3885}
3886
Hal Finkelf0417332014-07-17 14:25:55 +00003887/// SemaBuiltinAssume - Handle __assume (MS Extension).
3888// __assume does not evaluate its arguments, and should warn if its argument
3889// has side effects.
3890bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3891 Expr *Arg = TheCall->getArg(0);
3892 if (Arg->isInstantiationDependent()) return false;
3893
3894 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003895 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003896 << Arg->getSourceRange()
3897 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3898
3899 return false;
3900}
3901
David Majnemer86b1bfa2016-10-31 18:07:57 +00003902/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00003903/// as (size_t, size_t) where the second size_t must be a power of 2 greater
3904/// than 8.
3905bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
3906 // The alignment must be a constant integer.
3907 Expr *Arg = TheCall->getArg(1);
3908
3909 // We can't check the value of a dependent argument.
3910 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00003911 if (const auto *UE =
3912 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
3913 if (UE->getKind() == UETT_AlignOf)
3914 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
3915 << Arg->getSourceRange();
3916
David Majnemer51169932016-10-31 05:37:48 +00003917 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
3918
3919 if (!Result.isPowerOf2())
3920 return Diag(TheCall->getLocStart(),
3921 diag::err_alignment_not_power_of_two)
3922 << Arg->getSourceRange();
3923
3924 if (Result < Context.getCharWidth())
3925 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
3926 << (unsigned)Context.getCharWidth()
3927 << Arg->getSourceRange();
3928
3929 if (Result > INT32_MAX)
3930 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
3931 << INT32_MAX
3932 << Arg->getSourceRange();
3933 }
3934
3935 return false;
3936}
3937
3938/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00003939/// as (const void*, size_t, ...) and can take one optional constant int arg.
3940bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3941 unsigned NumArgs = TheCall->getNumArgs();
3942
3943 if (NumArgs > 3)
3944 return Diag(TheCall->getLocEnd(),
3945 diag::err_typecheck_call_too_many_args_at_most)
3946 << 0 /*function call*/ << 3 << NumArgs
3947 << TheCall->getSourceRange();
3948
3949 // The alignment must be a constant integer.
3950 Expr *Arg = TheCall->getArg(1);
3951
3952 // We can't check the value of a dependent argument.
3953 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3954 llvm::APSInt Result;
3955 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3956 return true;
3957
3958 if (!Result.isPowerOf2())
3959 return Diag(TheCall->getLocStart(),
3960 diag::err_alignment_not_power_of_two)
3961 << Arg->getSourceRange();
3962 }
3963
3964 if (NumArgs > 2) {
3965 ExprResult Arg(TheCall->getArg(2));
3966 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3967 Context.getSizeType(), false);
3968 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3969 if (Arg.isInvalid()) return true;
3970 TheCall->setArg(2, Arg.get());
3971 }
Hal Finkelf0417332014-07-17 14:25:55 +00003972
3973 return false;
3974}
3975
Mehdi Amini06d367c2016-10-24 20:39:34 +00003976bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
3977 unsigned BuiltinID =
3978 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
3979 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
3980
3981 unsigned NumArgs = TheCall->getNumArgs();
3982 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
3983 if (NumArgs < NumRequiredArgs) {
3984 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3985 << 0 /* function call */ << NumRequiredArgs << NumArgs
3986 << TheCall->getSourceRange();
3987 }
3988 if (NumArgs >= NumRequiredArgs + 0x100) {
3989 return Diag(TheCall->getLocEnd(),
3990 diag::err_typecheck_call_too_many_args_at_most)
3991 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
3992 << TheCall->getSourceRange();
3993 }
3994 unsigned i = 0;
3995
3996 // For formatting call, check buffer arg.
3997 if (!IsSizeCall) {
3998 ExprResult Arg(TheCall->getArg(i));
3999 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4000 Context, Context.VoidPtrTy, false);
4001 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4002 if (Arg.isInvalid())
4003 return true;
4004 TheCall->setArg(i, Arg.get());
4005 i++;
4006 }
4007
4008 // Check string literal arg.
4009 unsigned FormatIdx = i;
4010 {
4011 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4012 if (Arg.isInvalid())
4013 return true;
4014 TheCall->setArg(i, Arg.get());
4015 i++;
4016 }
4017
4018 // Make sure variadic args are scalar.
4019 unsigned FirstDataArg = i;
4020 while (i < NumArgs) {
4021 ExprResult Arg = DefaultVariadicArgumentPromotion(
4022 TheCall->getArg(i), VariadicFunction, nullptr);
4023 if (Arg.isInvalid())
4024 return true;
4025 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4026 if (ArgSize.getQuantity() >= 0x100) {
4027 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4028 << i << (int)ArgSize.getQuantity() << 0xff
4029 << TheCall->getSourceRange();
4030 }
4031 TheCall->setArg(i, Arg.get());
4032 i++;
4033 }
4034
4035 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4036 // call to avoid duplicate diagnostics.
4037 if (!IsSizeCall) {
4038 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4039 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4040 bool Success = CheckFormatArguments(
4041 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4042 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4043 CheckedVarArgs);
4044 if (!Success)
4045 return true;
4046 }
4047
4048 if (IsSizeCall) {
4049 TheCall->setType(Context.getSizeType());
4050 } else {
4051 TheCall->setType(Context.VoidPtrTy);
4052 }
4053 return false;
4054}
4055
Eric Christopher8d0c6212010-04-17 02:26:23 +00004056/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4057/// TheCall is a constant expression.
4058bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4059 llvm::APSInt &Result) {
4060 Expr *Arg = TheCall->getArg(ArgNum);
4061 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4062 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4063
4064 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4065
4066 if (!Arg->isIntegerConstantExpr(Result, Context))
4067 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004068 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004069
Chris Lattnerd545ad12009-09-23 06:06:36 +00004070 return false;
4071}
4072
Richard Sandiford28940af2014-04-16 08:47:51 +00004073/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4074/// TheCall is a constant expression in the range [Low, High].
4075bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4076 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004077 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004078
4079 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004080 Expr *Arg = TheCall->getArg(ArgNum);
4081 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004082 return false;
4083
Eric Christopher8d0c6212010-04-17 02:26:23 +00004084 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004085 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004086 return true;
4087
Richard Sandiford28940af2014-04-16 08:47:51 +00004088 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004089 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004090 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004091
4092 return false;
4093}
4094
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004095/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4096/// TheCall is a constant expression is a multiple of Num..
4097bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4098 unsigned Num) {
4099 llvm::APSInt Result;
4100
4101 // We can't check the value of a dependent argument.
4102 Expr *Arg = TheCall->getArg(ArgNum);
4103 if (Arg->isTypeDependent() || Arg->isValueDependent())
4104 return false;
4105
4106 // Check constant-ness first.
4107 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4108 return true;
4109
4110 if (Result.getSExtValue() % Num != 0)
4111 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4112 << Num << Arg->getSourceRange();
4113
4114 return false;
4115}
4116
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004117/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4118/// TheCall is an ARM/AArch64 special register string literal.
4119bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4120 int ArgNum, unsigned ExpectedFieldNum,
4121 bool AllowName) {
4122 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4123 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4124 BuiltinID == ARM::BI__builtin_arm_rsr ||
4125 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4126 BuiltinID == ARM::BI__builtin_arm_wsr ||
4127 BuiltinID == ARM::BI__builtin_arm_wsrp;
4128 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4129 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4130 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4131 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4132 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4133 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4134 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4135
4136 // We can't check the value of a dependent argument.
4137 Expr *Arg = TheCall->getArg(ArgNum);
4138 if (Arg->isTypeDependent() || Arg->isValueDependent())
4139 return false;
4140
4141 // Check if the argument is a string literal.
4142 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4143 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4144 << Arg->getSourceRange();
4145
4146 // Check the type of special register given.
4147 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4148 SmallVector<StringRef, 6> Fields;
4149 Reg.split(Fields, ":");
4150
4151 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4152 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4153 << Arg->getSourceRange();
4154
4155 // If the string is the name of a register then we cannot check that it is
4156 // valid here but if the string is of one the forms described in ACLE then we
4157 // can check that the supplied fields are integers and within the valid
4158 // ranges.
4159 if (Fields.size() > 1) {
4160 bool FiveFields = Fields.size() == 5;
4161
4162 bool ValidString = true;
4163 if (IsARMBuiltin) {
4164 ValidString &= Fields[0].startswith_lower("cp") ||
4165 Fields[0].startswith_lower("p");
4166 if (ValidString)
4167 Fields[0] =
4168 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4169
4170 ValidString &= Fields[2].startswith_lower("c");
4171 if (ValidString)
4172 Fields[2] = Fields[2].drop_front(1);
4173
4174 if (FiveFields) {
4175 ValidString &= Fields[3].startswith_lower("c");
4176 if (ValidString)
4177 Fields[3] = Fields[3].drop_front(1);
4178 }
4179 }
4180
4181 SmallVector<int, 5> Ranges;
4182 if (FiveFields)
4183 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
4184 else
4185 Ranges.append({15, 7, 15});
4186
4187 for (unsigned i=0; i<Fields.size(); ++i) {
4188 int IntField;
4189 ValidString &= !Fields[i].getAsInteger(10, IntField);
4190 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4191 }
4192
4193 if (!ValidString)
4194 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4195 << Arg->getSourceRange();
4196
4197 } else if (IsAArch64Builtin && Fields.size() == 1) {
4198 // If the register name is one of those that appear in the condition below
4199 // and the special register builtin being used is one of the write builtins,
4200 // then we require that the argument provided for writing to the register
4201 // is an integer constant expression. This is because it will be lowered to
4202 // an MSR (immediate) instruction, so we need to know the immediate at
4203 // compile time.
4204 if (TheCall->getNumArgs() != 2)
4205 return false;
4206
4207 std::string RegLower = Reg.lower();
4208 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4209 RegLower != "pan" && RegLower != "uao")
4210 return false;
4211
4212 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4213 }
4214
4215 return false;
4216}
4217
Eli Friedmanc97d0142009-05-03 06:04:26 +00004218/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004219/// This checks that the target supports __builtin_longjmp and
4220/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004221bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004222 if (!Context.getTargetInfo().hasSjLjLowering())
4223 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4224 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4225
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004226 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004227 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004228
Eric Christopher8d0c6212010-04-17 02:26:23 +00004229 // TODO: This is less than ideal. Overload this to take a value.
4230 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4231 return true;
4232
4233 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004234 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4235 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4236
4237 return false;
4238}
4239
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004240/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4241/// This checks that the target supports __builtin_setjmp.
4242bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4243 if (!Context.getTargetInfo().hasSjLjLowering())
4244 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4245 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4246 return false;
4247}
4248
Richard Smithd7293d72013-08-05 18:49:43 +00004249namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004250class UncoveredArgHandler {
4251 enum { Unknown = -1, AllCovered = -2 };
4252 signed FirstUncoveredArg;
4253 SmallVector<const Expr *, 4> DiagnosticExprs;
4254
4255public:
4256 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4257
4258 bool hasUncoveredArg() const {
4259 return (FirstUncoveredArg >= 0);
4260 }
4261
4262 unsigned getUncoveredArg() const {
4263 assert(hasUncoveredArg() && "no uncovered argument");
4264 return FirstUncoveredArg;
4265 }
4266
4267 void setAllCovered() {
4268 // A string has been found with all arguments covered, so clear out
4269 // the diagnostics.
4270 DiagnosticExprs.clear();
4271 FirstUncoveredArg = AllCovered;
4272 }
4273
4274 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4275 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4276
4277 // Don't update if a previous string covers all arguments.
4278 if (FirstUncoveredArg == AllCovered)
4279 return;
4280
4281 // UncoveredArgHandler tracks the highest uncovered argument index
4282 // and with it all the strings that match this index.
4283 if (NewFirstUncoveredArg == FirstUncoveredArg)
4284 DiagnosticExprs.push_back(StrExpr);
4285 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4286 DiagnosticExprs.clear();
4287 DiagnosticExprs.push_back(StrExpr);
4288 FirstUncoveredArg = NewFirstUncoveredArg;
4289 }
4290 }
4291
4292 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4293};
4294
Richard Smithd7293d72013-08-05 18:49:43 +00004295enum StringLiteralCheckType {
4296 SLCT_NotALiteral,
4297 SLCT_UncheckedLiteral,
4298 SLCT_CheckedLiteral
4299};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004300} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004301
Stephen Hines648c3692016-09-16 01:07:04 +00004302static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4303 BinaryOperatorKind BinOpKind,
4304 bool AddendIsRight) {
4305 unsigned BitWidth = Offset.getBitWidth();
4306 unsigned AddendBitWidth = Addend.getBitWidth();
4307 // There might be negative interim results.
4308 if (Addend.isUnsigned()) {
4309 Addend = Addend.zext(++AddendBitWidth);
4310 Addend.setIsSigned(true);
4311 }
4312 // Adjust the bit width of the APSInts.
4313 if (AddendBitWidth > BitWidth) {
4314 Offset = Offset.sext(AddendBitWidth);
4315 BitWidth = AddendBitWidth;
4316 } else if (BitWidth > AddendBitWidth) {
4317 Addend = Addend.sext(BitWidth);
4318 }
4319
4320 bool Ov = false;
4321 llvm::APSInt ResOffset = Offset;
4322 if (BinOpKind == BO_Add)
4323 ResOffset = Offset.sadd_ov(Addend, Ov);
4324 else {
4325 assert(AddendIsRight && BinOpKind == BO_Sub &&
4326 "operator must be add or sub with addend on the right");
4327 ResOffset = Offset.ssub_ov(Addend, Ov);
4328 }
4329
4330 // We add an offset to a pointer here so we should support an offset as big as
4331 // possible.
4332 if (Ov) {
4333 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004334 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004335 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4336 return;
4337 }
4338
4339 Offset = ResOffset;
4340}
4341
4342namespace {
4343// This is a wrapper class around StringLiteral to support offsetted string
4344// literals as format strings. It takes the offset into account when returning
4345// the string and its length or the source locations to display notes correctly.
4346class FormatStringLiteral {
4347 const StringLiteral *FExpr;
4348 int64_t Offset;
4349
4350 public:
4351 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4352 : FExpr(fexpr), Offset(Offset) {}
4353
4354 StringRef getString() const {
4355 return FExpr->getString().drop_front(Offset);
4356 }
4357
4358 unsigned getByteLength() const {
4359 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4360 }
4361 unsigned getLength() const { return FExpr->getLength() - Offset; }
4362 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4363
4364 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4365
4366 QualType getType() const { return FExpr->getType(); }
4367
4368 bool isAscii() const { return FExpr->isAscii(); }
4369 bool isWide() const { return FExpr->isWide(); }
4370 bool isUTF8() const { return FExpr->isUTF8(); }
4371 bool isUTF16() const { return FExpr->isUTF16(); }
4372 bool isUTF32() const { return FExpr->isUTF32(); }
4373 bool isPascal() const { return FExpr->isPascal(); }
4374
4375 SourceLocation getLocationOfByte(
4376 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4377 const TargetInfo &Target, unsigned *StartToken = nullptr,
4378 unsigned *StartTokenByteOffset = nullptr) const {
4379 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4380 StartToken, StartTokenByteOffset);
4381 }
4382
4383 SourceLocation getLocStart() const LLVM_READONLY {
4384 return FExpr->getLocStart().getLocWithOffset(Offset);
4385 }
4386 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4387};
4388} // end anonymous namespace
4389
4390static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004391 const Expr *OrigFormatExpr,
4392 ArrayRef<const Expr *> Args,
4393 bool HasVAListArg, unsigned format_idx,
4394 unsigned firstDataArg,
4395 Sema::FormatStringType Type,
4396 bool inFunctionCall,
4397 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004398 llvm::SmallBitVector &CheckedVarArgs,
4399 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004400
Richard Smith55ce3522012-06-25 20:30:08 +00004401// Determine if an expression is a string literal or constant string.
4402// If this function returns false on the arguments to a function expecting a
4403// format string, we will usually need to emit a warning.
4404// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004405static StringLiteralCheckType
4406checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4407 bool HasVAListArg, unsigned format_idx,
4408 unsigned firstDataArg, Sema::FormatStringType Type,
4409 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004410 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004411 UncoveredArgHandler &UncoveredArg,
4412 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004413 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004414 assert(Offset.isSigned() && "invalid offset");
4415
Douglas Gregorc25f7662009-05-19 22:10:17 +00004416 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004417 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004418
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004419 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004420
Richard Smithd7293d72013-08-05 18:49:43 +00004421 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004422 // Technically -Wformat-nonliteral does not warn about this case.
4423 // The behavior of printf and friends in this case is implementation
4424 // dependent. Ideally if the format string cannot be null then
4425 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004426 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004427
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004428 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004429 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004430 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004431 // The expression is a literal if both sub-expressions were, and it was
4432 // completely checked only if both sub-expressions were checked.
4433 const AbstractConditionalOperator *C =
4434 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004435
4436 // Determine whether it is necessary to check both sub-expressions, for
4437 // example, because the condition expression is a constant that can be
4438 // evaluated at compile time.
4439 bool CheckLeft = true, CheckRight = true;
4440
4441 bool Cond;
4442 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4443 if (Cond)
4444 CheckRight = false;
4445 else
4446 CheckLeft = false;
4447 }
4448
Stephen Hines648c3692016-09-16 01:07:04 +00004449 // We need to maintain the offsets for the right and the left hand side
4450 // separately to check if every possible indexed expression is a valid
4451 // string literal. They might have different offsets for different string
4452 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004453 StringLiteralCheckType Left;
4454 if (!CheckLeft)
4455 Left = SLCT_UncheckedLiteral;
4456 else {
4457 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4458 HasVAListArg, format_idx, firstDataArg,
4459 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004460 CheckedVarArgs, UncoveredArg, Offset);
4461 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004462 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004463 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004464 }
4465
Richard Smith55ce3522012-06-25 20:30:08 +00004466 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004467 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004468 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004469 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004470 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004471
4472 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004473 }
4474
4475 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004476 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4477 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004478 }
4479
John McCallc07a0c72011-02-17 10:25:35 +00004480 case Stmt::OpaqueValueExprClass:
4481 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4482 E = src;
4483 goto tryAgain;
4484 }
Richard Smith55ce3522012-06-25 20:30:08 +00004485 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004486
Ted Kremeneka8890832011-02-24 23:03:04 +00004487 case Stmt::PredefinedExprClass:
4488 // While __func__, etc., are technically not string literals, they
4489 // cannot contain format specifiers and thus are not a security
4490 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004491 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004492
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004493 case Stmt::DeclRefExprClass: {
4494 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004495
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004496 // As an exception, do not flag errors for variables binding to
4497 // const string literals.
4498 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4499 bool isConstant = false;
4500 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004501
Richard Smithd7293d72013-08-05 18:49:43 +00004502 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4503 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004504 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004505 isConstant = T.isConstant(S.Context) &&
4506 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004507 } else if (T->isObjCObjectPointerType()) {
4508 // In ObjC, there is usually no "const ObjectPointer" type,
4509 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004510 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004511 }
Mike Stump11289f42009-09-09 15:08:12 +00004512
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004513 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004514 if (const Expr *Init = VD->getAnyInitializer()) {
4515 // Look through initializers like const char c[] = { "foo" }
4516 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4517 if (InitList->isStringLiteralInit())
4518 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4519 }
Richard Smithd7293d72013-08-05 18:49:43 +00004520 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004521 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004522 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004523 /*InFunctionCall*/ false, CheckedVarArgs,
4524 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004525 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004526 }
Mike Stump11289f42009-09-09 15:08:12 +00004527
Anders Carlssonb012ca92009-06-28 19:55:58 +00004528 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4529 // special check to see if the format string is a function parameter
4530 // of the function calling the printf function. If the function
4531 // has an attribute indicating it is a printf-like function, then we
4532 // should suppress warnings concerning non-literals being used in a call
4533 // to a vprintf function. For example:
4534 //
4535 // void
4536 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4537 // va_list ap;
4538 // va_start(ap, fmt);
4539 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4540 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004541 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004542 if (HasVAListArg) {
4543 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4544 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4545 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004546 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004547 // adjust for implicit parameter
4548 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4549 if (MD->isInstance())
4550 ++PVIndex;
4551 // We also check if the formats are compatible.
4552 // We can't pass a 'scanf' string to a 'printf' function.
4553 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004554 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004555 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004556 }
4557 }
4558 }
4559 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004560 }
Mike Stump11289f42009-09-09 15:08:12 +00004561
Richard Smith55ce3522012-06-25 20:30:08 +00004562 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004563 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004564
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004565 case Stmt::CallExprClass:
4566 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004567 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004568 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4569 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4570 unsigned ArgIndex = FA->getFormatIdx();
4571 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4572 if (MD->isInstance())
4573 --ArgIndex;
4574 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004575
Richard Smithd7293d72013-08-05 18:49:43 +00004576 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004577 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004578 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004579 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004580 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4581 unsigned BuiltinID = FD->getBuiltinID();
4582 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4583 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4584 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004585 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004586 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004587 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004588 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004589 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004590 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004591 }
4592 }
Mike Stump11289f42009-09-09 15:08:12 +00004593
Richard Smith55ce3522012-06-25 20:30:08 +00004594 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004595 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004596 case Stmt::ObjCMessageExprClass: {
4597 const auto *ME = cast<ObjCMessageExpr>(E);
4598 if (const auto *ND = ME->getMethodDecl()) {
4599 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4600 unsigned ArgIndex = FA->getFormatIdx();
4601 const Expr *Arg = ME->getArg(ArgIndex - 1);
4602 return checkFormatStringExpr(
4603 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4604 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4605 }
4606 }
4607
4608 return SLCT_NotALiteral;
4609 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004610 case Stmt::ObjCStringLiteralClass:
4611 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004612 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004613
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004614 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004615 StrE = ObjCFExpr->getString();
4616 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004617 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004618
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004619 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004620 if (Offset.isNegative() || Offset > StrE->getLength()) {
4621 // TODO: It would be better to have an explicit warning for out of
4622 // bounds literals.
4623 return SLCT_NotALiteral;
4624 }
4625 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4626 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004627 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004628 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004629 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004630 }
Mike Stump11289f42009-09-09 15:08:12 +00004631
Richard Smith55ce3522012-06-25 20:30:08 +00004632 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004633 }
Stephen Hines648c3692016-09-16 01:07:04 +00004634 case Stmt::BinaryOperatorClass: {
4635 llvm::APSInt LResult;
4636 llvm::APSInt RResult;
4637
4638 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4639
4640 // A string literal + an int offset is still a string literal.
4641 if (BinOp->isAdditiveOp()) {
4642 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4643 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4644
4645 if (LIsInt != RIsInt) {
4646 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4647
4648 if (LIsInt) {
4649 if (BinOpKind == BO_Add) {
4650 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4651 E = BinOp->getRHS();
4652 goto tryAgain;
4653 }
4654 } else {
4655 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4656 E = BinOp->getLHS();
4657 goto tryAgain;
4658 }
4659 }
Stephen Hines648c3692016-09-16 01:07:04 +00004660 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004661
4662 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004663 }
4664 case Stmt::UnaryOperatorClass: {
4665 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4666 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4667 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4668 llvm::APSInt IndexResult;
4669 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4670 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4671 E = ASE->getBase();
4672 goto tryAgain;
4673 }
4674 }
4675
4676 return SLCT_NotALiteral;
4677 }
Mike Stump11289f42009-09-09 15:08:12 +00004678
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004679 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004680 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004681 }
4682}
4683
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004684Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004685 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004686 .Case("scanf", FST_Scanf)
4687 .Cases("printf", "printf0", FST_Printf)
4688 .Cases("NSString", "CFString", FST_NSString)
4689 .Case("strftime", FST_Strftime)
4690 .Case("strfmon", FST_Strfmon)
4691 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4692 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4693 .Case("os_trace", FST_OSLog)
4694 .Case("os_log", FST_OSLog)
4695 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004696}
4697
Jordan Rose3e0ec582012-07-19 18:10:23 +00004698/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004699/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004700/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004701bool Sema::CheckFormatArguments(const FormatAttr *Format,
4702 ArrayRef<const Expr *> Args,
4703 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004704 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004705 SourceLocation Loc, SourceRange Range,
4706 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004707 FormatStringInfo FSI;
4708 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004709 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004710 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004711 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004712 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004713}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004714
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004715bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004716 bool HasVAListArg, unsigned format_idx,
4717 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004718 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004719 SourceLocation Loc, SourceRange Range,
4720 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004721 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004722 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004723 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004724 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004725 }
Mike Stump11289f42009-09-09 15:08:12 +00004726
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004727 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004728
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004729 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004730 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004731 // Dynamically generated format strings are difficult to
4732 // automatically vet at compile time. Requiring that format strings
4733 // are string literals: (1) permits the checking of format strings by
4734 // the compiler and thereby (2) can practically remove the source of
4735 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004736
Mike Stump11289f42009-09-09 15:08:12 +00004737 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004738 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004739 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004740 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004741 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004742 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004743 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4744 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004745 /*IsFunctionCall*/ true, CheckedVarArgs,
4746 UncoveredArg,
4747 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004748
4749 // Generate a diagnostic where an uncovered argument is detected.
4750 if (UncoveredArg.hasUncoveredArg()) {
4751 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4752 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4753 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4754 }
4755
Richard Smith55ce3522012-06-25 20:30:08 +00004756 if (CT != SLCT_NotALiteral)
4757 // Literal format string found, check done!
4758 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004759
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004760 // Strftime is particular as it always uses a single 'time' argument,
4761 // so it is safe to pass a non-literal string.
4762 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004763 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004764
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004765 // Do not emit diag when the string param is a macro expansion and the
4766 // format is either NSString or CFString. This is a hack to prevent
4767 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4768 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004769 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4770 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004771 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004772
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004773 // If there are no arguments specified, warn with -Wformat-security, otherwise
4774 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004775 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004776 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4777 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004778 switch (Type) {
4779 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004780 break;
4781 case FST_Kprintf:
4782 case FST_FreeBSDKPrintf:
4783 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004784 Diag(FormatLoc, diag::note_format_security_fixit)
4785 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004786 break;
4787 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004788 Diag(FormatLoc, diag::note_format_security_fixit)
4789 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004790 break;
4791 }
4792 } else {
4793 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004794 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004795 }
Richard Smith55ce3522012-06-25 20:30:08 +00004796 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004797}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004798
Ted Kremenekab278de2010-01-28 23:39:18 +00004799namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00004800class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4801protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00004802 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00004803 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00004804 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00004805 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00004806 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00004807 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00004808 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00004809 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004810 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00004811 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00004812 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00004813 bool usesPositionalArgs;
4814 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00004815 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00004816 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00004817 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004818 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004819
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004820public:
Stephen Hines648c3692016-09-16 01:07:04 +00004821 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004822 const Expr *origFormatExpr,
4823 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004824 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00004825 ArrayRef<const Expr *> Args, unsigned formatIdx,
4826 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004827 llvm::SmallBitVector &CheckedVarArgs,
4828 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00004829 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
4830 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
4831 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
4832 usesPositionalArgs(false), atFirstArg(true),
4833 inFunctionCall(inFunctionCall), CallType(callType),
4834 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00004835 CoveredArgs.resize(numDataArgs);
4836 CoveredArgs.reset();
4837 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004838
Ted Kremenek019d2242010-01-29 01:50:07 +00004839 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004840
Ted Kremenek02087932010-07-16 02:11:22 +00004841 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004842 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004843
Jordan Rose92303592012-09-08 04:00:03 +00004844 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004845 const analyze_format_string::FormatSpecifier &FS,
4846 const analyze_format_string::ConversionSpecifier &CS,
4847 const char *startSpecifier, unsigned specifierLen,
4848 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00004849
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004850 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004851 const analyze_format_string::FormatSpecifier &FS,
4852 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004853
4854 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00004855 const analyze_format_string::ConversionSpecifier &CS,
4856 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004857
Craig Toppere14c0f82014-03-12 04:55:44 +00004858 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00004859
Craig Toppere14c0f82014-03-12 04:55:44 +00004860 void HandleInvalidPosition(const char *startSpecifier,
4861 unsigned specifierLen,
4862 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004863
Craig Toppere14c0f82014-03-12 04:55:44 +00004864 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00004865
Craig Toppere14c0f82014-03-12 04:55:44 +00004866 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004867
Richard Trieu03cf7b72011-10-28 00:41:25 +00004868 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00004869 static void
4870 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4871 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4872 bool IsStringLocation, Range StringRange,
4873 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004874
Ted Kremenek02087932010-07-16 02:11:22 +00004875protected:
Ted Kremenekce815422010-07-19 21:25:57 +00004876 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4877 const char *startSpec,
4878 unsigned specifierLen,
4879 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004880
4881 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4882 const char *startSpec,
4883 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00004884
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004885 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00004886 CharSourceRange getSpecifierRange(const char *startSpecifier,
4887 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00004888 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004889
Ted Kremenek5739de72010-01-29 01:06:55 +00004890 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004891
4892 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4893 const analyze_format_string::ConversionSpecifier &CS,
4894 const char *startSpecifier, unsigned specifierLen,
4895 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00004896
4897 template <typename Range>
4898 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4899 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004900 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00004901};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004902} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004903
Ted Kremenek02087932010-07-16 02:11:22 +00004904SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00004905 return OrigFormatExpr->getSourceRange();
4906}
4907
Ted Kremenek02087932010-07-16 02:11:22 +00004908CharSourceRange CheckFormatHandler::
4909getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00004910 SourceLocation Start = getLocationOfByte(startSpecifier);
4911 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
4912
4913 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004914 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00004915
4916 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004917}
4918
Ted Kremenek02087932010-07-16 02:11:22 +00004919SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00004920 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4921 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00004922}
4923
Ted Kremenek02087932010-07-16 02:11:22 +00004924void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4925 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00004926 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4927 getLocationOfByte(startSpecifier),
4928 /*IsStringLocation*/true,
4929 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00004930}
4931
Jordan Rose92303592012-09-08 04:00:03 +00004932void CheckFormatHandler::HandleInvalidLengthModifier(
4933 const analyze_format_string::FormatSpecifier &FS,
4934 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00004935 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00004936 using namespace analyze_format_string;
4937
4938 const LengthModifier &LM = FS.getLengthModifier();
4939 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4940
4941 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004942 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00004943 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004944 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004945 getLocationOfByte(LM.getStart()),
4946 /*IsStringLocation*/true,
4947 getSpecifierRange(startSpecifier, specifierLen));
4948
4949 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4950 << FixedLM->toString()
4951 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4952
4953 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004954 FixItHint Hint;
4955 if (DiagID == diag::warn_format_nonsensical_length)
4956 Hint = FixItHint::CreateRemoval(LMRange);
4957
4958 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00004959 getLocationOfByte(LM.getStart()),
4960 /*IsStringLocation*/true,
4961 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00004962 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00004963 }
4964}
4965
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004966void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00004967 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004968 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00004969 using namespace analyze_format_string;
4970
4971 const LengthModifier &LM = FS.getLengthModifier();
4972 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4973
4974 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00004975 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00004976 if (FixedLM) {
4977 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4978 << LM.toString() << 0,
4979 getLocationOfByte(LM.getStart()),
4980 /*IsStringLocation*/true,
4981 getSpecifierRange(startSpecifier, specifierLen));
4982
4983 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4984 << FixedLM->toString()
4985 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4986
4987 } else {
4988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4989 << LM.toString() << 0,
4990 getLocationOfByte(LM.getStart()),
4991 /*IsStringLocation*/true,
4992 getSpecifierRange(startSpecifier, specifierLen));
4993 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004994}
4995
4996void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4997 const analyze_format_string::ConversionSpecifier &CS,
4998 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00004999 using namespace analyze_format_string;
5000
5001 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005002 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005003 if (FixedCS) {
5004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5005 << CS.toString() << /*conversion specifier*/1,
5006 getLocationOfByte(CS.getStart()),
5007 /*IsStringLocation*/true,
5008 getSpecifierRange(startSpecifier, specifierLen));
5009
5010 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5011 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5012 << FixedCS->toString()
5013 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5014 } else {
5015 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5016 << CS.toString() << /*conversion specifier*/1,
5017 getLocationOfByte(CS.getStart()),
5018 /*IsStringLocation*/true,
5019 getSpecifierRange(startSpecifier, specifierLen));
5020 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005021}
5022
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005023void CheckFormatHandler::HandlePosition(const char *startPos,
5024 unsigned posLen) {
5025 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5026 getLocationOfByte(startPos),
5027 /*IsStringLocation*/true,
5028 getSpecifierRange(startPos, posLen));
5029}
5030
Ted Kremenekd1668192010-02-27 01:41:03 +00005031void
Ted Kremenek02087932010-07-16 02:11:22 +00005032CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5033 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5035 << (unsigned) p,
5036 getLocationOfByte(startPos), /*IsStringLocation*/true,
5037 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005038}
5039
Ted Kremenek02087932010-07-16 02:11:22 +00005040void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005041 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005042 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5043 getLocationOfByte(startPos),
5044 /*IsStringLocation*/true,
5045 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005046}
5047
Ted Kremenek02087932010-07-16 02:11:22 +00005048void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005049 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005050 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005051 EmitFormatDiagnostic(
5052 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5053 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5054 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005055 }
Ted Kremenek02087932010-07-16 02:11:22 +00005056}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005057
Jordan Rose58bbe422012-07-19 18:10:08 +00005058// Note that this may return NULL if there was an error parsing or building
5059// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005060const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005061 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005062}
5063
5064void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005065 // Does the number of data arguments exceed the number of
5066 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005067 if (!HasVAListArg) {
5068 // Find any arguments that weren't covered.
5069 CoveredArgs.flip();
5070 signed notCoveredArg = CoveredArgs.find_first();
5071 if (notCoveredArg >= 0) {
5072 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005073 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5074 } else {
5075 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005076 }
5077 }
5078}
5079
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005080void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5081 const Expr *ArgExpr) {
5082 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5083 "Invalid state");
5084
5085 if (!ArgExpr)
5086 return;
5087
5088 SourceLocation Loc = ArgExpr->getLocStart();
5089
5090 if (S.getSourceManager().isInSystemMacro(Loc))
5091 return;
5092
5093 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5094 for (auto E : DiagnosticExprs)
5095 PDiag << E->getSourceRange();
5096
5097 CheckFormatHandler::EmitFormatDiagnostic(
5098 S, IsFunctionCall, DiagnosticExprs[0],
5099 PDiag, Loc, /*IsStringLocation*/false,
5100 DiagnosticExprs[0]->getSourceRange());
5101}
5102
Ted Kremenekce815422010-07-19 21:25:57 +00005103bool
5104CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5105 SourceLocation Loc,
5106 const char *startSpec,
5107 unsigned specifierLen,
5108 const char *csStart,
5109 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005110 bool keepGoing = true;
5111 if (argIndex < NumDataArgs) {
5112 // Consider the argument coverered, even though the specifier doesn't
5113 // make sense.
5114 CoveredArgs.set(argIndex);
5115 }
5116 else {
5117 // If argIndex exceeds the number of data arguments we
5118 // don't issue a warning because that is just a cascade of warnings (and
5119 // they may have intended '%%' anyway). We don't want to continue processing
5120 // the format string after this point, however, as we will like just get
5121 // gibberish when trying to match arguments.
5122 keepGoing = false;
5123 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005124
5125 StringRef Specifier(csStart, csLen);
5126
5127 // If the specifier in non-printable, it could be the first byte of a UTF-8
5128 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5129 // hex value.
5130 std::string CodePointStr;
5131 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005132 llvm::UTF32 CodePoint;
5133 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5134 const llvm::UTF8 *E =
5135 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5136 llvm::ConversionResult Result =
5137 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005138
Justin Lebar90910552016-09-30 00:38:45 +00005139 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005140 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005141 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005142 }
5143
5144 llvm::raw_string_ostream OS(CodePointStr);
5145 if (CodePoint < 256)
5146 OS << "\\x" << llvm::format("%02x", CodePoint);
5147 else if (CodePoint <= 0xFFFF)
5148 OS << "\\u" << llvm::format("%04x", CodePoint);
5149 else
5150 OS << "\\U" << llvm::format("%08x", CodePoint);
5151 OS.flush();
5152 Specifier = CodePointStr;
5153 }
5154
5155 EmitFormatDiagnostic(
5156 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5157 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5158
Ted Kremenekce815422010-07-19 21:25:57 +00005159 return keepGoing;
5160}
5161
Richard Trieu03cf7b72011-10-28 00:41:25 +00005162void
5163CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5164 const char *startSpec,
5165 unsigned specifierLen) {
5166 EmitFormatDiagnostic(
5167 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5168 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5169}
5170
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005171bool
5172CheckFormatHandler::CheckNumArgs(
5173 const analyze_format_string::FormatSpecifier &FS,
5174 const analyze_format_string::ConversionSpecifier &CS,
5175 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5176
5177 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005178 PartialDiagnostic PDiag = FS.usesPositionalArg()
5179 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5180 << (argIndex+1) << NumDataArgs)
5181 : S.PDiag(diag::warn_printf_insufficient_data_args);
5182 EmitFormatDiagnostic(
5183 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5184 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005185
5186 // Since more arguments than conversion tokens are given, by extension
5187 // all arguments are covered, so mark this as so.
5188 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005189 return false;
5190 }
5191 return true;
5192}
5193
Richard Trieu03cf7b72011-10-28 00:41:25 +00005194template<typename Range>
5195void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5196 SourceLocation Loc,
5197 bool IsStringLocation,
5198 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005199 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005200 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005201 Loc, IsStringLocation, StringRange, FixIt);
5202}
5203
5204/// \brief If the format string is not within the funcion call, emit a note
5205/// so that the function call and string are in diagnostic messages.
5206///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005207/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005208/// call and only one diagnostic message will be produced. Otherwise, an
5209/// extra note will be emitted pointing to location of the format string.
5210///
5211/// \param ArgumentExpr the expression that is passed as the format string
5212/// argument in the function call. Used for getting locations when two
5213/// diagnostics are emitted.
5214///
5215/// \param PDiag the callee should already have provided any strings for the
5216/// diagnostic message. This function only adds locations and fixits
5217/// to diagnostics.
5218///
5219/// \param Loc primary location for diagnostic. If two diagnostics are
5220/// required, one will be at Loc and a new SourceLocation will be created for
5221/// the other one.
5222///
5223/// \param IsStringLocation if true, Loc points to the format string should be
5224/// used for the note. Otherwise, Loc points to the argument list and will
5225/// be used with PDiag.
5226///
5227/// \param StringRange some or all of the string to highlight. This is
5228/// templated so it can accept either a CharSourceRange or a SourceRange.
5229///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005230/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005231template <typename Range>
5232void CheckFormatHandler::EmitFormatDiagnostic(
5233 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5234 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5235 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005236 if (InFunctionCall) {
5237 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5238 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005239 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005240 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005241 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5242 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005243
5244 const Sema::SemaDiagnosticBuilder &Note =
5245 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5246 diag::note_format_string_defined);
5247
5248 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005249 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005250 }
5251}
5252
Ted Kremenek02087932010-07-16 02:11:22 +00005253//===--- CHECK: Printf format string checking ------------------------------===//
5254
5255namespace {
5256class CheckPrintfHandler : public CheckFormatHandler {
5257public:
Stephen Hines648c3692016-09-16 01:07:04 +00005258 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005259 const Expr *origFormatExpr,
5260 const Sema::FormatStringType type, unsigned firstDataArg,
5261 unsigned numDataArgs, bool isObjC, const char *beg,
5262 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005263 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005264 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005265 llvm::SmallBitVector &CheckedVarArgs,
5266 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005267 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5268 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5269 inFunctionCall, CallType, CheckedVarArgs,
5270 UncoveredArg) {}
5271
5272 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5273
5274 /// Returns true if '%@' specifiers are allowed in the format string.
5275 bool allowsObjCArg() const {
5276 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5277 FSType == Sema::FST_OSTrace;
5278 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005279
Ted Kremenek02087932010-07-16 02:11:22 +00005280 bool HandleInvalidPrintfConversionSpecifier(
5281 const analyze_printf::PrintfSpecifier &FS,
5282 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005283 unsigned specifierLen) override;
5284
Ted Kremenek02087932010-07-16 02:11:22 +00005285 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5286 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005287 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005288 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5289 const char *StartSpecifier,
5290 unsigned SpecifierLen,
5291 const Expr *E);
5292
Ted Kremenek02087932010-07-16 02:11:22 +00005293 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5294 const char *startSpecifier, unsigned specifierLen);
5295 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5296 const analyze_printf::OptionalAmount &Amt,
5297 unsigned type,
5298 const char *startSpecifier, unsigned specifierLen);
5299 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5300 const analyze_printf::OptionalFlag &flag,
5301 const char *startSpecifier, unsigned specifierLen);
5302 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5303 const analyze_printf::OptionalFlag &ignoredFlag,
5304 const analyze_printf::OptionalFlag &flag,
5305 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005306 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005307 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005308
5309 void HandleEmptyObjCModifierFlag(const char *startFlag,
5310 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005311
Ted Kremenek2b417712015-07-02 05:39:16 +00005312 void HandleInvalidObjCModifierFlag(const char *startFlag,
5313 unsigned flagLen) override;
5314
5315 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5316 const char *flagsEnd,
5317 const char *conversionPosition)
5318 override;
5319};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005320} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005321
5322bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5323 const analyze_printf::PrintfSpecifier &FS,
5324 const char *startSpecifier,
5325 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005326 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005327 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005328
Ted Kremenekce815422010-07-19 21:25:57 +00005329 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5330 getLocationOfByte(CS.getStart()),
5331 startSpecifier, specifierLen,
5332 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005333}
5334
Ted Kremenek02087932010-07-16 02:11:22 +00005335bool CheckPrintfHandler::HandleAmount(
5336 const analyze_format_string::OptionalAmount &Amt,
5337 unsigned k, const char *startSpecifier,
5338 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005339 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005340 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005341 unsigned argIndex = Amt.getArgIndex();
5342 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005343 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5344 << k,
5345 getLocationOfByte(Amt.getStart()),
5346 /*IsStringLocation*/true,
5347 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005348 // Don't do any more checking. We will just emit
5349 // spurious errors.
5350 return false;
5351 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005352
Ted Kremenek5739de72010-01-29 01:06:55 +00005353 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005354 // Although not in conformance with C99, we also allow the argument to be
5355 // an 'unsigned int' as that is a reasonably safe case. GCC also
5356 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005357 CoveredArgs.set(argIndex);
5358 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005359 if (!Arg)
5360 return false;
5361
Ted Kremenek5739de72010-01-29 01:06:55 +00005362 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005363
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005364 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5365 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005366
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005367 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005368 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005369 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005370 << T << Arg->getSourceRange(),
5371 getLocationOfByte(Amt.getStart()),
5372 /*IsStringLocation*/true,
5373 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005374 // Don't do any more checking. We will just emit
5375 // spurious errors.
5376 return false;
5377 }
5378 }
5379 }
5380 return true;
5381}
Ted Kremenek5739de72010-01-29 01:06:55 +00005382
Tom Careb49ec692010-06-17 19:00:27 +00005383void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005384 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005385 const analyze_printf::OptionalAmount &Amt,
5386 unsigned type,
5387 const char *startSpecifier,
5388 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005389 const analyze_printf::PrintfConversionSpecifier &CS =
5390 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005391
Richard Trieu03cf7b72011-10-28 00:41:25 +00005392 FixItHint fixit =
5393 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5394 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5395 Amt.getConstantLength()))
5396 : FixItHint();
5397
5398 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5399 << type << CS.toString(),
5400 getLocationOfByte(Amt.getStart()),
5401 /*IsStringLocation*/true,
5402 getSpecifierRange(startSpecifier, specifierLen),
5403 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005404}
5405
Ted Kremenek02087932010-07-16 02:11:22 +00005406void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005407 const analyze_printf::OptionalFlag &flag,
5408 const char *startSpecifier,
5409 unsigned specifierLen) {
5410 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005411 const analyze_printf::PrintfConversionSpecifier &CS =
5412 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005413 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5414 << flag.toString() << CS.toString(),
5415 getLocationOfByte(flag.getPosition()),
5416 /*IsStringLocation*/true,
5417 getSpecifierRange(startSpecifier, specifierLen),
5418 FixItHint::CreateRemoval(
5419 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005420}
5421
5422void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005423 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005424 const analyze_printf::OptionalFlag &ignoredFlag,
5425 const analyze_printf::OptionalFlag &flag,
5426 const char *startSpecifier,
5427 unsigned specifierLen) {
5428 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005429 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5430 << ignoredFlag.toString() << flag.toString(),
5431 getLocationOfByte(ignoredFlag.getPosition()),
5432 /*IsStringLocation*/true,
5433 getSpecifierRange(startSpecifier, specifierLen),
5434 FixItHint::CreateRemoval(
5435 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005436}
5437
Ted Kremenek2b417712015-07-02 05:39:16 +00005438// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5439// bool IsStringLocation, Range StringRange,
5440// ArrayRef<FixItHint> Fixit = None);
5441
5442void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5443 unsigned flagLen) {
5444 // Warn about an empty flag.
5445 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5446 getLocationOfByte(startFlag),
5447 /*IsStringLocation*/true,
5448 getSpecifierRange(startFlag, flagLen));
5449}
5450
5451void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5452 unsigned flagLen) {
5453 // Warn about an invalid flag.
5454 auto Range = getSpecifierRange(startFlag, flagLen);
5455 StringRef flag(startFlag, flagLen);
5456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5457 getLocationOfByte(startFlag),
5458 /*IsStringLocation*/true,
5459 Range, FixItHint::CreateRemoval(Range));
5460}
5461
5462void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5463 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5464 // Warn about using '[...]' without a '@' conversion.
5465 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5466 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5467 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5468 getLocationOfByte(conversionPosition),
5469 /*IsStringLocation*/true,
5470 Range, FixItHint::CreateRemoval(Range));
5471}
5472
Richard Smith55ce3522012-06-25 20:30:08 +00005473// Determines if the specified is a C++ class or struct containing
5474// a member with the specified name and kind (e.g. a CXXMethodDecl named
5475// "c_str()").
5476template<typename MemberKind>
5477static llvm::SmallPtrSet<MemberKind*, 1>
5478CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5479 const RecordType *RT = Ty->getAs<RecordType>();
5480 llvm::SmallPtrSet<MemberKind*, 1> Results;
5481
5482 if (!RT)
5483 return Results;
5484 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005485 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005486 return Results;
5487
Alp Tokerb6cc5922014-05-03 03:45:55 +00005488 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005489 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005490 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005491
5492 // We just need to include all members of the right kind turned up by the
5493 // filter, at this point.
5494 if (S.LookupQualifiedName(R, RT->getDecl()))
5495 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5496 NamedDecl *decl = (*I)->getUnderlyingDecl();
5497 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5498 Results.insert(FK);
5499 }
5500 return Results;
5501}
5502
Richard Smith2868a732014-02-28 01:36:39 +00005503/// Check if we could call '.c_str()' on an object.
5504///
5505/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5506/// allow the call, or if it would be ambiguous).
5507bool Sema::hasCStrMethod(const Expr *E) {
5508 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5509 MethodSet Results =
5510 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5511 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5512 MI != ME; ++MI)
5513 if ((*MI)->getMinRequiredArguments() == 0)
5514 return true;
5515 return false;
5516}
5517
Richard Smith55ce3522012-06-25 20:30:08 +00005518// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005519// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005520// Returns true when a c_str() conversion method is found.
5521bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005522 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005523 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5524
5525 MethodSet Results =
5526 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5527
5528 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5529 MI != ME; ++MI) {
5530 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005531 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005532 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005533 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005534 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005535 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5536 << "c_str()"
5537 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5538 return true;
5539 }
5540 }
5541
5542 return false;
5543}
5544
Ted Kremenekab278de2010-01-28 23:39:18 +00005545bool
Ted Kremenek02087932010-07-16 02:11:22 +00005546CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005547 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005548 const char *startSpecifier,
5549 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005550 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005551 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005552 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005553
Ted Kremenek6cd69422010-07-19 22:01:06 +00005554 if (FS.consumesDataArgument()) {
5555 if (atFirstArg) {
5556 atFirstArg = false;
5557 usesPositionalArgs = FS.usesPositionalArg();
5558 }
5559 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005560 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5561 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005562 return false;
5563 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005564 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005565
Ted Kremenekd1668192010-02-27 01:41:03 +00005566 // First check if the field width, precision, and conversion specifier
5567 // have matching data arguments.
5568 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5569 startSpecifier, specifierLen)) {
5570 return false;
5571 }
5572
5573 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5574 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005575 return false;
5576 }
5577
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005578 if (!CS.consumesDataArgument()) {
5579 // FIXME: Technically specifying a precision or field width here
5580 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005581 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005582 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005583
Ted Kremenek4a49d982010-02-26 19:18:41 +00005584 // Consume the argument.
5585 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005586 if (argIndex < NumDataArgs) {
5587 // The check to see if the argIndex is valid will come later.
5588 // We set the bit here because we may exit early from this
5589 // function if we encounter some other error.
5590 CoveredArgs.set(argIndex);
5591 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005592
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005593 // FreeBSD kernel extensions.
5594 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5595 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5596 // We need at least two arguments.
5597 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5598 return false;
5599
5600 // Claim the second argument.
5601 CoveredArgs.set(argIndex + 1);
5602
5603 // Type check the first argument (int for %b, pointer for %D)
5604 const Expr *Ex = getDataArg(argIndex);
5605 const analyze_printf::ArgType &AT =
5606 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5607 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5608 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5609 EmitFormatDiagnostic(
5610 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5611 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5612 << false << Ex->getSourceRange(),
5613 Ex->getLocStart(), /*IsStringLocation*/false,
5614 getSpecifierRange(startSpecifier, specifierLen));
5615
5616 // Type check the second argument (char * for both %b and %D)
5617 Ex = getDataArg(argIndex + 1);
5618 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5619 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5620 EmitFormatDiagnostic(
5621 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5622 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5623 << false << Ex->getSourceRange(),
5624 Ex->getLocStart(), /*IsStringLocation*/false,
5625 getSpecifierRange(startSpecifier, specifierLen));
5626
5627 return true;
5628 }
5629
Ted Kremenek4a49d982010-02-26 19:18:41 +00005630 // Check for using an Objective-C specific conversion specifier
5631 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005632 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005633 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5634 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005635 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005636
Mehdi Amini06d367c2016-10-24 20:39:34 +00005637 // %P can only be used with os_log.
5638 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5639 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5640 specifierLen);
5641 }
5642
5643 // %n is not allowed with os_log.
5644 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5645 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5646 getLocationOfByte(CS.getStart()),
5647 /*IsStringLocation*/ false,
5648 getSpecifierRange(startSpecifier, specifierLen));
5649
5650 return true;
5651 }
5652
5653 // Only scalars are allowed for os_trace.
5654 if (FSType == Sema::FST_OSTrace &&
5655 (CS.getKind() == ConversionSpecifier::PArg ||
5656 CS.getKind() == ConversionSpecifier::sArg ||
5657 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5658 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5659 specifierLen);
5660 }
5661
5662 // Check for use of public/private annotation outside of os_log().
5663 if (FSType != Sema::FST_OSLog) {
5664 if (FS.isPublic().isSet()) {
5665 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5666 << "public",
5667 getLocationOfByte(FS.isPublic().getPosition()),
5668 /*IsStringLocation*/ false,
5669 getSpecifierRange(startSpecifier, specifierLen));
5670 }
5671 if (FS.isPrivate().isSet()) {
5672 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5673 << "private",
5674 getLocationOfByte(FS.isPrivate().getPosition()),
5675 /*IsStringLocation*/ false,
5676 getSpecifierRange(startSpecifier, specifierLen));
5677 }
5678 }
5679
Tom Careb49ec692010-06-17 19:00:27 +00005680 // Check for invalid use of field width
5681 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005682 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005683 startSpecifier, specifierLen);
5684 }
5685
5686 // Check for invalid use of precision
5687 if (!FS.hasValidPrecision()) {
5688 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5689 startSpecifier, specifierLen);
5690 }
5691
Mehdi Amini06d367c2016-10-24 20:39:34 +00005692 // Precision is mandatory for %P specifier.
5693 if (CS.getKind() == ConversionSpecifier::PArg &&
5694 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5695 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5696 getLocationOfByte(startSpecifier),
5697 /*IsStringLocation*/ false,
5698 getSpecifierRange(startSpecifier, specifierLen));
5699 }
5700
Tom Careb49ec692010-06-17 19:00:27 +00005701 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005702 if (!FS.hasValidThousandsGroupingPrefix())
5703 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005704 if (!FS.hasValidLeadingZeros())
5705 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5706 if (!FS.hasValidPlusPrefix())
5707 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005708 if (!FS.hasValidSpacePrefix())
5709 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005710 if (!FS.hasValidAlternativeForm())
5711 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5712 if (!FS.hasValidLeftJustified())
5713 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5714
5715 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005716 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5717 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5718 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005719 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5720 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5721 startSpecifier, specifierLen);
5722
5723 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005724 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005725 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5726 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005727 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005728 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005729 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005730 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5731 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005732
Jordan Rose92303592012-09-08 04:00:03 +00005733 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5734 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5735
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005736 // The remaining checks depend on the data arguments.
5737 if (HasVAListArg)
5738 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005739
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005740 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005741 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005742
Jordan Rose58bbe422012-07-19 18:10:08 +00005743 const Expr *Arg = getDataArg(argIndex);
5744 if (!Arg)
5745 return true;
5746
5747 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005748}
5749
Jordan Roseaee34382012-09-05 22:56:26 +00005750static bool requiresParensToAddCast(const Expr *E) {
5751 // FIXME: We should have a general way to reason about operator
5752 // precedence and whether parens are actually needed here.
5753 // Take care of a few common cases where they aren't.
5754 const Expr *Inside = E->IgnoreImpCasts();
5755 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5756 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5757
5758 switch (Inside->getStmtClass()) {
5759 case Stmt::ArraySubscriptExprClass:
5760 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005761 case Stmt::CharacterLiteralClass:
5762 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005763 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005764 case Stmt::FloatingLiteralClass:
5765 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005766 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005767 case Stmt::ObjCArrayLiteralClass:
5768 case Stmt::ObjCBoolLiteralExprClass:
5769 case Stmt::ObjCBoxedExprClass:
5770 case Stmt::ObjCDictionaryLiteralClass:
5771 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005772 case Stmt::ObjCIvarRefExprClass:
5773 case Stmt::ObjCMessageExprClass:
5774 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005775 case Stmt::ObjCStringLiteralClass:
5776 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005777 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005778 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005779 case Stmt::UnaryOperatorClass:
5780 return false;
5781 default:
5782 return true;
5783 }
5784}
5785
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005786static std::pair<QualType, StringRef>
5787shouldNotPrintDirectly(const ASTContext &Context,
5788 QualType IntendedTy,
5789 const Expr *E) {
5790 // Use a 'while' to peel off layers of typedefs.
5791 QualType TyTy = IntendedTy;
5792 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5793 StringRef Name = UserTy->getDecl()->getName();
5794 QualType CastTy = llvm::StringSwitch<QualType>(Name)
5795 .Case("NSInteger", Context.LongTy)
5796 .Case("NSUInteger", Context.UnsignedLongTy)
5797 .Case("SInt32", Context.IntTy)
5798 .Case("UInt32", Context.UnsignedIntTy)
5799 .Default(QualType());
5800
5801 if (!CastTy.isNull())
5802 return std::make_pair(CastTy, Name);
5803
5804 TyTy = UserTy->desugar();
5805 }
5806
5807 // Strip parens if necessary.
5808 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5809 return shouldNotPrintDirectly(Context,
5810 PE->getSubExpr()->getType(),
5811 PE->getSubExpr());
5812
5813 // If this is a conditional expression, then its result type is constructed
5814 // via usual arithmetic conversions and thus there might be no necessary
5815 // typedef sugar there. Recurse to operands to check for NSInteger &
5816 // Co. usage condition.
5817 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5818 QualType TrueTy, FalseTy;
5819 StringRef TrueName, FalseName;
5820
5821 std::tie(TrueTy, TrueName) =
5822 shouldNotPrintDirectly(Context,
5823 CO->getTrueExpr()->getType(),
5824 CO->getTrueExpr());
5825 std::tie(FalseTy, FalseName) =
5826 shouldNotPrintDirectly(Context,
5827 CO->getFalseExpr()->getType(),
5828 CO->getFalseExpr());
5829
5830 if (TrueTy == FalseTy)
5831 return std::make_pair(TrueTy, TrueName);
5832 else if (TrueTy.isNull())
5833 return std::make_pair(FalseTy, FalseName);
5834 else if (FalseTy.isNull())
5835 return std::make_pair(TrueTy, TrueName);
5836 }
5837
5838 return std::make_pair(QualType(), StringRef());
5839}
5840
Richard Smith55ce3522012-06-25 20:30:08 +00005841bool
5842CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5843 const char *StartSpecifier,
5844 unsigned SpecifierLen,
5845 const Expr *E) {
5846 using namespace analyze_format_string;
5847 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005848 // Now type check the data expression that matches the
5849 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005850 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00005851 if (!AT.isValid())
5852 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00005853
Jordan Rose598ec092012-12-05 18:44:40 +00005854 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00005855 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5856 ExprTy = TET->getUnderlyingExpr()->getType();
5857 }
5858
Seth Cantrellb4802962015-03-04 03:12:10 +00005859 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5860
5861 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00005862 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00005863 }
Jordan Rose98709982012-06-04 22:48:57 +00005864
Jordan Rose22b74712012-09-05 22:56:19 +00005865 // Look through argument promotions for our error message's reported type.
5866 // This includes the integral and floating promotions, but excludes array
5867 // and function pointer decay; seeing that an argument intended to be a
5868 // string has type 'char [6]' is probably more confusing than 'char *'.
5869 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5870 if (ICE->getCastKind() == CK_IntegralCast ||
5871 ICE->getCastKind() == CK_FloatingCast) {
5872 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00005873 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00005874
5875 // Check if we didn't match because of an implicit cast from a 'char'
5876 // or 'short' to an 'int'. This is done because printf is a varargs
5877 // function.
5878 if (ICE->getType() == S.Context.IntTy ||
5879 ICE->getType() == S.Context.UnsignedIntTy) {
5880 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00005881 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00005882 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00005883 }
Jordan Rose98709982012-06-04 22:48:57 +00005884 }
Jordan Rose598ec092012-12-05 18:44:40 +00005885 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5886 // Special case for 'a', which has type 'int' in C.
5887 // Note, however, that we do /not/ want to treat multibyte constants like
5888 // 'MooV' as characters! This form is deprecated but still exists.
5889 if (ExprTy == S.Context.IntTy)
5890 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5891 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00005892 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005893
Jordan Rosebc53ed12014-05-31 04:12:14 +00005894 // Look through enums to their underlying type.
5895 bool IsEnum = false;
5896 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5897 ExprTy = EnumTy->getDecl()->getIntegerType();
5898 IsEnum = true;
5899 }
5900
Jordan Rose0e5badd2012-12-05 18:44:49 +00005901 // %C in an Objective-C context prints a unichar, not a wchar_t.
5902 // If the argument is an integer of some kind, believe the %C and suggest
5903 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00005904 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005905 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00005906 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5907 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5908 !ExprTy->isCharType()) {
5909 // 'unichar' is defined as a typedef of unsigned short, but we should
5910 // prefer using the typedef if it is visible.
5911 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00005912
5913 // While we are here, check if the value is an IntegerLiteral that happens
5914 // to be within the valid range.
5915 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5916 const llvm::APInt &V = IL->getValue();
5917 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5918 return true;
5919 }
5920
Jordan Rose0e5badd2012-12-05 18:44:49 +00005921 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5922 Sema::LookupOrdinaryName);
5923 if (S.LookupName(Result, S.getCurScope())) {
5924 NamedDecl *ND = Result.getFoundDecl();
5925 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5926 if (TD->getUnderlyingType() == IntendedTy)
5927 IntendedTy = S.Context.getTypedefType(TD);
5928 }
5929 }
5930 }
5931
5932 // Special-case some of Darwin's platform-independence types by suggesting
5933 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005934 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00005935 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005936 QualType CastTy;
5937 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5938 if (!CastTy.isNull()) {
5939 IntendedTy = CastTy;
5940 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00005941 }
5942 }
5943
Jordan Rose22b74712012-09-05 22:56:19 +00005944 // We may be able to offer a FixItHint if it is a supported type.
5945 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005946 bool success =
5947 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005948
Jordan Rose22b74712012-09-05 22:56:19 +00005949 if (success) {
5950 // Get the fix string from the fixed format specifier
5951 SmallString<16> buf;
5952 llvm::raw_svector_ostream os(buf);
5953 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00005954
Jordan Roseaee34382012-09-05 22:56:26 +00005955 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5956
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005957 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00005958 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5959 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5960 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5961 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00005962 // In this case, the specifier is wrong and should be changed to match
5963 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00005964 EmitFormatDiagnostic(S.PDiag(diag)
5965 << AT.getRepresentativeTypeName(S.Context)
5966 << IntendedTy << IsEnum << E->getSourceRange(),
5967 E->getLocStart(),
5968 /*IsStringLocation*/ false, SpecRange,
5969 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00005970 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00005971 // The canonical type for formatting this value is different from the
5972 // actual type of the expression. (This occurs, for example, with Darwin's
5973 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5974 // should be printed as 'long' for 64-bit compatibility.)
5975 // Rather than emitting a normal format/argument mismatch, we want to
5976 // add a cast to the recommended type (and correct the format string
5977 // if necessary).
5978 SmallString<16> CastBuf;
5979 llvm::raw_svector_ostream CastFix(CastBuf);
5980 CastFix << "(";
5981 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5982 CastFix << ")";
5983
5984 SmallVector<FixItHint,4> Hints;
5985 if (!AT.matchesType(S.Context, IntendedTy))
5986 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5987
5988 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5989 // If there's already a cast present, just replace it.
5990 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5991 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5992
5993 } else if (!requiresParensToAddCast(E)) {
5994 // If the expression has high enough precedence,
5995 // just write the C-style cast.
5996 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5997 CastFix.str()));
5998 } else {
5999 // Otherwise, add parens around the expression as well as the cast.
6000 CastFix << "(";
6001 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6002 CastFix.str()));
6003
Alp Tokerb6cc5922014-05-03 03:45:55 +00006004 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006005 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6006 }
6007
Jordan Rose0e5badd2012-12-05 18:44:49 +00006008 if (ShouldNotPrintDirectly) {
6009 // The expression has a type that should not be printed directly.
6010 // We extract the name from the typedef because we don't want to show
6011 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006012 StringRef Name;
6013 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6014 Name = TypedefTy->getDecl()->getName();
6015 else
6016 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006017 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006018 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006019 << E->getSourceRange(),
6020 E->getLocStart(), /*IsStringLocation=*/false,
6021 SpecRange, Hints);
6022 } else {
6023 // In this case, the expression could be printed using a different
6024 // specifier, but we've decided that the specifier is probably correct
6025 // and we should cast instead. Just use the normal warning message.
6026 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006027 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6028 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006029 << E->getSourceRange(),
6030 E->getLocStart(), /*IsStringLocation*/false,
6031 SpecRange, Hints);
6032 }
Jordan Roseaee34382012-09-05 22:56:26 +00006033 }
Jordan Rose22b74712012-09-05 22:56:19 +00006034 } else {
6035 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6036 SpecifierLen);
6037 // Since the warning for passing non-POD types to variadic functions
6038 // was deferred until now, we emit a warning for non-POD
6039 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006040 switch (S.isValidVarArgType(ExprTy)) {
6041 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006042 case Sema::VAK_ValidInCXX11: {
6043 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6044 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6045 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6046 }
Richard Smithd7293d72013-08-05 18:49:43 +00006047
Seth Cantrellb4802962015-03-04 03:12:10 +00006048 EmitFormatDiagnostic(
6049 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6050 << IsEnum << CSR << E->getSourceRange(),
6051 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6052 break;
6053 }
Richard Smithd7293d72013-08-05 18:49:43 +00006054 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006055 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006056 EmitFormatDiagnostic(
6057 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006058 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006059 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006060 << CallType
6061 << AT.getRepresentativeTypeName(S.Context)
6062 << CSR
6063 << E->getSourceRange(),
6064 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006065 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006066 break;
6067
6068 case Sema::VAK_Invalid:
6069 if (ExprTy->isObjCObjectType())
6070 EmitFormatDiagnostic(
6071 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6072 << S.getLangOpts().CPlusPlus11
6073 << ExprTy
6074 << CallType
6075 << AT.getRepresentativeTypeName(S.Context)
6076 << CSR
6077 << E->getSourceRange(),
6078 E->getLocStart(), /*IsStringLocation*/false, CSR);
6079 else
6080 // FIXME: If this is an initializer list, suggest removing the braces
6081 // or inserting a cast to the target type.
6082 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6083 << isa<InitListExpr>(E) << ExprTy << CallType
6084 << AT.getRepresentativeTypeName(S.Context)
6085 << E->getSourceRange();
6086 break;
6087 }
6088
6089 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6090 "format string specifier index out of range");
6091 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006092 }
6093
Ted Kremenekab278de2010-01-28 23:39:18 +00006094 return true;
6095}
6096
Ted Kremenek02087932010-07-16 02:11:22 +00006097//===--- CHECK: Scanf format string checking ------------------------------===//
6098
6099namespace {
6100class CheckScanfHandler : public CheckFormatHandler {
6101public:
Stephen Hines648c3692016-09-16 01:07:04 +00006102 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006103 const Expr *origFormatExpr, Sema::FormatStringType type,
6104 unsigned firstDataArg, unsigned numDataArgs,
6105 const char *beg, bool hasVAListArg,
6106 ArrayRef<const Expr *> Args, unsigned formatIdx,
6107 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006108 llvm::SmallBitVector &CheckedVarArgs,
6109 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006110 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6111 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6112 inFunctionCall, CallType, CheckedVarArgs,
6113 UncoveredArg) {}
6114
Ted Kremenek02087932010-07-16 02:11:22 +00006115 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6116 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006117 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006118
6119 bool HandleInvalidScanfConversionSpecifier(
6120 const analyze_scanf::ScanfSpecifier &FS,
6121 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006122 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006123
Craig Toppere14c0f82014-03-12 04:55:44 +00006124 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006125};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006126} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006127
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006128void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6129 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006130 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6131 getLocationOfByte(end), /*IsStringLocation*/true,
6132 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006133}
6134
Ted Kremenekce815422010-07-19 21:25:57 +00006135bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6136 const analyze_scanf::ScanfSpecifier &FS,
6137 const char *startSpecifier,
6138 unsigned specifierLen) {
6139
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006140 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006141 FS.getConversionSpecifier();
6142
6143 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6144 getLocationOfByte(CS.getStart()),
6145 startSpecifier, specifierLen,
6146 CS.getStart(), CS.getLength());
6147}
6148
Ted Kremenek02087932010-07-16 02:11:22 +00006149bool CheckScanfHandler::HandleScanfSpecifier(
6150 const analyze_scanf::ScanfSpecifier &FS,
6151 const char *startSpecifier,
6152 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006153 using namespace analyze_scanf;
6154 using namespace analyze_format_string;
6155
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006156 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006157
Ted Kremenek6cd69422010-07-19 22:01:06 +00006158 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6159 // be used to decide if we are using positional arguments consistently.
6160 if (FS.consumesDataArgument()) {
6161 if (atFirstArg) {
6162 atFirstArg = false;
6163 usesPositionalArgs = FS.usesPositionalArg();
6164 }
6165 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006166 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6167 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006168 return false;
6169 }
Ted Kremenek02087932010-07-16 02:11:22 +00006170 }
6171
6172 // Check if the field with is non-zero.
6173 const OptionalAmount &Amt = FS.getFieldWidth();
6174 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6175 if (Amt.getConstantAmount() == 0) {
6176 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6177 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006178 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6179 getLocationOfByte(Amt.getStart()),
6180 /*IsStringLocation*/true, R,
6181 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006182 }
6183 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006184
Ted Kremenek02087932010-07-16 02:11:22 +00006185 if (!FS.consumesDataArgument()) {
6186 // FIXME: Technically specifying a precision or field width here
6187 // makes no sense. Worth issuing a warning at some point.
6188 return true;
6189 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006190
Ted Kremenek02087932010-07-16 02:11:22 +00006191 // Consume the argument.
6192 unsigned argIndex = FS.getArgIndex();
6193 if (argIndex < NumDataArgs) {
6194 // The check to see if the argIndex is valid will come later.
6195 // We set the bit here because we may exit early from this
6196 // function if we encounter some other error.
6197 CoveredArgs.set(argIndex);
6198 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006199
Ted Kremenek4407ea42010-07-20 20:04:47 +00006200 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006201 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006202 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6203 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006204 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006205 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006206 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006207 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6208 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006209
Jordan Rose92303592012-09-08 04:00:03 +00006210 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6211 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6212
Ted Kremenek02087932010-07-16 02:11:22 +00006213 // The remaining checks depend on the data arguments.
6214 if (HasVAListArg)
6215 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006216
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006217 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006218 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006219
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006220 // Check that the argument type matches the format specifier.
6221 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006222 if (!Ex)
6223 return true;
6224
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006225 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006226
6227 if (!AT.isValid()) {
6228 return true;
6229 }
6230
Seth Cantrellb4802962015-03-04 03:12:10 +00006231 analyze_format_string::ArgType::MatchKind match =
6232 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006233 if (match == analyze_format_string::ArgType::Match) {
6234 return true;
6235 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006236
Seth Cantrell79340072015-03-04 05:58:08 +00006237 ScanfSpecifier fixedFS = FS;
6238 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6239 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006240
Seth Cantrell79340072015-03-04 05:58:08 +00006241 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6242 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6243 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6244 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006245
Seth Cantrell79340072015-03-04 05:58:08 +00006246 if (success) {
6247 // Get the fix string from the fixed format specifier.
6248 SmallString<128> buf;
6249 llvm::raw_svector_ostream os(buf);
6250 fixedFS.toString(os);
6251
6252 EmitFormatDiagnostic(
6253 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6254 << Ex->getType() << false << Ex->getSourceRange(),
6255 Ex->getLocStart(),
6256 /*IsStringLocation*/ false,
6257 getSpecifierRange(startSpecifier, specifierLen),
6258 FixItHint::CreateReplacement(
6259 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6260 } else {
6261 EmitFormatDiagnostic(S.PDiag(diag)
6262 << AT.getRepresentativeTypeName(S.Context)
6263 << Ex->getType() << false << Ex->getSourceRange(),
6264 Ex->getLocStart(),
6265 /*IsStringLocation*/ false,
6266 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006267 }
6268
Ted Kremenek02087932010-07-16 02:11:22 +00006269 return true;
6270}
6271
Stephen Hines648c3692016-09-16 01:07:04 +00006272static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006273 const Expr *OrigFormatExpr,
6274 ArrayRef<const Expr *> Args,
6275 bool HasVAListArg, unsigned format_idx,
6276 unsigned firstDataArg,
6277 Sema::FormatStringType Type,
6278 bool inFunctionCall,
6279 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006280 llvm::SmallBitVector &CheckedVarArgs,
6281 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006282 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006283 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006284 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006285 S, inFunctionCall, Args[format_idx],
6286 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006287 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006288 return;
6289 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006290
Ted Kremenekab278de2010-01-28 23:39:18 +00006291 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006292 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006293 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006294 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006295 const ConstantArrayType *T =
6296 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006297 assert(T && "String literal not of constant array type!");
6298 size_t TypeSize = T->getSize().getZExtValue();
6299 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006300 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006301
6302 // Emit a warning if the string literal is truncated and does not contain an
6303 // embedded null character.
6304 if (TypeSize <= StrRef.size() &&
6305 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6306 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006307 S, inFunctionCall, Args[format_idx],
6308 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006309 FExpr->getLocStart(),
6310 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6311 return;
6312 }
6313
Ted Kremenekab278de2010-01-28 23:39:18 +00006314 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006315 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006316 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006317 S, inFunctionCall, Args[format_idx],
6318 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006319 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006320 return;
6321 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006322
6323 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006324 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6325 Type == Sema::FST_OSTrace) {
6326 CheckPrintfHandler H(
6327 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6328 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6329 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6330 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006331
Hans Wennborg23926bd2011-12-15 10:25:47 +00006332 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006333 S.getLangOpts(),
6334 S.Context.getTargetInfo(),
6335 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006336 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006337 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006338 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6339 numDataArgs, Str, HasVAListArg, Args, format_idx,
6340 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006341
Hans Wennborg23926bd2011-12-15 10:25:47 +00006342 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006343 S.getLangOpts(),
6344 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006345 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006346 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006347}
6348
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006349bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6350 // Str - The format string. NOTE: this is NOT null-terminated!
6351 StringRef StrRef = FExpr->getString();
6352 const char *Str = StrRef.data();
6353 // Account for cases where the string literal is truncated in a declaration.
6354 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6355 assert(T && "String literal not of constant array type!");
6356 size_t TypeSize = T->getSize().getZExtValue();
6357 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6358 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6359 getLangOpts(),
6360 Context.getTargetInfo());
6361}
6362
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006363//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6364
6365// Returns the related absolute value function that is larger, of 0 if one
6366// does not exist.
6367static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6368 switch (AbsFunction) {
6369 default:
6370 return 0;
6371
6372 case Builtin::BI__builtin_abs:
6373 return Builtin::BI__builtin_labs;
6374 case Builtin::BI__builtin_labs:
6375 return Builtin::BI__builtin_llabs;
6376 case Builtin::BI__builtin_llabs:
6377 return 0;
6378
6379 case Builtin::BI__builtin_fabsf:
6380 return Builtin::BI__builtin_fabs;
6381 case Builtin::BI__builtin_fabs:
6382 return Builtin::BI__builtin_fabsl;
6383 case Builtin::BI__builtin_fabsl:
6384 return 0;
6385
6386 case Builtin::BI__builtin_cabsf:
6387 return Builtin::BI__builtin_cabs;
6388 case Builtin::BI__builtin_cabs:
6389 return Builtin::BI__builtin_cabsl;
6390 case Builtin::BI__builtin_cabsl:
6391 return 0;
6392
6393 case Builtin::BIabs:
6394 return Builtin::BIlabs;
6395 case Builtin::BIlabs:
6396 return Builtin::BIllabs;
6397 case Builtin::BIllabs:
6398 return 0;
6399
6400 case Builtin::BIfabsf:
6401 return Builtin::BIfabs;
6402 case Builtin::BIfabs:
6403 return Builtin::BIfabsl;
6404 case Builtin::BIfabsl:
6405 return 0;
6406
6407 case Builtin::BIcabsf:
6408 return Builtin::BIcabs;
6409 case Builtin::BIcabs:
6410 return Builtin::BIcabsl;
6411 case Builtin::BIcabsl:
6412 return 0;
6413 }
6414}
6415
6416// Returns the argument type of the absolute value function.
6417static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6418 unsigned AbsType) {
6419 if (AbsType == 0)
6420 return QualType();
6421
6422 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6423 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6424 if (Error != ASTContext::GE_None)
6425 return QualType();
6426
6427 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6428 if (!FT)
6429 return QualType();
6430
6431 if (FT->getNumParams() != 1)
6432 return QualType();
6433
6434 return FT->getParamType(0);
6435}
6436
6437// Returns the best absolute value function, or zero, based on type and
6438// current absolute value function.
6439static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6440 unsigned AbsFunctionKind) {
6441 unsigned BestKind = 0;
6442 uint64_t ArgSize = Context.getTypeSize(ArgType);
6443 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6444 Kind = getLargerAbsoluteValueFunction(Kind)) {
6445 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6446 if (Context.getTypeSize(ParamType) >= ArgSize) {
6447 if (BestKind == 0)
6448 BestKind = Kind;
6449 else if (Context.hasSameType(ParamType, ArgType)) {
6450 BestKind = Kind;
6451 break;
6452 }
6453 }
6454 }
6455 return BestKind;
6456}
6457
6458enum AbsoluteValueKind {
6459 AVK_Integer,
6460 AVK_Floating,
6461 AVK_Complex
6462};
6463
6464static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6465 if (T->isIntegralOrEnumerationType())
6466 return AVK_Integer;
6467 if (T->isRealFloatingType())
6468 return AVK_Floating;
6469 if (T->isAnyComplexType())
6470 return AVK_Complex;
6471
6472 llvm_unreachable("Type not integer, floating, or complex");
6473}
6474
6475// Changes the absolute value function to a different type. Preserves whether
6476// the function is a builtin.
6477static unsigned changeAbsFunction(unsigned AbsKind,
6478 AbsoluteValueKind ValueKind) {
6479 switch (ValueKind) {
6480 case AVK_Integer:
6481 switch (AbsKind) {
6482 default:
6483 return 0;
6484 case Builtin::BI__builtin_fabsf:
6485 case Builtin::BI__builtin_fabs:
6486 case Builtin::BI__builtin_fabsl:
6487 case Builtin::BI__builtin_cabsf:
6488 case Builtin::BI__builtin_cabs:
6489 case Builtin::BI__builtin_cabsl:
6490 return Builtin::BI__builtin_abs;
6491 case Builtin::BIfabsf:
6492 case Builtin::BIfabs:
6493 case Builtin::BIfabsl:
6494 case Builtin::BIcabsf:
6495 case Builtin::BIcabs:
6496 case Builtin::BIcabsl:
6497 return Builtin::BIabs;
6498 }
6499 case AVK_Floating:
6500 switch (AbsKind) {
6501 default:
6502 return 0;
6503 case Builtin::BI__builtin_abs:
6504 case Builtin::BI__builtin_labs:
6505 case Builtin::BI__builtin_llabs:
6506 case Builtin::BI__builtin_cabsf:
6507 case Builtin::BI__builtin_cabs:
6508 case Builtin::BI__builtin_cabsl:
6509 return Builtin::BI__builtin_fabsf;
6510 case Builtin::BIabs:
6511 case Builtin::BIlabs:
6512 case Builtin::BIllabs:
6513 case Builtin::BIcabsf:
6514 case Builtin::BIcabs:
6515 case Builtin::BIcabsl:
6516 return Builtin::BIfabsf;
6517 }
6518 case AVK_Complex:
6519 switch (AbsKind) {
6520 default:
6521 return 0;
6522 case Builtin::BI__builtin_abs:
6523 case Builtin::BI__builtin_labs:
6524 case Builtin::BI__builtin_llabs:
6525 case Builtin::BI__builtin_fabsf:
6526 case Builtin::BI__builtin_fabs:
6527 case Builtin::BI__builtin_fabsl:
6528 return Builtin::BI__builtin_cabsf;
6529 case Builtin::BIabs:
6530 case Builtin::BIlabs:
6531 case Builtin::BIllabs:
6532 case Builtin::BIfabsf:
6533 case Builtin::BIfabs:
6534 case Builtin::BIfabsl:
6535 return Builtin::BIcabsf;
6536 }
6537 }
6538 llvm_unreachable("Unable to convert function");
6539}
6540
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006541static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006542 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6543 if (!FnInfo)
6544 return 0;
6545
6546 switch (FDecl->getBuiltinID()) {
6547 default:
6548 return 0;
6549 case Builtin::BI__builtin_abs:
6550 case Builtin::BI__builtin_fabs:
6551 case Builtin::BI__builtin_fabsf:
6552 case Builtin::BI__builtin_fabsl:
6553 case Builtin::BI__builtin_labs:
6554 case Builtin::BI__builtin_llabs:
6555 case Builtin::BI__builtin_cabs:
6556 case Builtin::BI__builtin_cabsf:
6557 case Builtin::BI__builtin_cabsl:
6558 case Builtin::BIabs:
6559 case Builtin::BIlabs:
6560 case Builtin::BIllabs:
6561 case Builtin::BIfabs:
6562 case Builtin::BIfabsf:
6563 case Builtin::BIfabsl:
6564 case Builtin::BIcabs:
6565 case Builtin::BIcabsf:
6566 case Builtin::BIcabsl:
6567 return FDecl->getBuiltinID();
6568 }
6569 llvm_unreachable("Unknown Builtin type");
6570}
6571
6572// If the replacement is valid, emit a note with replacement function.
6573// Additionally, suggest including the proper header if not already included.
6574static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006575 unsigned AbsKind, QualType ArgType) {
6576 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006577 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006578 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006579 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6580 FunctionName = "std::abs";
6581 if (ArgType->isIntegralOrEnumerationType()) {
6582 HeaderName = "cstdlib";
6583 } else if (ArgType->isRealFloatingType()) {
6584 HeaderName = "cmath";
6585 } else {
6586 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006587 }
Richard Trieubeffb832014-04-15 23:47:53 +00006588
6589 // Lookup all std::abs
6590 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006591 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006592 R.suppressDiagnostics();
6593 S.LookupQualifiedName(R, Std);
6594
6595 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006596 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006597 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6598 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6599 } else {
6600 FDecl = dyn_cast<FunctionDecl>(I);
6601 }
6602 if (!FDecl)
6603 continue;
6604
6605 // Found std::abs(), check that they are the right ones.
6606 if (FDecl->getNumParams() != 1)
6607 continue;
6608
6609 // Check that the parameter type can handle the argument.
6610 QualType ParamType = FDecl->getParamDecl(0)->getType();
6611 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6612 S.Context.getTypeSize(ArgType) <=
6613 S.Context.getTypeSize(ParamType)) {
6614 // Found a function, don't need the header hint.
6615 EmitHeaderHint = false;
6616 break;
6617 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006618 }
Richard Trieubeffb832014-04-15 23:47:53 +00006619 }
6620 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006621 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006622 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6623
6624 if (HeaderName) {
6625 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6626 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6627 R.suppressDiagnostics();
6628 S.LookupName(R, S.getCurScope());
6629
6630 if (R.isSingleResult()) {
6631 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6632 if (FD && FD->getBuiltinID() == AbsKind) {
6633 EmitHeaderHint = false;
6634 } else {
6635 return;
6636 }
6637 } else if (!R.empty()) {
6638 return;
6639 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006640 }
6641 }
6642
6643 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006644 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006645
Richard Trieubeffb832014-04-15 23:47:53 +00006646 if (!HeaderName)
6647 return;
6648
6649 if (!EmitHeaderHint)
6650 return;
6651
Alp Toker5d96e0a2014-07-11 20:53:51 +00006652 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6653 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006654}
6655
6656static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6657 if (!FDecl)
6658 return false;
6659
6660 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6661 return false;
6662
6663 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6664
6665 while (ND && ND->isInlineNamespace()) {
6666 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006667 }
Richard Trieubeffb832014-04-15 23:47:53 +00006668
6669 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6670 return false;
6671
6672 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6673 return false;
6674
6675 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006676}
6677
6678// Warn when using the wrong abs() function.
6679void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6680 const FunctionDecl *FDecl,
6681 IdentifierInfo *FnInfo) {
6682 if (Call->getNumArgs() != 1)
6683 return;
6684
6685 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00006686 bool IsStdAbs = IsFunctionStdAbs(FDecl);
6687 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006688 return;
6689
6690 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6691 QualType ParamType = Call->getArg(0)->getType();
6692
Alp Toker5d96e0a2014-07-11 20:53:51 +00006693 // Unsigned types cannot be negative. Suggest removing the absolute value
6694 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006695 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006696 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006697 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006698 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6699 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006700 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006701 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6702 return;
6703 }
6704
David Majnemer7f77eb92015-11-15 03:04:34 +00006705 // Taking the absolute value of a pointer is very suspicious, they probably
6706 // wanted to index into an array, dereference a pointer, call a function, etc.
6707 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6708 unsigned DiagType = 0;
6709 if (ArgType->isFunctionType())
6710 DiagType = 1;
6711 else if (ArgType->isArrayType())
6712 DiagType = 2;
6713
6714 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6715 return;
6716 }
6717
Richard Trieubeffb832014-04-15 23:47:53 +00006718 // std::abs has overloads which prevent most of the absolute value problems
6719 // from occurring.
6720 if (IsStdAbs)
6721 return;
6722
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006723 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6724 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6725
6726 // The argument and parameter are the same kind. Check if they are the right
6727 // size.
6728 if (ArgValueKind == ParamValueKind) {
6729 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6730 return;
6731
6732 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6733 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6734 << FDecl << ArgType << ParamType;
6735
6736 if (NewAbsKind == 0)
6737 return;
6738
6739 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006740 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006741 return;
6742 }
6743
6744 // ArgValueKind != ParamValueKind
6745 // The wrong type of absolute value function was used. Attempt to find the
6746 // proper one.
6747 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6748 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6749 if (NewAbsKind == 0)
6750 return;
6751
6752 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6753 << FDecl << ParamValueKind << ArgValueKind;
6754
6755 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006756 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006757}
6758
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006759//===--- CHECK: Standard memory functions ---------------------------------===//
6760
Nico Weber0e6daef2013-12-26 23:38:39 +00006761/// \brief Takes the expression passed to the size_t parameter of functions
6762/// such as memcmp, strncat, etc and warns if it's a comparison.
6763///
6764/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6765static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6766 IdentifierInfo *FnName,
6767 SourceLocation FnLoc,
6768 SourceLocation RParenLoc) {
6769 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6770 if (!Size)
6771 return false;
6772
6773 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6774 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6775 return false;
6776
Nico Weber0e6daef2013-12-26 23:38:39 +00006777 SourceRange SizeRange = Size->getSourceRange();
6778 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6779 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00006780 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006781 << FnName << FixItHint::CreateInsertion(
6782 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00006783 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00006784 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00006785 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00006786 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6787 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00006788
6789 return true;
6790}
6791
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006792/// \brief Determine whether the given type is or contains a dynamic class type
6793/// (e.g., whether it has a vtable).
6794static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6795 bool &IsContained) {
6796 // Look through array types while ignoring qualifiers.
6797 const Type *Ty = T->getBaseElementTypeUnsafe();
6798 IsContained = false;
6799
6800 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6801 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00006802 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00006803 return nullptr;
6804
6805 if (RD->isDynamicClass())
6806 return RD;
6807
6808 // Check all the fields. If any bases were dynamic, the class is dynamic.
6809 // It's impossible for a class to transitively contain itself by value, so
6810 // infinite recursion is impossible.
6811 for (auto *FD : RD->fields()) {
6812 bool SubContained;
6813 if (const CXXRecordDecl *ContainedRD =
6814 getContainedDynamicClass(FD->getType(), SubContained)) {
6815 IsContained = true;
6816 return ContainedRD;
6817 }
6818 }
6819
6820 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00006821}
6822
Chandler Carruth889ed862011-06-21 23:04:20 +00006823/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006824/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00006825static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00006826 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006827 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6828 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6829 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006830
Craig Topperc3ec1492014-05-26 06:22:03 +00006831 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006832}
6833
Chandler Carruth889ed862011-06-21 23:04:20 +00006834/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00006835static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006836 if (const UnaryExprOrTypeTraitExpr *SizeOf =
6837 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6838 if (SizeOf->getKind() == clang::UETT_SizeOf)
6839 return SizeOf->getTypeOfArgument();
6840
6841 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00006842}
6843
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006844/// \brief Check for dangerous or invalid arguments to memset().
6845///
Chandler Carruthac687262011-06-03 06:23:57 +00006846/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006847/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6848/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006849///
6850/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006851void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00006852 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00006853 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00006854 assert(BId != 0);
6855
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006856 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00006857 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006858 unsigned ExpectedNumArgs =
6859 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00006860 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00006861 return;
6862
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006863 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00006864 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00006865 unsigned LenArg =
6866 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00006867 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006868
Nico Weber0e6daef2013-12-26 23:38:39 +00006869 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6870 Call->getLocStart(), Call->getRParenLoc()))
6871 return;
6872
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006873 // We have special checking when the length is a sizeof expression.
6874 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6875 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6876 llvm::FoldingSetNodeID SizeOfArgID;
6877
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00006878 // Although widely used, 'bzero' is not a standard function. Be more strict
6879 // with the argument types before allowing diagnostics and only allow the
6880 // form bzero(ptr, sizeof(...)).
6881 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6882 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6883 return;
6884
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006885 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6886 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00006887 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006888
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006889 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00006890 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006891 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00006892 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00006893
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006894 // Never warn about void type pointers. This can be used to suppress
6895 // false positives.
6896 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00006897 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00006898
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006899 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6900 // actually comparing the expressions for equality. Because computing the
6901 // expression IDs can be expensive, we only do this if the diagnostic is
6902 // enabled.
6903 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006904 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6905 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006906 // We only compute IDs for expressions if the warning is enabled, and
6907 // cache the sizeof arg's ID.
6908 if (SizeOfArgID == llvm::FoldingSetNodeID())
6909 SizeOfArg->Profile(SizeOfArgID, Context, true);
6910 llvm::FoldingSetNodeID DestID;
6911 Dest->Profile(DestID, Context, true);
6912 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00006913 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6914 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006915 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00006916 StringRef ReadableName = FnName->getName();
6917
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006918 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00006919 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006920 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00006921 if (!PointeeTy->isIncompleteType() &&
6922 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006923 ActionIdx = 2; // If the pointee's size is sizeof(char),
6924 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00006925
6926 // If the function is defined as a builtin macro, do not show macro
6927 // expansion.
6928 SourceLocation SL = SizeOfArg->getExprLoc();
6929 SourceRange DSR = Dest->getSourceRange();
6930 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00006931 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00006932
6933 if (SM.isMacroArgExpansion(SL)) {
6934 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6935 SL = SM.getSpellingLoc(SL);
6936 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6937 SM.getSpellingLoc(DSR.getEnd()));
6938 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6939 SM.getSpellingLoc(SSR.getEnd()));
6940 }
6941
Anna Zaksd08d9152012-05-30 23:14:52 +00006942 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006943 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00006944 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00006945 << PointeeTy
6946 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00006947 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00006948 << SSR);
6949 DiagRuntimeBehavior(SL, SizeOfArg,
6950 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6951 << ActionIdx
6952 << SSR);
6953
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00006954 break;
6955 }
6956 }
6957
6958 // Also check for cases where the sizeof argument is the exact same
6959 // type as the memory argument, and where it points to a user-defined
6960 // record type.
6961 if (SizeOfArgTy != QualType()) {
6962 if (PointeeTy->isRecordType() &&
6963 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6964 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6965 PDiag(diag::warn_sizeof_pointer_type_memaccess)
6966 << FnName << SizeOfArgTy << ArgIdx
6967 << PointeeTy << Dest->getSourceRange()
6968 << LenExpr->getSourceRange());
6969 break;
6970 }
Nico Weberc5e73862011-06-14 16:14:58 +00006971 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00006972 } else if (DestTy->isArrayType()) {
6973 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00006974 }
Nico Weberc5e73862011-06-14 16:14:58 +00006975
Nico Weberc44b35e2015-03-21 17:37:46 +00006976 if (PointeeTy == QualType())
6977 continue;
Anna Zaks22122702012-01-17 00:37:07 +00006978
Nico Weberc44b35e2015-03-21 17:37:46 +00006979 // Always complain about dynamic classes.
6980 bool IsContained;
6981 if (const CXXRecordDecl *ContainedRD =
6982 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00006983
Nico Weberc44b35e2015-03-21 17:37:46 +00006984 unsigned OperationType = 0;
6985 // "overwritten" if we're warning about the destination for any call
6986 // but memcmp; otherwise a verb appropriate to the call.
6987 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6988 if (BId == Builtin::BImemcpy)
6989 OperationType = 1;
6990 else if(BId == Builtin::BImemmove)
6991 OperationType = 2;
6992 else if (BId == Builtin::BImemcmp)
6993 OperationType = 3;
6994 }
6995
John McCall31168b02011-06-15 23:02:42 +00006996 DiagRuntimeBehavior(
6997 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00006998 PDiag(diag::warn_dyn_class_memaccess)
6999 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7000 << FnName << IsContained << ContainedRD << OperationType
7001 << Call->getCallee()->getSourceRange());
7002 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7003 BId != Builtin::BImemset)
7004 DiagRuntimeBehavior(
7005 Dest->getExprLoc(), Dest,
7006 PDiag(diag::warn_arc_object_memaccess)
7007 << ArgIdx << FnName << PointeeTy
7008 << Call->getCallee()->getSourceRange());
7009 else
7010 continue;
7011
7012 DiagRuntimeBehavior(
7013 Dest->getExprLoc(), Dest,
7014 PDiag(diag::note_bad_memaccess_silence)
7015 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7016 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007017 }
7018}
7019
Ted Kremenek6865f772011-08-18 20:55:45 +00007020// A little helper routine: ignore addition and subtraction of integer literals.
7021// This intentionally does not ignore all integer constant expressions because
7022// we don't want to remove sizeof().
7023static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7024 Ex = Ex->IgnoreParenCasts();
7025
7026 for (;;) {
7027 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7028 if (!BO || !BO->isAdditiveOp())
7029 break;
7030
7031 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7032 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7033
7034 if (isa<IntegerLiteral>(RHS))
7035 Ex = LHS;
7036 else if (isa<IntegerLiteral>(LHS))
7037 Ex = RHS;
7038 else
7039 break;
7040 }
7041
7042 return Ex;
7043}
7044
Anna Zaks13b08572012-08-08 21:42:23 +00007045static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7046 ASTContext &Context) {
7047 // Only handle constant-sized or VLAs, but not flexible members.
7048 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7049 // Only issue the FIXIT for arrays of size > 1.
7050 if (CAT->getSize().getSExtValue() <= 1)
7051 return false;
7052 } else if (!Ty->isVariableArrayType()) {
7053 return false;
7054 }
7055 return true;
7056}
7057
Ted Kremenek6865f772011-08-18 20:55:45 +00007058// Warn if the user has made the 'size' argument to strlcpy or strlcat
7059// be the size of the source, instead of the destination.
7060void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7061 IdentifierInfo *FnName) {
7062
7063 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007064 unsigned NumArgs = Call->getNumArgs();
7065 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007066 return;
7067
7068 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7069 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007070 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007071
7072 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7073 Call->getLocStart(), Call->getRParenLoc()))
7074 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007075
7076 // Look for 'strlcpy(dst, x, sizeof(x))'
7077 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7078 CompareWithSrc = Ex;
7079 else {
7080 // Look for 'strlcpy(dst, x, strlen(x))'
7081 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007082 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7083 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007084 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7085 }
7086 }
7087
7088 if (!CompareWithSrc)
7089 return;
7090
7091 // Determine if the argument to sizeof/strlen is equal to the source
7092 // argument. In principle there's all kinds of things you could do
7093 // here, for instance creating an == expression and evaluating it with
7094 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7095 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7096 if (!SrcArgDRE)
7097 return;
7098
7099 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7100 if (!CompareWithSrcDRE ||
7101 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7102 return;
7103
7104 const Expr *OriginalSizeArg = Call->getArg(2);
7105 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7106 << OriginalSizeArg->getSourceRange() << FnName;
7107
7108 // Output a FIXIT hint if the destination is an array (rather than a
7109 // pointer to an array). This could be enhanced to handle some
7110 // pointers if we know the actual size, like if DstArg is 'array+2'
7111 // we could say 'sizeof(array)-2'.
7112 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007113 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007114 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007115
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007116 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007117 llvm::raw_svector_ostream OS(sizeString);
7118 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007119 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007120 OS << ")";
7121
7122 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7123 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7124 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007125}
7126
Anna Zaks314cd092012-02-01 19:08:57 +00007127/// Check if two expressions refer to the same declaration.
7128static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7129 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7130 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7131 return D1->getDecl() == D2->getDecl();
7132 return false;
7133}
7134
7135static const Expr *getStrlenExprArg(const Expr *E) {
7136 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7137 const FunctionDecl *FD = CE->getDirectCallee();
7138 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007139 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007140 return CE->getArg(0)->IgnoreParenCasts();
7141 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007142 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007143}
7144
7145// Warn on anti-patterns as the 'size' argument to strncat.
7146// The correct size argument should look like following:
7147// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7148void Sema::CheckStrncatArguments(const CallExpr *CE,
7149 IdentifierInfo *FnName) {
7150 // Don't crash if the user has the wrong number of arguments.
7151 if (CE->getNumArgs() < 3)
7152 return;
7153 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7154 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7155 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7156
Nico Weber0e6daef2013-12-26 23:38:39 +00007157 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7158 CE->getRParenLoc()))
7159 return;
7160
Anna Zaks314cd092012-02-01 19:08:57 +00007161 // Identify common expressions, which are wrongly used as the size argument
7162 // to strncat and may lead to buffer overflows.
7163 unsigned PatternType = 0;
7164 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7165 // - sizeof(dst)
7166 if (referToTheSameDecl(SizeOfArg, DstArg))
7167 PatternType = 1;
7168 // - sizeof(src)
7169 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7170 PatternType = 2;
7171 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7172 if (BE->getOpcode() == BO_Sub) {
7173 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7174 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7175 // - sizeof(dst) - strlen(dst)
7176 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7177 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7178 PatternType = 1;
7179 // - sizeof(src) - (anything)
7180 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7181 PatternType = 2;
7182 }
7183 }
7184
7185 if (PatternType == 0)
7186 return;
7187
Anna Zaks5069aa32012-02-03 01:27:37 +00007188 // Generate the diagnostic.
7189 SourceLocation SL = LenArg->getLocStart();
7190 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007191 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007192
7193 // If the function is defined as a builtin macro, do not show macro expansion.
7194 if (SM.isMacroArgExpansion(SL)) {
7195 SL = SM.getSpellingLoc(SL);
7196 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7197 SM.getSpellingLoc(SR.getEnd()));
7198 }
7199
Anna Zaks13b08572012-08-08 21:42:23 +00007200 // Check if the destination is an array (rather than a pointer to an array).
7201 QualType DstTy = DstArg->getType();
7202 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7203 Context);
7204 if (!isKnownSizeArray) {
7205 if (PatternType == 1)
7206 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7207 else
7208 Diag(SL, diag::warn_strncat_src_size) << SR;
7209 return;
7210 }
7211
Anna Zaks314cd092012-02-01 19:08:57 +00007212 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007213 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007214 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007215 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007216
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007217 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007218 llvm::raw_svector_ostream OS(sizeString);
7219 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007220 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007221 OS << ") - ";
7222 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007223 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007224 OS << ") - 1";
7225
Anna Zaks5069aa32012-02-03 01:27:37 +00007226 Diag(SL, diag::note_strncat_wrong_size)
7227 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007228}
7229
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007230//===--- CHECK: Return Address of Stack Variable --------------------------===//
7231
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007232static const Expr *EvalVal(const Expr *E,
7233 SmallVectorImpl<const DeclRefExpr *> &refVars,
7234 const Decl *ParentDecl);
7235static const Expr *EvalAddr(const Expr *E,
7236 SmallVectorImpl<const DeclRefExpr *> &refVars,
7237 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007238
7239/// CheckReturnStackAddr - Check if a return statement returns the address
7240/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007241static void
7242CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7243 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007244
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007245 const Expr *stackE = nullptr;
7246 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007247
7248 // Perform checking for returned stack addresses, local blocks,
7249 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007250 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007251 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007252 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007253 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007254 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007255 }
7256
Craig Topperc3ec1492014-05-26 06:22:03 +00007257 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007258 return; // Nothing suspicious was found.
7259
Richard Trieu81b6c562016-08-05 23:24:47 +00007260 // Parameters are initalized in the calling scope, so taking the address
7261 // of a parameter reference doesn't need a warning.
7262 for (auto *DRE : refVars)
7263 if (isa<ParmVarDecl>(DRE->getDecl()))
7264 return;
7265
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007266 SourceLocation diagLoc;
7267 SourceRange diagRange;
7268 if (refVars.empty()) {
7269 diagLoc = stackE->getLocStart();
7270 diagRange = stackE->getSourceRange();
7271 } else {
7272 // We followed through a reference variable. 'stackE' contains the
7273 // problematic expression but we will warn at the return statement pointing
7274 // at the reference variable. We will later display the "trail" of
7275 // reference variables using notes.
7276 diagLoc = refVars[0]->getLocStart();
7277 diagRange = refVars[0]->getSourceRange();
7278 }
7279
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007280 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7281 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007282 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007283 << DR->getDecl()->getDeclName() << diagRange;
7284 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007285 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007286 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007287 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007288 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007289 // If there is an LValue->RValue conversion, then the value of the
7290 // reference type is used, not the reference.
7291 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7292 if (ICE->getCastKind() == CK_LValueToRValue) {
7293 return;
7294 }
7295 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007296 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7297 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007298 }
7299
7300 // Display the "trail" of reference variables that we followed until we
7301 // found the problematic expression using notes.
7302 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007303 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007304 // If this var binds to another reference var, show the range of the next
7305 // var, otherwise the var binds to the problematic expression, in which case
7306 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007307 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7308 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007309 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7310 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007311 }
7312}
7313
7314/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7315/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007316/// to a location on the stack, a local block, an address of a label, or a
7317/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007318/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007319/// encounter a subexpression that (1) clearly does not lead to one of the
7320/// above problematic expressions (2) is something we cannot determine leads to
7321/// a problematic expression based on such local checking.
7322///
7323/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7324/// the expression that they point to. Such variables are added to the
7325/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007326///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007327/// EvalAddr processes expressions that are pointers that are used as
7328/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007329/// At the base case of the recursion is a check for the above problematic
7330/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007331///
7332/// This implementation handles:
7333///
7334/// * pointer-to-pointer casts
7335/// * implicit conversions from array references to pointers
7336/// * taking the address of fields
7337/// * arbitrary interplay between "&" and "*" operators
7338/// * pointer arithmetic from an address of a stack variable
7339/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007340static const Expr *EvalAddr(const Expr *E,
7341 SmallVectorImpl<const DeclRefExpr *> &refVars,
7342 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007343 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007344 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007345
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007346 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007347 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007348 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007349 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007350 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007351
Peter Collingbourne91147592011-04-15 00:35:48 +00007352 E = E->IgnoreParens();
7353
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007354 // Our "symbolic interpreter" is just a dispatch off the currently
7355 // viewed AST node. We then recursively traverse the AST by calling
7356 // EvalAddr and EvalVal appropriately.
7357 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007358 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007359 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007360
Richard Smith40f08eb2014-01-30 22:05:38 +00007361 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007362 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007363 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007364
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007365 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007366 // If this is a reference variable, follow through to the expression that
7367 // it points to.
7368 if (V->hasLocalStorage() &&
7369 V->getType()->isReferenceType() && V->hasInit()) {
7370 // Add the reference variable to the "trail".
7371 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007372 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007373 }
7374
Craig Topperc3ec1492014-05-26 06:22:03 +00007375 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007376 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007377
Chris Lattner934edb22007-12-28 05:31:15 +00007378 case Stmt::UnaryOperatorClass: {
7379 // The only unary operator that make sense to handle here
7380 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007381 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007382
John McCalle3027922010-08-25 11:45:40 +00007383 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007384 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007385 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007386 }
Mike Stump11289f42009-09-09 15:08:12 +00007387
Chris Lattner934edb22007-12-28 05:31:15 +00007388 case Stmt::BinaryOperatorClass: {
7389 // Handle pointer arithmetic. All other binary operators are not valid
7390 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007391 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007392 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007393
John McCalle3027922010-08-25 11:45:40 +00007394 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007395 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007396
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007397 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007398
7399 // Determine which argument is the real pointer base. It could be
7400 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007401 if (!Base->getType()->isPointerType())
7402 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007403
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007404 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007405 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007406 }
Steve Naroff2752a172008-09-10 19:17:48 +00007407
Chris Lattner934edb22007-12-28 05:31:15 +00007408 // For conditional operators we need to see if either the LHS or RHS are
7409 // valid DeclRefExpr*s. If one of them is valid, we return it.
7410 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007411 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007412
Chris Lattner934edb22007-12-28 05:31:15 +00007413 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007414 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007415 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007416 // In C++, we can have a throw-expression, which has 'void' type.
7417 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007418 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007419 return LHS;
7420 }
Chris Lattner934edb22007-12-28 05:31:15 +00007421
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007422 // In C++, we can have a throw-expression, which has 'void' type.
7423 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007424 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007425
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007426 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007427 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007428
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007429 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007430 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007431 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007432 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007433
7434 case Stmt::AddrLabelExprClass:
7435 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007436
John McCall28fc7092011-11-10 05:35:25 +00007437 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007438 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7439 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007440
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007441 // For casts, we need to handle conversions from arrays to
7442 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007443 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007444 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007445 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007446 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007447 case Stmt::CXXStaticCastExprClass:
7448 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007449 case Stmt::CXXConstCastExprClass:
7450 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007451 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007452 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007453 case CK_LValueToRValue:
7454 case CK_NoOp:
7455 case CK_BaseToDerived:
7456 case CK_DerivedToBase:
7457 case CK_UncheckedDerivedToBase:
7458 case CK_Dynamic:
7459 case CK_CPointerToObjCPointerCast:
7460 case CK_BlockPointerToObjCPointerCast:
7461 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007462 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007463
7464 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007465 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007466
Richard Trieudadefde2014-07-02 04:39:38 +00007467 case CK_BitCast:
7468 if (SubExpr->getType()->isAnyPointerType() ||
7469 SubExpr->getType()->isBlockPointerType() ||
7470 SubExpr->getType()->isObjCQualifiedIdType())
7471 return EvalAddr(SubExpr, refVars, ParentDecl);
7472 else
7473 return nullptr;
7474
Eli Friedman8195ad72012-02-23 23:04:32 +00007475 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007476 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007477 }
Chris Lattner934edb22007-12-28 05:31:15 +00007478 }
Mike Stump11289f42009-09-09 15:08:12 +00007479
Douglas Gregorfe314812011-06-21 17:03:29 +00007480 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007481 if (const Expr *Result =
7482 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7483 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007484 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007485 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007486
Chris Lattner934edb22007-12-28 05:31:15 +00007487 // Everything else: we simply don't reason about them.
7488 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007489 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007490 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007491}
Mike Stump11289f42009-09-09 15:08:12 +00007492
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007493/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7494/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007495static const Expr *EvalVal(const Expr *E,
7496 SmallVectorImpl<const DeclRefExpr *> &refVars,
7497 const Decl *ParentDecl) {
7498 do {
7499 // We should only be called for evaluating non-pointer expressions, or
7500 // expressions with a pointer type that are not used as references but
7501 // instead
7502 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007503
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007504 // Our "symbolic interpreter" is just a dispatch off the currently
7505 // viewed AST node. We then recursively traverse the AST by calling
7506 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007507
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007508 E = E->IgnoreParens();
7509 switch (E->getStmtClass()) {
7510 case Stmt::ImplicitCastExprClass: {
7511 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7512 if (IE->getValueKind() == VK_LValue) {
7513 E = IE->getSubExpr();
7514 continue;
7515 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007516 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007517 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007518
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007519 case Stmt::ExprWithCleanupsClass:
7520 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7521 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007522
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007523 case Stmt::DeclRefExprClass: {
7524 // When we hit a DeclRefExpr we are looking at code that refers to a
7525 // variable's name. If it's not a reference variable we check if it has
7526 // local storage within the function, and if so, return the expression.
7527 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7528
7529 // If we leave the immediate function, the lifetime isn't about to end.
7530 if (DR->refersToEnclosingVariableOrCapture())
7531 return nullptr;
7532
7533 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7534 // Check if it refers to itself, e.g. "int& i = i;".
7535 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007536 return DR;
7537
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007538 if (V->hasLocalStorage()) {
7539 if (!V->getType()->isReferenceType())
7540 return DR;
7541
7542 // Reference variable, follow through to the expression that
7543 // it points to.
7544 if (V->hasInit()) {
7545 // Add the reference variable to the "trail".
7546 refVars.push_back(DR);
7547 return EvalVal(V->getInit(), refVars, V);
7548 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007549 }
7550 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007551
7552 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007553 }
Mike Stump11289f42009-09-09 15:08:12 +00007554
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007555 case Stmt::UnaryOperatorClass: {
7556 // The only unary operator that make sense to handle here
7557 // is Deref. All others don't resolve to a "name." This includes
7558 // handling all sorts of rvalues passed to a unary operator.
7559 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007560
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007561 if (U->getOpcode() == UO_Deref)
7562 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007563
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007564 return nullptr;
7565 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007566
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007567 case Stmt::ArraySubscriptExprClass: {
7568 // Array subscripts are potential references to data on the stack. We
7569 // retrieve the DeclRefExpr* for the array variable if it indeed
7570 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007571 const auto *ASE = cast<ArraySubscriptExpr>(E);
7572 if (ASE->isTypeDependent())
7573 return nullptr;
7574 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007575 }
Mike Stump11289f42009-09-09 15:08:12 +00007576
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007577 case Stmt::OMPArraySectionExprClass: {
7578 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7579 ParentDecl);
7580 }
Mike Stump11289f42009-09-09 15:08:12 +00007581
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007582 case Stmt::ConditionalOperatorClass: {
7583 // For conditional operators we need to see if either the LHS or RHS are
7584 // non-NULL Expr's. If one is non-NULL, we return it.
7585 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007586
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007587 // Handle the GNU extension for missing LHS.
7588 if (const Expr *LHSExpr = C->getLHS()) {
7589 // In C++, we can have a throw-expression, which has 'void' type.
7590 if (!LHSExpr->getType()->isVoidType())
7591 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7592 return LHS;
7593 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007594
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007595 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007596 if (C->getRHS()->getType()->isVoidType())
7597 return nullptr;
7598
7599 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007600 }
7601
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007602 // Accesses to members are potential references to data on the stack.
7603 case Stmt::MemberExprClass: {
7604 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007605
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007606 // Check for indirect access. We only want direct field accesses.
7607 if (M->isArrow())
7608 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007609
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007610 // Check whether the member type is itself a reference, in which case
7611 // we're not going to refer to the member, but to what the member refers
7612 // to.
7613 if (M->getMemberDecl()->getType()->isReferenceType())
7614 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007615
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007616 return EvalVal(M->getBase(), refVars, ParentDecl);
7617 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007618
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007619 case Stmt::MaterializeTemporaryExprClass:
7620 if (const Expr *Result =
7621 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7622 refVars, ParentDecl))
7623 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007624 return E;
7625
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007626 default:
7627 // Check that we don't return or take the address of a reference to a
7628 // temporary. This is only useful in C++.
7629 if (!E->isTypeDependent() && E->isRValue())
7630 return E;
7631
7632 // Everything else: we simply don't reason about them.
7633 return nullptr;
7634 }
7635 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007636}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007637
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007638void
7639Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7640 SourceLocation ReturnLoc,
7641 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007642 const AttrVec *Attrs,
7643 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007644 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7645
7646 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007647 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7648 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007649 CheckNonNullExpr(*this, RetValExp))
7650 Diag(ReturnLoc, diag::warn_null_ret)
7651 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007652
7653 // C++11 [basic.stc.dynamic.allocation]p4:
7654 // If an allocation function declared with a non-throwing
7655 // exception-specification fails to allocate storage, it shall return
7656 // a null pointer. Any other allocation function that fails to allocate
7657 // storage shall indicate failure only by throwing an exception [...]
7658 if (FD) {
7659 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7660 if (Op == OO_New || Op == OO_Array_New) {
7661 const FunctionProtoType *Proto
7662 = FD->getType()->castAs<FunctionProtoType>();
7663 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7664 CheckNonNullExpr(*this, RetValExp))
7665 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7666 << FD << getLangOpts().CPlusPlus11;
7667 }
7668 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007669}
7670
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007671//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7672
7673/// Check for comparisons of floating point operands using != and ==.
7674/// Issue a warning if these are no self-comparisons, as they are not likely
7675/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007676void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007677 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7678 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007679
7680 // Special case: check for x == x (which is OK).
7681 // Do not emit warnings for such cases.
7682 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7683 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7684 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007685 return;
Mike Stump11289f42009-09-09 15:08:12 +00007686
Ted Kremenekeda40e22007-11-29 00:59:04 +00007687 // Special case: check for comparisons against literals that can be exactly
7688 // represented by APFloat. In such cases, do not emit a warning. This
7689 // is a heuristic: often comparison against such literals are used to
7690 // detect if a value in a variable has not changed. This clearly can
7691 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007692 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7693 if (FLL->isExact())
7694 return;
7695 } else
7696 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7697 if (FLR->isExact())
7698 return;
Mike Stump11289f42009-09-09 15:08:12 +00007699
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007700 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007701 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007702 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007703 return;
Mike Stump11289f42009-09-09 15:08:12 +00007704
David Blaikie1f4ff152012-07-16 20:47:22 +00007705 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007706 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007707 return;
Mike Stump11289f42009-09-09 15:08:12 +00007708
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007709 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007710 Diag(Loc, diag::warn_floatingpoint_eq)
7711 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007712}
John McCallca01b222010-01-04 23:21:16 +00007713
John McCall70aa5392010-01-06 05:24:50 +00007714//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7715//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007716
John McCall70aa5392010-01-06 05:24:50 +00007717namespace {
John McCallca01b222010-01-04 23:21:16 +00007718
John McCall70aa5392010-01-06 05:24:50 +00007719/// Structure recording the 'active' range of an integer-valued
7720/// expression.
7721struct IntRange {
7722 /// The number of bits active in the int.
7723 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007724
John McCall70aa5392010-01-06 05:24:50 +00007725 /// True if the int is known not to have negative values.
7726 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007727
John McCall70aa5392010-01-06 05:24:50 +00007728 IntRange(unsigned Width, bool NonNegative)
7729 : Width(Width), NonNegative(NonNegative)
7730 {}
John McCallca01b222010-01-04 23:21:16 +00007731
John McCall817d4af2010-11-10 23:38:19 +00007732 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007733 static IntRange forBoolType() {
7734 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00007735 }
7736
John McCall817d4af2010-11-10 23:38:19 +00007737 /// Returns the range of an opaque value of the given integral type.
7738 static IntRange forValueOfType(ASTContext &C, QualType T) {
7739 return forValueOfCanonicalType(C,
7740 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00007741 }
7742
John McCall817d4af2010-11-10 23:38:19 +00007743 /// Returns the range of an opaque value of a canonical integral type.
7744 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00007745 assert(T->isCanonicalUnqualified());
7746
7747 if (const VectorType *VT = dyn_cast<VectorType>(T))
7748 T = VT->getElementType().getTypePtr();
7749 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7750 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007751 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7752 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00007753
David Majnemer6a426652013-06-07 22:07:20 +00007754 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00007755 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00007756 EnumDecl *Enum = ET->getDecl();
7757 if (!Enum->isCompleteDefinition())
7758 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00007759
David Majnemer6a426652013-06-07 22:07:20 +00007760 unsigned NumPositive = Enum->getNumPositiveBits();
7761 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00007762
David Majnemer6a426652013-06-07 22:07:20 +00007763 if (NumNegative == 0)
7764 return IntRange(NumPositive, true/*NonNegative*/);
7765 else
7766 return IntRange(std::max(NumPositive + 1, NumNegative),
7767 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00007768 }
John McCall70aa5392010-01-06 05:24:50 +00007769
7770 const BuiltinType *BT = cast<BuiltinType>(T);
7771 assert(BT->isInteger());
7772
7773 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7774 }
7775
John McCall817d4af2010-11-10 23:38:19 +00007776 /// Returns the "target" range of a canonical integral type, i.e.
7777 /// the range of values expressible in the type.
7778 ///
7779 /// This matches forValueOfCanonicalType except that enums have the
7780 /// full range of their type, not the range of their enumerators.
7781 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7782 assert(T->isCanonicalUnqualified());
7783
7784 if (const VectorType *VT = dyn_cast<VectorType>(T))
7785 T = VT->getElementType().getTypePtr();
7786 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7787 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00007788 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7789 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007790 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00007791 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00007792
7793 const BuiltinType *BT = cast<BuiltinType>(T);
7794 assert(BT->isInteger());
7795
7796 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7797 }
7798
7799 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00007800 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00007801 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00007802 L.NonNegative && R.NonNegative);
7803 }
7804
John McCall817d4af2010-11-10 23:38:19 +00007805 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00007806 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00007807 return IntRange(std::min(L.Width, R.Width),
7808 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00007809 }
7810};
7811
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007812IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007813 if (value.isSigned() && value.isNegative())
7814 return IntRange(value.getMinSignedBits(), false);
7815
7816 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00007817 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007818
7819 // isNonNegative() just checks the sign bit without considering
7820 // signedness.
7821 return IntRange(value.getActiveBits(), true);
7822}
7823
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007824IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7825 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007826 if (result.isInt())
7827 return GetValueRange(C, result.getInt(), MaxWidth);
7828
7829 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00007830 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7831 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7832 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7833 R = IntRange::join(R, El);
7834 }
John McCall70aa5392010-01-06 05:24:50 +00007835 return R;
7836 }
7837
7838 if (result.isComplexInt()) {
7839 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7840 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7841 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00007842 }
7843
7844 // This can happen with lossless casts to intptr_t of "based" lvalues.
7845 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00007846 // FIXME: The only reason we need to pass the type in here is to get
7847 // the sign right on this one case. It would be nice if APValue
7848 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007849 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00007850 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00007851}
John McCall70aa5392010-01-06 05:24:50 +00007852
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007853QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007854 QualType Ty = E->getType();
7855 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7856 Ty = AtomicRHS->getValueType();
7857 return Ty;
7858}
7859
John McCall70aa5392010-01-06 05:24:50 +00007860/// Pseudo-evaluate the given integer expression, estimating the
7861/// range of values it might take.
7862///
7863/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007864IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00007865 E = E->IgnoreParens();
7866
7867 // Try a full evaluation first.
7868 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007869 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00007870 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00007871
7872 // I think we only want to look through implicit casts here; if the
7873 // user has an explicit widening cast, we should treat the value as
7874 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007875 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00007876 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00007877 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7878
Eli Friedmane6d33952013-07-08 20:20:06 +00007879 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00007880
George Burgess IVdf1ed002016-01-13 01:52:39 +00007881 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7882 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00007883
John McCall70aa5392010-01-06 05:24:50 +00007884 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00007885 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00007886 return OutputTypeRange;
7887
7888 IntRange SubRange
7889 = GetExprRange(C, CE->getSubExpr(),
7890 std::min(MaxWidth, OutputTypeRange.Width));
7891
7892 // Bail out if the subexpr's range is as wide as the cast type.
7893 if (SubRange.Width >= OutputTypeRange.Width)
7894 return OutputTypeRange;
7895
7896 // Otherwise, we take the smaller width, and we're non-negative if
7897 // either the output type or the subexpr is.
7898 return IntRange(SubRange.Width,
7899 SubRange.NonNegative || OutputTypeRange.NonNegative);
7900 }
7901
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007902 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007903 // If we can fold the condition, just take that operand.
7904 bool CondResult;
7905 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7906 return GetExprRange(C, CondResult ? CO->getTrueExpr()
7907 : CO->getFalseExpr(),
7908 MaxWidth);
7909
7910 // Otherwise, conservatively merge.
7911 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7912 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7913 return IntRange::join(L, R);
7914 }
7915
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00007916 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00007917 switch (BO->getOpcode()) {
7918
7919 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00007920 case BO_LAnd:
7921 case BO_LOr:
7922 case BO_LT:
7923 case BO_GT:
7924 case BO_LE:
7925 case BO_GE:
7926 case BO_EQ:
7927 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00007928 return IntRange::forBoolType();
7929
John McCallc3688382011-07-13 06:35:24 +00007930 // The type of the assignments is the type of the LHS, so the RHS
7931 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00007932 case BO_MulAssign:
7933 case BO_DivAssign:
7934 case BO_RemAssign:
7935 case BO_AddAssign:
7936 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00007937 case BO_XorAssign:
7938 case BO_OrAssign:
7939 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00007940 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00007941
John McCallc3688382011-07-13 06:35:24 +00007942 // Simple assignments just pass through the RHS, which will have
7943 // been coerced to the LHS type.
7944 case BO_Assign:
7945 // TODO: bitfields?
7946 return GetExprRange(C, BO->getRHS(), MaxWidth);
7947
John McCall70aa5392010-01-06 05:24:50 +00007948 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00007949 case BO_PtrMemD:
7950 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00007951 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007952
John McCall2ce81ad2010-01-06 22:07:33 +00007953 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00007954 case BO_And:
7955 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00007956 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7957 GetExprRange(C, BO->getRHS(), MaxWidth));
7958
John McCall70aa5392010-01-06 05:24:50 +00007959 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00007960 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00007961 // ...except that we want to treat '1 << (blah)' as logically
7962 // positive. It's an important idiom.
7963 if (IntegerLiteral *I
7964 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7965 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00007966 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00007967 return IntRange(R.Width, /*NonNegative*/ true);
7968 }
7969 }
7970 // fallthrough
7971
John McCalle3027922010-08-25 11:45:40 +00007972 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00007973 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00007974
John McCall2ce81ad2010-01-06 22:07:33 +00007975 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00007976 case BO_Shr:
7977 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00007978 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7979
7980 // If the shift amount is a positive constant, drop the width by
7981 // that much.
7982 llvm::APSInt shift;
7983 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7984 shift.isNonNegative()) {
7985 unsigned zext = shift.getZExtValue();
7986 if (zext >= L.Width)
7987 L.Width = (L.NonNegative ? 0 : 1);
7988 else
7989 L.Width -= zext;
7990 }
7991
7992 return L;
7993 }
7994
7995 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00007996 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00007997 return GetExprRange(C, BO->getRHS(), MaxWidth);
7998
John McCall2ce81ad2010-01-06 22:07:33 +00007999 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008000 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008001 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008002 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008003 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008004
John McCall51431812011-07-14 22:39:48 +00008005 // The width of a division result is mostly determined by the size
8006 // of the LHS.
8007 case BO_Div: {
8008 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008009 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008010 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8011
8012 // If the divisor is constant, use that.
8013 llvm::APSInt divisor;
8014 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8015 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8016 if (log2 >= L.Width)
8017 L.Width = (L.NonNegative ? 0 : 1);
8018 else
8019 L.Width = std::min(L.Width - log2, MaxWidth);
8020 return L;
8021 }
8022
8023 // Otherwise, just use the LHS's width.
8024 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8025 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8026 }
8027
8028 // The result of a remainder can't be larger than the result of
8029 // either side.
8030 case BO_Rem: {
8031 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008032 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008033 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8034 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8035
8036 IntRange meet = IntRange::meet(L, R);
8037 meet.Width = std::min(meet.Width, MaxWidth);
8038 return meet;
8039 }
8040
8041 // The default behavior is okay for these.
8042 case BO_Mul:
8043 case BO_Add:
8044 case BO_Xor:
8045 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008046 break;
8047 }
8048
John McCall51431812011-07-14 22:39:48 +00008049 // The default case is to treat the operation as if it were closed
8050 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008051 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8052 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8053 return IntRange::join(L, R);
8054 }
8055
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008056 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008057 switch (UO->getOpcode()) {
8058 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008059 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008060 return IntRange::forBoolType();
8061
8062 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008063 case UO_Deref:
8064 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008065 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008066
8067 default:
8068 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8069 }
8070 }
8071
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008072 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008073 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8074
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008075 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008076 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008077 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008078
Eli Friedmane6d33952013-07-08 20:20:06 +00008079 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008080}
John McCall263a48b2010-01-04 23:31:57 +00008081
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008082IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008083 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008084}
8085
John McCall263a48b2010-01-04 23:31:57 +00008086/// Checks whether the given value, which currently has the given
8087/// source semantics, has the same value when coerced through the
8088/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008089bool IsSameFloatAfterCast(const llvm::APFloat &value,
8090 const llvm::fltSemantics &Src,
8091 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008092 llvm::APFloat truncated = value;
8093
8094 bool ignored;
8095 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8096 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8097
8098 return truncated.bitwiseIsEqual(value);
8099}
8100
8101/// Checks whether the given value, which currently has the given
8102/// source semantics, has the same value when coerced through the
8103/// target semantics.
8104///
8105/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008106bool IsSameFloatAfterCast(const APValue &value,
8107 const llvm::fltSemantics &Src,
8108 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008109 if (value.isFloat())
8110 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8111
8112 if (value.isVector()) {
8113 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8114 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8115 return false;
8116 return true;
8117 }
8118
8119 assert(value.isComplexFloat());
8120 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8121 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8122}
8123
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008124void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008125
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008126bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008127 // Suppress cases where we are comparing against an enum constant.
8128 if (const DeclRefExpr *DR =
8129 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8130 if (isa<EnumConstantDecl>(DR->getDecl()))
8131 return false;
8132
8133 // Suppress cases where the '0' value is expanded from a macro.
8134 if (E->getLocStart().isMacroID())
8135 return false;
8136
John McCallcc7e5bf2010-05-06 08:58:33 +00008137 llvm::APSInt Value;
8138 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8139}
8140
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008141bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008142 // Strip off implicit integral promotions.
8143 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008144 if (ICE->getCastKind() != CK_IntegralCast &&
8145 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008146 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008147 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008148 }
8149
8150 return E->getType()->isEnumeralType();
8151}
8152
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008153void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008154 // Disable warning in template instantiations.
8155 if (!S.ActiveTemplateInstantiations.empty())
8156 return;
8157
John McCalle3027922010-08-25 11:45:40 +00008158 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008159 if (E->isValueDependent())
8160 return;
8161
John McCalle3027922010-08-25 11:45:40 +00008162 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008163 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008164 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008165 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008166 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008167 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008168 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008169 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008170 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008171 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008172 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008173 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008174 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008175 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008176 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008177 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8178 }
8179}
8180
Benjamin Kramer7320b992016-06-15 14:20:56 +00008181void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8182 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008183 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008184 // Disable warning in template instantiations.
8185 if (!S.ActiveTemplateInstantiations.empty())
8186 return;
8187
Richard Trieu0f097742014-04-04 04:13:47 +00008188 // TODO: Investigate using GetExprRange() to get tighter bounds
8189 // on the bit ranges.
8190 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008191 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008192 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008193 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8194 unsigned OtherWidth = OtherRange.Width;
8195
8196 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8197
Richard Trieu560910c2012-11-14 22:50:24 +00008198 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008199 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008200 return;
8201
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008202 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008203 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008204
Richard Trieu0f097742014-04-04 04:13:47 +00008205 // Used for diagnostic printout.
8206 enum {
8207 LiteralConstant = 0,
8208 CXXBoolLiteralTrue,
8209 CXXBoolLiteralFalse
8210 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008211
Richard Trieu0f097742014-04-04 04:13:47 +00008212 if (!OtherIsBooleanType) {
8213 QualType ConstantT = Constant->getType();
8214 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008215
Richard Trieu0f097742014-04-04 04:13:47 +00008216 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8217 return;
8218 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8219 "comparison with non-integer type");
8220
8221 bool ConstantSigned = ConstantT->isSignedIntegerType();
8222 bool CommonSigned = CommonT->isSignedIntegerType();
8223
8224 bool EqualityOnly = false;
8225
8226 if (CommonSigned) {
8227 // The common type is signed, therefore no signed to unsigned conversion.
8228 if (!OtherRange.NonNegative) {
8229 // Check that the constant is representable in type OtherT.
8230 if (ConstantSigned) {
8231 if (OtherWidth >= Value.getMinSignedBits())
8232 return;
8233 } else { // !ConstantSigned
8234 if (OtherWidth >= Value.getActiveBits() + 1)
8235 return;
8236 }
8237 } else { // !OtherSigned
8238 // Check that the constant is representable in type OtherT.
8239 // Negative values are out of range.
8240 if (ConstantSigned) {
8241 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8242 return;
8243 } else { // !ConstantSigned
8244 if (OtherWidth >= Value.getActiveBits())
8245 return;
8246 }
Richard Trieu560910c2012-11-14 22:50:24 +00008247 }
Richard Trieu0f097742014-04-04 04:13:47 +00008248 } else { // !CommonSigned
8249 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008250 if (OtherWidth >= Value.getActiveBits())
8251 return;
Craig Toppercf360162014-06-18 05:13:11 +00008252 } else { // OtherSigned
8253 assert(!ConstantSigned &&
8254 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008255 // Check to see if the constant is representable in OtherT.
8256 if (OtherWidth > Value.getActiveBits())
8257 return;
8258 // Check to see if the constant is equivalent to a negative value
8259 // cast to CommonT.
8260 if (S.Context.getIntWidth(ConstantT) ==
8261 S.Context.getIntWidth(CommonT) &&
8262 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8263 return;
8264 // The constant value rests between values that OtherT can represent
8265 // after conversion. Relational comparison still works, but equality
8266 // comparisons will be tautological.
8267 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008268 }
8269 }
Richard Trieu0f097742014-04-04 04:13:47 +00008270
8271 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8272
8273 if (op == BO_EQ || op == BO_NE) {
8274 IsTrue = op == BO_NE;
8275 } else if (EqualityOnly) {
8276 return;
8277 } else if (RhsConstant) {
8278 if (op == BO_GT || op == BO_GE)
8279 IsTrue = !PositiveConstant;
8280 else // op == BO_LT || op == BO_LE
8281 IsTrue = PositiveConstant;
8282 } else {
8283 if (op == BO_LT || op == BO_LE)
8284 IsTrue = !PositiveConstant;
8285 else // op == BO_GT || op == BO_GE
8286 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008287 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008288 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008289 // Other isKnownToHaveBooleanValue
8290 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8291 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8292 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8293
8294 static const struct LinkedConditions {
8295 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8296 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8297 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8298 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8299 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8300 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8301
8302 } TruthTable = {
8303 // Constant on LHS. | Constant on RHS. |
8304 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8305 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8306 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8307 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8308 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8309 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8310 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8311 };
8312
8313 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8314
8315 enum ConstantValue ConstVal = Zero;
8316 if (Value.isUnsigned() || Value.isNonNegative()) {
8317 if (Value == 0) {
8318 LiteralOrBoolConstant =
8319 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8320 ConstVal = Zero;
8321 } else if (Value == 1) {
8322 LiteralOrBoolConstant =
8323 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8324 ConstVal = One;
8325 } else {
8326 LiteralOrBoolConstant = LiteralConstant;
8327 ConstVal = GT_One;
8328 }
8329 } else {
8330 ConstVal = LT_Zero;
8331 }
8332
8333 CompareBoolWithConstantResult CmpRes;
8334
8335 switch (op) {
8336 case BO_LT:
8337 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8338 break;
8339 case BO_GT:
8340 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8341 break;
8342 case BO_LE:
8343 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8344 break;
8345 case BO_GE:
8346 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8347 break;
8348 case BO_EQ:
8349 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8350 break;
8351 case BO_NE:
8352 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8353 break;
8354 default:
8355 CmpRes = Unkwn;
8356 break;
8357 }
8358
8359 if (CmpRes == AFals) {
8360 IsTrue = false;
8361 } else if (CmpRes == ATrue) {
8362 IsTrue = true;
8363 } else {
8364 return;
8365 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008366 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008367
8368 // If this is a comparison to an enum constant, include that
8369 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008370 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008371 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8372 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8373
8374 SmallString<64> PrettySourceValue;
8375 llvm::raw_svector_ostream OS(PrettySourceValue);
8376 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008377 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008378 else
8379 OS << Value;
8380
Richard Trieu0f097742014-04-04 04:13:47 +00008381 S.DiagRuntimeBehavior(
8382 E->getOperatorLoc(), E,
8383 S.PDiag(diag::warn_out_of_range_compare)
8384 << OS.str() << LiteralOrBoolConstant
8385 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8386 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008387}
8388
John McCallcc7e5bf2010-05-06 08:58:33 +00008389/// Analyze the operands of the given comparison. Implements the
8390/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008391void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008392 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8393 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008394}
John McCall263a48b2010-01-04 23:31:57 +00008395
John McCallca01b222010-01-04 23:21:16 +00008396/// \brief Implements -Wsign-compare.
8397///
Richard Trieu82402a02011-09-15 21:56:47 +00008398/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008399void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008400 // The type the comparison is being performed in.
8401 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008402
8403 // Only analyze comparison operators where both sides have been converted to
8404 // the same type.
8405 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8406 return AnalyzeImpConvsInComparison(S, E);
8407
8408 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008409 if (E->isValueDependent())
8410 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008411
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008412 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8413 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008414
8415 bool IsComparisonConstant = false;
8416
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008417 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008418 // of 'true' or 'false'.
8419 if (T->isIntegralType(S.Context)) {
8420 llvm::APSInt RHSValue;
8421 bool IsRHSIntegralLiteral =
8422 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8423 llvm::APSInt LHSValue;
8424 bool IsLHSIntegralLiteral =
8425 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8426 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8427 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8428 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8429 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8430 else
8431 IsComparisonConstant =
8432 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008433 } else if (!T->hasUnsignedIntegerRepresentation())
8434 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008435
John McCallcc7e5bf2010-05-06 08:58:33 +00008436 // We don't do anything special if this isn't an unsigned integral
8437 // comparison: we're only interested in integral comparisons, and
8438 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008439 //
8440 // We also don't care about value-dependent expressions or expressions
8441 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008442 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008443 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008444
John McCallcc7e5bf2010-05-06 08:58:33 +00008445 // Check to see if one of the (unmodified) operands is of different
8446 // signedness.
8447 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008448 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8449 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008450 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008451 signedOperand = LHS;
8452 unsignedOperand = RHS;
8453 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8454 signedOperand = RHS;
8455 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008456 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008457 CheckTrivialUnsignedComparison(S, E);
8458 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008459 }
8460
John McCallcc7e5bf2010-05-06 08:58:33 +00008461 // Otherwise, calculate the effective range of the signed operand.
8462 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008463
John McCallcc7e5bf2010-05-06 08:58:33 +00008464 // Go ahead and analyze implicit conversions in the operands. Note
8465 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008466 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8467 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008468
John McCallcc7e5bf2010-05-06 08:58:33 +00008469 // If the signed range is non-negative, -Wsign-compare won't fire,
8470 // but we should still check for comparisons which are always true
8471 // or false.
8472 if (signedRange.NonNegative)
8473 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008474
8475 // For (in)equality comparisons, if the unsigned operand is a
8476 // constant which cannot collide with a overflowed signed operand,
8477 // then reinterpreting the signed operand as unsigned will not
8478 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008479 if (E->isEqualityOp()) {
8480 unsigned comparisonWidth = S.Context.getIntWidth(T);
8481 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008482
John McCallcc7e5bf2010-05-06 08:58:33 +00008483 // We should never be unable to prove that the unsigned operand is
8484 // non-negative.
8485 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8486
8487 if (unsignedRange.Width < comparisonWidth)
8488 return;
8489 }
8490
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008491 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8492 S.PDiag(diag::warn_mixed_sign_comparison)
8493 << LHS->getType() << RHS->getType()
8494 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008495}
8496
John McCall1f425642010-11-11 03:21:53 +00008497/// Analyzes an attempt to assign the given value to a bitfield.
8498///
8499/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008500bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8501 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008502 assert(Bitfield->isBitField());
8503 if (Bitfield->isInvalidDecl())
8504 return false;
8505
John McCalldeebbcf2010-11-11 05:33:51 +00008506 // White-list bool bitfields.
8507 if (Bitfield->getType()->isBooleanType())
8508 return false;
8509
Douglas Gregor789adec2011-02-04 13:09:01 +00008510 // Ignore value- or type-dependent expressions.
8511 if (Bitfield->getBitWidth()->isValueDependent() ||
8512 Bitfield->getBitWidth()->isTypeDependent() ||
8513 Init->isValueDependent() ||
8514 Init->isTypeDependent())
8515 return false;
8516
John McCall1f425642010-11-11 03:21:53 +00008517 Expr *OriginalInit = Init->IgnoreParenImpCasts();
8518
Richard Smith5fab0c92011-12-28 19:48:30 +00008519 llvm::APSInt Value;
8520 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00008521 return false;
8522
John McCall1f425642010-11-11 03:21:53 +00008523 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00008524 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008525
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008526 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008527 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008528 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8529 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008530
John McCall1f425642010-11-11 03:21:53 +00008531 if (OriginalWidth <= FieldWidth)
8532 return false;
8533
Eli Friedmanc267a322012-01-26 23:11:39 +00008534 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008535 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00008536 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008537
Eli Friedmanc267a322012-01-26 23:11:39 +00008538 // Check whether the stored value is equal to the original value.
8539 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008540 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008541 return false;
8542
Eli Friedmanc267a322012-01-26 23:11:39 +00008543 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008544 // therefore don't strictly fit into a signed bitfield of width 1.
8545 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008546 return false;
8547
John McCall1f425642010-11-11 03:21:53 +00008548 std::string PrettyValue = Value.toString(10);
8549 std::string PrettyTrunc = TruncatedValue.toString(10);
8550
8551 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8552 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8553 << Init->getSourceRange();
8554
8555 return true;
8556}
8557
John McCalld2a53122010-11-09 23:24:47 +00008558/// Analyze the given simple or compound assignment for warning-worthy
8559/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008560void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008561 // Just recurse on the LHS.
8562 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8563
8564 // We want to recurse on the RHS as normal unless we're assigning to
8565 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008566 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008567 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008568 E->getOperatorLoc())) {
8569 // Recurse, ignoring any implicit conversions on the RHS.
8570 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8571 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008572 }
8573 }
8574
8575 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8576}
8577
John McCall263a48b2010-01-04 23:31:57 +00008578/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008579void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8580 SourceLocation CContext, unsigned diag,
8581 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008582 if (pruneControlFlow) {
8583 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8584 S.PDiag(diag)
8585 << SourceType << T << E->getSourceRange()
8586 << SourceRange(CContext));
8587 return;
8588 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008589 S.Diag(E->getExprLoc(), diag)
8590 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8591}
8592
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008593/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008594void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8595 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008596 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008597}
8598
Richard Trieube234c32016-04-21 21:04:55 +00008599
8600/// Diagnose an implicit cast from a floating point value to an integer value.
8601void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8602
8603 SourceLocation CContext) {
8604 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8605 const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8606
8607 Expr *InnerE = E->IgnoreParenImpCasts();
8608 // We also want to warn on, e.g., "int i = -1.234"
8609 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8610 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8611 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8612
8613 const bool IsLiteral =
8614 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8615
8616 llvm::APFloat Value(0.0);
8617 bool IsConstant =
8618 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8619 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008620 return DiagnoseImpCast(S, E, T, CContext,
8621 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008622 }
8623
Chandler Carruth016ef402011-04-10 08:36:24 +00008624 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008625
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008626 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8627 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008628 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8629 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008630 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008631 if (IsLiteral) return;
8632 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8633 PruneWarnings);
8634 }
8635
8636 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008637 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008638 // Warn on floating point literal to integer.
8639 DiagID = diag::warn_impcast_literal_float_to_integer;
8640 } else if (IntegerValue == 0) {
8641 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8642 return DiagnoseImpCast(S, E, T, CContext,
8643 diag::warn_impcast_float_integer, PruneWarnings);
8644 }
8645 // Warn on non-zero to zero conversion.
8646 DiagID = diag::warn_impcast_float_to_integer_zero;
8647 } else {
8648 if (IntegerValue.isUnsigned()) {
8649 if (!IntegerValue.isMaxValue()) {
8650 return DiagnoseImpCast(S, E, T, CContext,
8651 diag::warn_impcast_float_integer, PruneWarnings);
8652 }
8653 } else { // IntegerValue.isSigned()
8654 if (!IntegerValue.isMaxSignedValue() &&
8655 !IntegerValue.isMinSignedValue()) {
8656 return DiagnoseImpCast(S, E, T, CContext,
8657 diag::warn_impcast_float_integer, PruneWarnings);
8658 }
8659 }
8660 // Warn on evaluatable floating point expression to integer conversion.
8661 DiagID = diag::warn_impcast_float_to_integer;
8662 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008663
Eli Friedman07185912013-08-29 23:44:43 +00008664 // FIXME: Force the precision of the source value down so we don't print
8665 // digits which are usually useless (we don't really care here if we
8666 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
8667 // would automatically print the shortest representation, but it's a bit
8668 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00008669 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00008670 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8671 precision = (precision * 59 + 195) / 196;
8672 Value.toString(PrettySourceValue, precision);
8673
David Blaikie9b88cc02012-05-15 17:18:27 +00008674 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00008675 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00008676 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00008677 else
David Blaikie9b88cc02012-05-15 17:18:27 +00008678 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00008679
Richard Trieube234c32016-04-21 21:04:55 +00008680 if (PruneWarnings) {
8681 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8682 S.PDiag(DiagID)
8683 << E->getType() << T.getUnqualifiedType()
8684 << PrettySourceValue << PrettyTargetValue
8685 << E->getSourceRange() << SourceRange(CContext));
8686 } else {
8687 S.Diag(E->getExprLoc(), DiagID)
8688 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8689 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8690 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008691}
8692
John McCall18a2c2c2010-11-09 22:22:12 +00008693std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8694 if (!Range.Width) return "0";
8695
8696 llvm::APSInt ValueInRange = Value;
8697 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00008698 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00008699 return ValueInRange.toString(10);
8700}
8701
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008702bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00008703 if (!isa<ImplicitCastExpr>(Ex))
8704 return false;
8705
8706 Expr *InnerE = Ex->IgnoreParenImpCasts();
8707 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8708 const Type *Source =
8709 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8710 if (Target->isDependentType())
8711 return false;
8712
8713 const BuiltinType *FloatCandidateBT =
8714 dyn_cast<BuiltinType>(ToBool ? Source : Target);
8715 const Type *BoolCandidateType = ToBool ? Target : Source;
8716
8717 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8718 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8719}
8720
8721void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8722 SourceLocation CC) {
8723 unsigned NumArgs = TheCall->getNumArgs();
8724 for (unsigned i = 0; i < NumArgs; ++i) {
8725 Expr *CurrA = TheCall->getArg(i);
8726 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8727 continue;
8728
8729 bool IsSwapped = ((i > 0) &&
8730 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8731 IsSwapped |= ((i < (NumArgs - 1)) &&
8732 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8733 if (IsSwapped) {
8734 // Warn on this floating-point to bool conversion.
8735 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8736 CurrA->getType(), CC,
8737 diag::warn_impcast_floating_point_to_bool);
8738 }
8739 }
8740}
8741
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008742void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00008743 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8744 E->getExprLoc()))
8745 return;
8746
Richard Trieu09d6b802016-01-08 23:35:06 +00008747 // Don't warn on functions which have return type nullptr_t.
8748 if (isa<CallExpr>(E))
8749 return;
8750
Richard Trieu5b993502014-10-15 03:42:06 +00008751 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8752 const Expr::NullPointerConstantKind NullKind =
8753 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8754 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8755 return;
8756
8757 // Return if target type is a safe conversion.
8758 if (T->isAnyPointerType() || T->isBlockPointerType() ||
8759 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8760 return;
8761
8762 SourceLocation Loc = E->getSourceRange().getBegin();
8763
Richard Trieu0a5e1662016-02-13 00:58:53 +00008764 // Venture through the macro stacks to get to the source of macro arguments.
8765 // The new location is a better location than the complete location that was
8766 // passed in.
8767 while (S.SourceMgr.isMacroArgExpansion(Loc))
8768 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8769
8770 while (S.SourceMgr.isMacroArgExpansion(CC))
8771 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8772
Richard Trieu5b993502014-10-15 03:42:06 +00008773 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00008774 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8775 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8776 Loc, S.SourceMgr, S.getLangOpts());
8777 if (MacroName == "NULL")
8778 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00008779 }
8780
8781 // Only warn if the null and context location are in the same macro expansion.
8782 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8783 return;
8784
8785 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8786 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8787 << FixItHint::CreateReplacement(Loc,
8788 S.getFixItZeroLiteralForType(T, Loc));
8789}
8790
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008791void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8792 ObjCArrayLiteral *ArrayLiteral);
8793void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8794 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00008795
8796/// Check a single element within a collection literal against the
8797/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008798void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8799 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008800 // Skip a bitcast to 'id' or qualified 'id'.
8801 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8802 if (ICE->getCastKind() == CK_BitCast &&
8803 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8804 Element = ICE->getSubExpr();
8805 }
8806
8807 QualType ElementType = Element->getType();
8808 ExprResult ElementResult(Element);
8809 if (ElementType->getAs<ObjCObjectPointerType>() &&
8810 S.CheckSingleAssignmentConstraints(TargetElementType,
8811 ElementResult,
8812 false, false)
8813 != Sema::Compatible) {
8814 S.Diag(Element->getLocStart(),
8815 diag::warn_objc_collection_literal_element)
8816 << ElementType << ElementKind << TargetElementType
8817 << Element->getSourceRange();
8818 }
8819
8820 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8821 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8822 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8823 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8824}
8825
8826/// Check an Objective-C array literal being converted to the given
8827/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008828void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8829 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008830 if (!S.NSArrayDecl)
8831 return;
8832
8833 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8834 if (!TargetObjCPtr)
8835 return;
8836
8837 if (TargetObjCPtr->isUnspecialized() ||
8838 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8839 != S.NSArrayDecl->getCanonicalDecl())
8840 return;
8841
8842 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8843 if (TypeArgs.size() != 1)
8844 return;
8845
8846 QualType TargetElementType = TypeArgs[0];
8847 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8848 checkObjCCollectionLiteralElement(S, TargetElementType,
8849 ArrayLiteral->getElement(I),
8850 0);
8851 }
8852}
8853
8854/// Check an Objective-C dictionary literal being converted to the given
8855/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008856void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8857 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00008858 if (!S.NSDictionaryDecl)
8859 return;
8860
8861 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8862 if (!TargetObjCPtr)
8863 return;
8864
8865 if (TargetObjCPtr->isUnspecialized() ||
8866 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8867 != S.NSDictionaryDecl->getCanonicalDecl())
8868 return;
8869
8870 auto TypeArgs = TargetObjCPtr->getTypeArgs();
8871 if (TypeArgs.size() != 2)
8872 return;
8873
8874 QualType TargetKeyType = TypeArgs[0];
8875 QualType TargetObjectType = TypeArgs[1];
8876 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8877 auto Element = DictionaryLiteral->getKeyValueElement(I);
8878 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8879 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8880 }
8881}
8882
Richard Trieufc404c72016-02-05 23:02:38 +00008883// Helper function to filter out cases for constant width constant conversion.
8884// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008885bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8886 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00008887 // If initializing from a constant, and the constant starts with '0',
8888 // then it is a binary, octal, or hexadecimal. Allow these constants
8889 // to fill all the bits, even if there is a sign change.
8890 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8891 const char FirstLiteralCharacter =
8892 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8893 if (FirstLiteralCharacter == '0')
8894 return false;
8895 }
8896
8897 // If the CC location points to a '{', and the type is char, then assume
8898 // assume it is an array initialization.
8899 if (CC.isValid() && T->isCharType()) {
8900 const char FirstContextCharacter =
8901 S.getSourceManager().getCharacterData(CC)[0];
8902 if (FirstContextCharacter == '{')
8903 return false;
8904 }
8905
8906 return true;
8907}
8908
John McCallcc7e5bf2010-05-06 08:58:33 +00008909void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00008910 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008911 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00008912
John McCallcc7e5bf2010-05-06 08:58:33 +00008913 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8914 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8915 if (Source == Target) return;
8916 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00008917
Chandler Carruthc22845a2011-07-26 05:40:03 +00008918 // If the conversion context location is invalid don't complain. We also
8919 // don't want to emit a warning if the issue occurs from the expansion of
8920 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8921 // delay this check as long as possible. Once we detect we are in that
8922 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008923 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00008924 return;
8925
Richard Trieu021baa32011-09-23 20:10:00 +00008926 // Diagnose implicit casts to bool.
8927 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8928 if (isa<StringLiteral>(E))
8929 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00008930 // and expressions, for instance, assert(0 && "error here"), are
8931 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00008932 return DiagnoseImpCast(S, E, T, CC,
8933 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00008934 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8935 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8936 // This covers the literal expressions that evaluate to Objective-C
8937 // objects.
8938 return DiagnoseImpCast(S, E, T, CC,
8939 diag::warn_impcast_objective_c_literal_to_bool);
8940 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00008941 if (Source->isPointerType() || Source->canDecayToPointerType()) {
8942 // Warn on pointer to bool conversion that is always true.
8943 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8944 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00008945 }
Richard Trieu021baa32011-09-23 20:10:00 +00008946 }
John McCall263a48b2010-01-04 23:31:57 +00008947
Douglas Gregor5054cb02015-07-07 03:58:22 +00008948 // Check implicit casts from Objective-C collection literals to specialized
8949 // collection types, e.g., NSArray<NSString *> *.
8950 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8951 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8952 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8953 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8954
John McCall263a48b2010-01-04 23:31:57 +00008955 // Strip vector types.
8956 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008957 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008958 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008959 return;
John McCallacf0ee52010-10-08 02:01:28 +00008960 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008961 }
Chris Lattneree7286f2011-06-14 04:51:15 +00008962
8963 // If the vector cast is cast between two vectors of the same size, it is
8964 // a bitcast, not a conversion.
8965 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8966 return;
John McCall263a48b2010-01-04 23:31:57 +00008967
8968 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8969 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8970 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00008971 if (auto VecTy = dyn_cast<VectorType>(Target))
8972 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00008973
8974 // Strip complex types.
8975 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008976 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00008977 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008978 return;
8979
John McCallacf0ee52010-10-08 02:01:28 +00008980 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00008981 }
John McCall263a48b2010-01-04 23:31:57 +00008982
8983 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8984 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8985 }
8986
8987 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8988 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8989
8990 // If the source is floating point...
8991 if (SourceBT && SourceBT->isFloatingPoint()) {
8992 // ...and the target is floating point...
8993 if (TargetBT && TargetBT->isFloatingPoint()) {
8994 // ...then warn if we're dropping FP rank.
8995
8996 // Builtin FP kinds are ordered by increasing FP rank.
8997 if (SourceBT->getKind() > TargetBT->getKind()) {
8998 // Don't warn about float constants that are precisely
8999 // representable in the target type.
9000 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009001 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009002 // Value might be a float, a float vector, or a float complex.
9003 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009004 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9005 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009006 return;
9007 }
9008
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009009 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009010 return;
9011
John McCallacf0ee52010-10-08 02:01:28 +00009012 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009013 }
9014 // ... or possibly if we're increasing rank, too
9015 else if (TargetBT->getKind() > SourceBT->getKind()) {
9016 if (S.SourceMgr.isInSystemMacro(CC))
9017 return;
9018
9019 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009020 }
9021 return;
9022 }
9023
Richard Trieube234c32016-04-21 21:04:55 +00009024 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009025 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009026 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009027 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009028
Richard Trieube234c32016-04-21 21:04:55 +00009029 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009030 }
John McCall263a48b2010-01-04 23:31:57 +00009031
Richard Smith54894fd2015-12-30 01:06:52 +00009032 // Detect the case where a call result is converted from floating-point to
9033 // to bool, and the final argument to the call is converted from bool, to
9034 // discover this typo:
9035 //
9036 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9037 //
9038 // FIXME: This is an incredibly special case; is there some more general
9039 // way to detect this class of misplaced-parentheses bug?
9040 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009041 // Check last argument of function call to see if it is an
9042 // implicit cast from a type matching the type the result
9043 // is being cast to.
9044 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009045 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009046 Expr *LastA = CEx->getArg(NumArgs - 1);
9047 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009048 if (isa<ImplicitCastExpr>(LastA) &&
9049 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009050 // Warn on this floating-point to bool conversion
9051 DiagnoseImpCast(S, E, T, CC,
9052 diag::warn_impcast_floating_point_to_bool);
9053 }
9054 }
9055 }
John McCall263a48b2010-01-04 23:31:57 +00009056 return;
9057 }
9058
Richard Trieu5b993502014-10-15 03:42:06 +00009059 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009060
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009061 S.DiscardMisalignedMemberAddress(Target, E);
9062
David Blaikie9366d2b2012-06-19 21:19:06 +00009063 if (!Source->isIntegerType() || !Target->isIntegerType())
9064 return;
9065
David Blaikie7555b6a2012-05-15 16:56:36 +00009066 // TODO: remove this early return once the false positives for constant->bool
9067 // in templates, macros, etc, are reduced or removed.
9068 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9069 return;
9070
John McCallcc7e5bf2010-05-06 08:58:33 +00009071 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009072 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009073
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009074 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009075 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009076 // TODO: this should happen for bitfield stores, too.
9077 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009078 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009079 if (S.SourceMgr.isInSystemMacro(CC))
9080 return;
9081
John McCall18a2c2c2010-11-09 22:22:12 +00009082 std::string PrettySourceValue = Value.toString(10);
9083 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009084
Ted Kremenek33ba9952011-10-22 02:37:33 +00009085 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9086 S.PDiag(diag::warn_impcast_integer_precision_constant)
9087 << PrettySourceValue << PrettyTargetValue
9088 << E->getType() << T << E->getSourceRange()
9089 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009090 return;
9091 }
9092
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009093 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9094 if (S.SourceMgr.isInSystemMacro(CC))
9095 return;
9096
David Blaikie9455da02012-04-12 22:40:54 +00009097 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009098 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9099 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009100 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009101 }
9102
Richard Trieudcb55572016-01-29 23:51:16 +00009103 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9104 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9105 // Warn when doing a signed to signed conversion, warn if the positive
9106 // source value is exactly the width of the target type, which will
9107 // cause a negative value to be stored.
9108
9109 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009110 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9111 !S.SourceMgr.isInSystemMacro(CC)) {
9112 if (isSameWidthConstantConversion(S, E, T, CC)) {
9113 std::string PrettySourceValue = Value.toString(10);
9114 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009115
Richard Trieufc404c72016-02-05 23:02:38 +00009116 S.DiagRuntimeBehavior(
9117 E->getExprLoc(), E,
9118 S.PDiag(diag::warn_impcast_integer_precision_constant)
9119 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9120 << E->getSourceRange() << clang::SourceRange(CC));
9121 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009122 }
9123 }
Richard Trieufc404c72016-02-05 23:02:38 +00009124
Richard Trieudcb55572016-01-29 23:51:16 +00009125 // Fall through for non-constants to give a sign conversion warning.
9126 }
9127
John McCallcc7e5bf2010-05-06 08:58:33 +00009128 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9129 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9130 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009131 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009132 return;
9133
John McCallcc7e5bf2010-05-06 08:58:33 +00009134 unsigned DiagID = diag::warn_impcast_integer_sign;
9135
9136 // Traditionally, gcc has warned about this under -Wsign-compare.
9137 // We also want to warn about it in -Wconversion.
9138 // So if -Wconversion is off, use a completely identical diagnostic
9139 // in the sign-compare group.
9140 // The conditional-checking code will
9141 if (ICContext) {
9142 DiagID = diag::warn_impcast_integer_sign_conditional;
9143 *ICContext = true;
9144 }
9145
John McCallacf0ee52010-10-08 02:01:28 +00009146 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009147 }
9148
Douglas Gregora78f1932011-02-22 02:45:07 +00009149 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009150 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9151 // type, to give us better diagnostics.
9152 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009153 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009154 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9155 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9156 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9157 SourceType = S.Context.getTypeDeclType(Enum);
9158 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9159 }
9160 }
9161
Douglas Gregora78f1932011-02-22 02:45:07 +00009162 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9163 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009164 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9165 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009166 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009167 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009168 return;
9169
Douglas Gregor364f7db2011-03-12 00:14:31 +00009170 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009171 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009172 }
John McCall263a48b2010-01-04 23:31:57 +00009173}
9174
David Blaikie18e9ac72012-05-15 21:57:38 +00009175void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9176 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009177
9178void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009179 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009180 E = E->IgnoreParenImpCasts();
9181
9182 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009183 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009184
John McCallacf0ee52010-10-08 02:01:28 +00009185 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009186 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009187 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009188}
9189
David Blaikie18e9ac72012-05-15 21:57:38 +00009190void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9191 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009192 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009193
9194 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009195 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9196 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009197
9198 // If -Wconversion would have warned about either of the candidates
9199 // for a signedness conversion to the context type...
9200 if (!Suspicious) return;
9201
9202 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009203 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009204 return;
9205
John McCallcc7e5bf2010-05-06 08:58:33 +00009206 // ...then check whether it would have warned about either of the
9207 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009208 if (E->getType() == T) return;
9209
9210 Suspicious = false;
9211 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9212 E->getType(), CC, &Suspicious);
9213 if (!Suspicious)
9214 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009215 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009216}
9217
Richard Trieu65724892014-11-15 06:37:39 +00009218/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9219/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009220void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009221 if (S.getLangOpts().Bool)
9222 return;
9223 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9224}
9225
John McCallcc7e5bf2010-05-06 08:58:33 +00009226/// AnalyzeImplicitConversions - Find and report any interesting
9227/// implicit conversions in the given expression. There are a couple
9228/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009229void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009230 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009231 Expr *E = OrigE->IgnoreParenImpCasts();
9232
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009233 if (E->isTypeDependent() || E->isValueDependent())
9234 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009235
John McCallcc7e5bf2010-05-06 08:58:33 +00009236 // For conditional operators, we analyze the arguments as if they
9237 // were being fed directly into the output.
9238 if (isa<ConditionalOperator>(E)) {
9239 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009240 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009241 return;
9242 }
9243
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009244 // Check implicit argument conversions for function calls.
9245 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9246 CheckImplicitArgumentConversions(S, Call, CC);
9247
John McCallcc7e5bf2010-05-06 08:58:33 +00009248 // Go ahead and check any implicit conversions we might have skipped.
9249 // The non-canonical typecheck is just an optimization;
9250 // CheckImplicitConversion will filter out dead implicit conversions.
9251 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009252 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009253
9254 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009255
9256 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9257 // The bound subexpressions in a PseudoObjectExpr are not reachable
9258 // as transitive children.
9259 // FIXME: Use a more uniform representation for this.
9260 for (auto *SE : POE->semantics())
9261 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9262 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009263 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009264
John McCallcc7e5bf2010-05-06 08:58:33 +00009265 // Skip past explicit casts.
9266 if (isa<ExplicitCastExpr>(E)) {
9267 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009268 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009269 }
9270
John McCalld2a53122010-11-09 23:24:47 +00009271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9272 // Do a somewhat different check with comparison operators.
9273 if (BO->isComparisonOp())
9274 return AnalyzeComparison(S, BO);
9275
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009276 // And with simple assignments.
9277 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009278 return AnalyzeAssignment(S, BO);
9279 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009280
9281 // These break the otherwise-useful invariant below. Fortunately,
9282 // we don't really need to recurse into them, because any internal
9283 // expressions should have been analyzed already when they were
9284 // built into statements.
9285 if (isa<StmtExpr>(E)) return;
9286
9287 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009288 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009289
9290 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009291 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009292 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009293 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009294 for (Stmt *SubStmt : E->children()) {
9295 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009296 if (!ChildExpr)
9297 continue;
9298
Richard Trieu955231d2014-01-25 01:10:35 +00009299 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009300 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009301 // Ignore checking string literals that are in logical and operators.
9302 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009303 continue;
9304 AnalyzeImplicitConversions(S, ChildExpr, CC);
9305 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009306
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009307 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009308 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9309 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009310 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009311
9312 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9313 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009314 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009315 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009316
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009317 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9318 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009319 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009320}
9321
9322} // end anonymous namespace
9323
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009324static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
9325 unsigned Start, unsigned End) {
9326 bool IllegalParams = false;
9327 for (unsigned I = Start; I <= End; ++I) {
9328 QualType Ty = TheCall->getArg(I)->getType();
9329 // Taking into account implicit conversions,
9330 // allow any integer within 32 bits range
9331 if (!Ty->isIntegerType() ||
9332 S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
9333 S.Diag(TheCall->getArg(I)->getLocStart(),
9334 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9335 IllegalParams = true;
9336 }
9337 // Potentially emit standard warnings for implicit conversions if enabled
9338 // using -Wconversion.
9339 CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
9340 TheCall->getArg(I)->getLocStart());
9341 }
9342 return IllegalParams;
9343}
9344
Richard Trieuc1888e02014-06-28 23:25:37 +00009345// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9346// Returns true when emitting a warning about taking the address of a reference.
9347static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009348 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009349 E = E->IgnoreParenImpCasts();
9350
9351 const FunctionDecl *FD = nullptr;
9352
9353 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9354 if (!DRE->getDecl()->getType()->isReferenceType())
9355 return false;
9356 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9357 if (!M->getMemberDecl()->getType()->isReferenceType())
9358 return false;
9359 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009360 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009361 return false;
9362 FD = Call->getDirectCallee();
9363 } else {
9364 return false;
9365 }
9366
9367 SemaRef.Diag(E->getExprLoc(), PD);
9368
9369 // If possible, point to location of function.
9370 if (FD) {
9371 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9372 }
9373
9374 return true;
9375}
9376
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009377// Returns true if the SourceLocation is expanded from any macro body.
9378// Returns false if the SourceLocation is invalid, is from not in a macro
9379// expansion, or is from expanded from a top-level macro argument.
9380static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9381 if (Loc.isInvalid())
9382 return false;
9383
9384 while (Loc.isMacroID()) {
9385 if (SM.isMacroBodyExpansion(Loc))
9386 return true;
9387 Loc = SM.getImmediateMacroCallerLoc(Loc);
9388 }
9389
9390 return false;
9391}
9392
Richard Trieu3bb8b562014-02-26 02:36:06 +00009393/// \brief Diagnose pointers that are always non-null.
9394/// \param E the expression containing the pointer
9395/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9396/// compared to a null pointer
9397/// \param IsEqual True when the comparison is equal to a null pointer
9398/// \param Range Extra SourceRange to highlight in the diagnostic
9399void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9400 Expr::NullPointerConstantKind NullKind,
9401 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009402 if (!E)
9403 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009404
9405 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009406 if (E->getExprLoc().isMacroID()) {
9407 const SourceManager &SM = getSourceManager();
9408 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9409 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009410 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009411 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009412 E = E->IgnoreImpCasts();
9413
9414 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9415
Richard Trieuf7432752014-06-06 21:39:26 +00009416 if (isa<CXXThisExpr>(E)) {
9417 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9418 : diag::warn_this_bool_conversion;
9419 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9420 return;
9421 }
9422
Richard Trieu3bb8b562014-02-26 02:36:06 +00009423 bool IsAddressOf = false;
9424
9425 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9426 if (UO->getOpcode() != UO_AddrOf)
9427 return;
9428 IsAddressOf = true;
9429 E = UO->getSubExpr();
9430 }
9431
Richard Trieuc1888e02014-06-28 23:25:37 +00009432 if (IsAddressOf) {
9433 unsigned DiagID = IsCompare
9434 ? diag::warn_address_of_reference_null_compare
9435 : diag::warn_address_of_reference_bool_conversion;
9436 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9437 << IsEqual;
9438 if (CheckForReference(*this, E, PD)) {
9439 return;
9440 }
9441 }
9442
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009443 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9444 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009445 std::string Str;
9446 llvm::raw_string_ostream S(Str);
9447 E->printPretty(S, nullptr, getPrintingPolicy());
9448 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9449 : diag::warn_cast_nonnull_to_bool;
9450 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9451 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009452 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009453 };
9454
9455 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9456 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9457 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009458 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9459 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009460 return;
9461 }
9462 }
9463 }
9464
Richard Trieu3bb8b562014-02-26 02:36:06 +00009465 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009466 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009467 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9468 D = R->getDecl();
9469 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9470 D = M->getMemberDecl();
9471 }
9472
9473 // Weak Decls can be null.
9474 if (!D || D->isWeak())
9475 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009476
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009477 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009478 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9479 if (getCurFunction() &&
9480 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009481 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9482 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009483 return;
9484 }
9485
9486 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009487 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009488 assert(ParamIter != FD->param_end());
9489 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9490
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009491 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9492 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009493 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009494 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009495 }
George Burgess IV850269a2015-12-08 22:02:00 +00009496
9497 for (unsigned ArgNo : NonNull->args()) {
9498 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009499 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009500 return;
9501 }
George Burgess IV850269a2015-12-08 22:02:00 +00009502 }
9503 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009504 }
9505 }
George Burgess IV850269a2015-12-08 22:02:00 +00009506 }
9507
Richard Trieu3bb8b562014-02-26 02:36:06 +00009508 QualType T = D->getType();
9509 const bool IsArray = T->isArrayType();
9510 const bool IsFunction = T->isFunctionType();
9511
Richard Trieuc1888e02014-06-28 23:25:37 +00009512 // Address of function is used to silence the function warning.
9513 if (IsAddressOf && IsFunction) {
9514 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009515 }
9516
9517 // Found nothing.
9518 if (!IsAddressOf && !IsFunction && !IsArray)
9519 return;
9520
9521 // Pretty print the expression for the diagnostic.
9522 std::string Str;
9523 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009524 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009525
9526 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9527 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009528 enum {
9529 AddressOf,
9530 FunctionPointer,
9531 ArrayPointer
9532 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009533 if (IsAddressOf)
9534 DiagType = AddressOf;
9535 else if (IsFunction)
9536 DiagType = FunctionPointer;
9537 else if (IsArray)
9538 DiagType = ArrayPointer;
9539 else
9540 llvm_unreachable("Could not determine diagnostic.");
9541 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9542 << Range << IsEqual;
9543
9544 if (!IsFunction)
9545 return;
9546
9547 // Suggest '&' to silence the function warning.
9548 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9549 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9550
9551 // Check to see if '()' fixit should be emitted.
9552 QualType ReturnType;
9553 UnresolvedSet<4> NonTemplateOverloads;
9554 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9555 if (ReturnType.isNull())
9556 return;
9557
9558 if (IsCompare) {
9559 // There are two cases here. If there is null constant, the only suggest
9560 // for a pointer return type. If the null is 0, then suggest if the return
9561 // type is a pointer or an integer type.
9562 if (!ReturnType->isPointerType()) {
9563 if (NullKind == Expr::NPCK_ZeroExpression ||
9564 NullKind == Expr::NPCK_ZeroLiteral) {
9565 if (!ReturnType->isIntegerType())
9566 return;
9567 } else {
9568 return;
9569 }
9570 }
9571 } else { // !IsCompare
9572 // For function to bool, only suggest if the function pointer has bool
9573 // return type.
9574 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9575 return;
9576 }
9577 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009578 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009579}
9580
John McCallcc7e5bf2010-05-06 08:58:33 +00009581/// Diagnoses "dangerous" implicit conversions within the given
9582/// expression (which is a full expression). Implements -Wconversion
9583/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009584///
9585/// \param CC the "context" location of the implicit conversion, i.e.
9586/// the most location of the syntactic entity requiring the implicit
9587/// conversion
9588void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009589 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009590 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009591 return;
9592
9593 // Don't diagnose for value- or type-dependent expressions.
9594 if (E->isTypeDependent() || E->isValueDependent())
9595 return;
9596
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009597 // Check for array bounds violations in cases where the check isn't triggered
9598 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9599 // ArraySubscriptExpr is on the RHS of a variable initialization.
9600 CheckArrayAccess(E);
9601
John McCallacf0ee52010-10-08 02:01:28 +00009602 // This is not the right CC for (e.g.) a variable initialization.
9603 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009604}
9605
Richard Trieu65724892014-11-15 06:37:39 +00009606/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9607/// Input argument E is a logical expression.
9608void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9609 ::CheckBoolLikeConversion(*this, E, CC);
9610}
9611
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009612/// Diagnose when expression is an integer constant expression and its evaluation
9613/// results in integer overflow
9614void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00009615 // Use a work list to deal with nested struct initializers.
9616 SmallVector<Expr *, 2> Exprs(1, E);
9617
9618 do {
9619 Expr *E = Exprs.pop_back_val();
9620
9621 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9622 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9623 continue;
9624 }
9625
9626 if (auto InitList = dyn_cast<InitListExpr>(E))
9627 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9628 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009629}
9630
Richard Smithc406cb72013-01-17 01:17:56 +00009631namespace {
9632/// \brief Visitor for expressions which looks for unsequenced operations on the
9633/// same object.
9634class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009635 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9636
Richard Smithc406cb72013-01-17 01:17:56 +00009637 /// \brief A tree of sequenced regions within an expression. Two regions are
9638 /// unsequenced if one is an ancestor or a descendent of the other. When we
9639 /// finish processing an expression with sequencing, such as a comma
9640 /// expression, we fold its tree nodes into its parent, since they are
9641 /// unsequenced with respect to nodes we will visit later.
9642 class SequenceTree {
9643 struct Value {
9644 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9645 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009646 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009647 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009648 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009649
9650 public:
9651 /// \brief A region within an expression which may be sequenced with respect
9652 /// to some other region.
9653 class Seq {
9654 explicit Seq(unsigned N) : Index(N) {}
9655 unsigned Index;
9656 friend class SequenceTree;
9657 public:
9658 Seq() : Index(0) {}
9659 };
9660
9661 SequenceTree() { Values.push_back(Value(0)); }
9662 Seq root() const { return Seq(0); }
9663
9664 /// \brief Create a new sequence of operations, which is an unsequenced
9665 /// subset of \p Parent. This sequence of operations is sequenced with
9666 /// respect to other children of \p Parent.
9667 Seq allocate(Seq Parent) {
9668 Values.push_back(Value(Parent.Index));
9669 return Seq(Values.size() - 1);
9670 }
9671
9672 /// \brief Merge a sequence of operations into its parent.
9673 void merge(Seq S) {
9674 Values[S.Index].Merged = true;
9675 }
9676
9677 /// \brief Determine whether two operations are unsequenced. This operation
9678 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9679 /// should have been merged into its parent as appropriate.
9680 bool isUnsequenced(Seq Cur, Seq Old) {
9681 unsigned C = representative(Cur.Index);
9682 unsigned Target = representative(Old.Index);
9683 while (C >= Target) {
9684 if (C == Target)
9685 return true;
9686 C = Values[C].Parent;
9687 }
9688 return false;
9689 }
9690
9691 private:
9692 /// \brief Pick a representative for a sequence.
9693 unsigned representative(unsigned K) {
9694 if (Values[K].Merged)
9695 // Perform path compression as we go.
9696 return Values[K].Parent = representative(Values[K].Parent);
9697 return K;
9698 }
9699 };
9700
9701 /// An object for which we can track unsequenced uses.
9702 typedef NamedDecl *Object;
9703
9704 /// Different flavors of object usage which we track. We only track the
9705 /// least-sequenced usage of each kind.
9706 enum UsageKind {
9707 /// A read of an object. Multiple unsequenced reads are OK.
9708 UK_Use,
9709 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00009710 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00009711 UK_ModAsValue,
9712 /// A modification of an object which is not sequenced before the value
9713 /// computation of the expression, such as n++.
9714 UK_ModAsSideEffect,
9715
9716 UK_Count = UK_ModAsSideEffect + 1
9717 };
9718
9719 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00009720 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00009721 Expr *Use;
9722 SequenceTree::Seq Seq;
9723 };
9724
9725 struct UsageInfo {
9726 UsageInfo() : Diagnosed(false) {}
9727 Usage Uses[UK_Count];
9728 /// Have we issued a diagnostic for this variable already?
9729 bool Diagnosed;
9730 };
9731 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9732
9733 Sema &SemaRef;
9734 /// Sequenced regions within the expression.
9735 SequenceTree Tree;
9736 /// Declaration modifications and references which we have seen.
9737 UsageInfoMap UsageMap;
9738 /// The region we are currently within.
9739 SequenceTree::Seq Region;
9740 /// Filled in with declarations which were modified as a side-effect
9741 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009742 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00009743 /// Expressions to check later. We defer checking these to reduce
9744 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009745 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00009746
9747 /// RAII object wrapping the visitation of a sequenced subexpression of an
9748 /// expression. At the end of this process, the side-effects of the evaluation
9749 /// become sequenced with respect to the value computation of the result, so
9750 /// we downgrade any UK_ModAsSideEffect within the evaluation to
9751 /// UK_ModAsValue.
9752 struct SequencedSubexpression {
9753 SequencedSubexpression(SequenceChecker &Self)
9754 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9755 Self.ModAsSideEffect = &ModAsSideEffect;
9756 }
9757 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +00009758 for (auto &M : llvm::reverse(ModAsSideEffect)) {
9759 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +00009760 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +00009761 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9762 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +00009763 }
9764 Self.ModAsSideEffect = OldModAsSideEffect;
9765 }
9766
9767 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009768 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9769 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00009770 };
9771
Richard Smith40238f02013-06-20 22:21:56 +00009772 /// RAII object wrapping the visitation of a subexpression which we might
9773 /// choose to evaluate as a constant. If any subexpression is evaluated and
9774 /// found to be non-constant, this allows us to suppress the evaluation of
9775 /// the outer expression.
9776 class EvaluationTracker {
9777 public:
9778 EvaluationTracker(SequenceChecker &Self)
9779 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9780 Self.EvalTracker = this;
9781 }
9782 ~EvaluationTracker() {
9783 Self.EvalTracker = Prev;
9784 if (Prev)
9785 Prev->EvalOK &= EvalOK;
9786 }
9787
9788 bool evaluate(const Expr *E, bool &Result) {
9789 if (!EvalOK || E->isValueDependent())
9790 return false;
9791 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9792 return EvalOK;
9793 }
9794
9795 private:
9796 SequenceChecker &Self;
9797 EvaluationTracker *Prev;
9798 bool EvalOK;
9799 } *EvalTracker;
9800
Richard Smithc406cb72013-01-17 01:17:56 +00009801 /// \brief Find the object which is produced by the specified expression,
9802 /// if any.
9803 Object getObject(Expr *E, bool Mod) const {
9804 E = E->IgnoreParenCasts();
9805 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9806 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9807 return getObject(UO->getSubExpr(), Mod);
9808 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9809 if (BO->getOpcode() == BO_Comma)
9810 return getObject(BO->getRHS(), Mod);
9811 if (Mod && BO->isAssignmentOp())
9812 return getObject(BO->getLHS(), Mod);
9813 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9814 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9815 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9816 return ME->getMemberDecl();
9817 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9818 // FIXME: If this is a reference, map through to its value.
9819 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00009820 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00009821 }
9822
9823 /// \brief Note that an object was modified or used by an expression.
9824 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9825 Usage &U = UI.Uses[UK];
9826 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9827 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9828 ModAsSideEffect->push_back(std::make_pair(O, U));
9829 U.Use = Ref;
9830 U.Seq = Region;
9831 }
9832 }
9833 /// \brief Check whether a modification or use conflicts with a prior usage.
9834 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9835 bool IsModMod) {
9836 if (UI.Diagnosed)
9837 return;
9838
9839 const Usage &U = UI.Uses[OtherKind];
9840 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9841 return;
9842
9843 Expr *Mod = U.Use;
9844 Expr *ModOrUse = Ref;
9845 if (OtherKind == UK_Use)
9846 std::swap(Mod, ModOrUse);
9847
9848 SemaRef.Diag(Mod->getExprLoc(),
9849 IsModMod ? diag::warn_unsequenced_mod_mod
9850 : diag::warn_unsequenced_mod_use)
9851 << O << SourceRange(ModOrUse->getExprLoc());
9852 UI.Diagnosed = true;
9853 }
9854
9855 void notePreUse(Object O, Expr *Use) {
9856 UsageInfo &U = UsageMap[O];
9857 // Uses conflict with other modifications.
9858 checkUsage(O, U, Use, UK_ModAsValue, false);
9859 }
9860 void notePostUse(Object O, Expr *Use) {
9861 UsageInfo &U = UsageMap[O];
9862 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9863 addUsage(U, O, Use, UK_Use);
9864 }
9865
9866 void notePreMod(Object O, Expr *Mod) {
9867 UsageInfo &U = UsageMap[O];
9868 // Modifications conflict with other modifications and with uses.
9869 checkUsage(O, U, Mod, UK_ModAsValue, true);
9870 checkUsage(O, U, Mod, UK_Use, false);
9871 }
9872 void notePostMod(Object O, Expr *Use, UsageKind UK) {
9873 UsageInfo &U = UsageMap[O];
9874 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9875 addUsage(U, O, Use, UK);
9876 }
9877
9878public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009879 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00009880 : Base(S.Context), SemaRef(S), Region(Tree.root()),
9881 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00009882 Visit(E);
9883 }
9884
9885 void VisitStmt(Stmt *S) {
9886 // Skip all statements which aren't expressions for now.
9887 }
9888
9889 void VisitExpr(Expr *E) {
9890 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00009891 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00009892 }
9893
9894 void VisitCastExpr(CastExpr *E) {
9895 Object O = Object();
9896 if (E->getCastKind() == CK_LValueToRValue)
9897 O = getObject(E->getSubExpr(), false);
9898
9899 if (O)
9900 notePreUse(O, E);
9901 VisitExpr(E);
9902 if (O)
9903 notePostUse(O, E);
9904 }
9905
9906 void VisitBinComma(BinaryOperator *BO) {
9907 // C++11 [expr.comma]p1:
9908 // Every value computation and side effect associated with the left
9909 // expression is sequenced before every value computation and side
9910 // effect associated with the right expression.
9911 SequenceTree::Seq LHS = Tree.allocate(Region);
9912 SequenceTree::Seq RHS = Tree.allocate(Region);
9913 SequenceTree::Seq OldRegion = Region;
9914
9915 {
9916 SequencedSubexpression SeqLHS(*this);
9917 Region = LHS;
9918 Visit(BO->getLHS());
9919 }
9920
9921 Region = RHS;
9922 Visit(BO->getRHS());
9923
9924 Region = OldRegion;
9925
9926 // Forget that LHS and RHS are sequenced. They are both unsequenced
9927 // with respect to other stuff.
9928 Tree.merge(LHS);
9929 Tree.merge(RHS);
9930 }
9931
9932 void VisitBinAssign(BinaryOperator *BO) {
9933 // The modification is sequenced after the value computation of the LHS
9934 // and RHS, so check it before inspecting the operands and update the
9935 // map afterwards.
9936 Object O = getObject(BO->getLHS(), true);
9937 if (!O)
9938 return VisitExpr(BO);
9939
9940 notePreMod(O, BO);
9941
9942 // C++11 [expr.ass]p7:
9943 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9944 // only once.
9945 //
9946 // Therefore, for a compound assignment operator, O is considered used
9947 // everywhere except within the evaluation of E1 itself.
9948 if (isa<CompoundAssignOperator>(BO))
9949 notePreUse(O, BO);
9950
9951 Visit(BO->getLHS());
9952
9953 if (isa<CompoundAssignOperator>(BO))
9954 notePostUse(O, BO);
9955
9956 Visit(BO->getRHS());
9957
Richard Smith83e37bee2013-06-26 23:16:51 +00009958 // C++11 [expr.ass]p1:
9959 // the assignment is sequenced [...] before the value computation of the
9960 // assignment expression.
9961 // C11 6.5.16/3 has no such rule.
9962 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9963 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009964 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009965
Richard Smithc406cb72013-01-17 01:17:56 +00009966 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9967 VisitBinAssign(CAO);
9968 }
9969
9970 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9971 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9972 void VisitUnaryPreIncDec(UnaryOperator *UO) {
9973 Object O = getObject(UO->getSubExpr(), true);
9974 if (!O)
9975 return VisitExpr(UO);
9976
9977 notePreMod(O, UO);
9978 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00009979 // C++11 [expr.pre.incr]p1:
9980 // the expression ++x is equivalent to x+=1
9981 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9982 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00009983 }
9984
9985 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9986 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9987 void VisitUnaryPostIncDec(UnaryOperator *UO) {
9988 Object O = getObject(UO->getSubExpr(), true);
9989 if (!O)
9990 return VisitExpr(UO);
9991
9992 notePreMod(O, UO);
9993 Visit(UO->getSubExpr());
9994 notePostMod(O, UO, UK_ModAsSideEffect);
9995 }
9996
9997 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9998 void VisitBinLOr(BinaryOperator *BO) {
9999 // The side-effects of the LHS of an '&&' are sequenced before the
10000 // value computation of the RHS, and hence before the value computation
10001 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10002 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010003 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010004 {
10005 SequencedSubexpression Sequenced(*this);
10006 Visit(BO->getLHS());
10007 }
10008
10009 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010010 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010011 if (!Result)
10012 Visit(BO->getRHS());
10013 } else {
10014 // Check for unsequenced operations in the RHS, treating it as an
10015 // entirely separate evaluation.
10016 //
10017 // FIXME: If there are operations in the RHS which are unsequenced
10018 // with respect to operations outside the RHS, and those operations
10019 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010020 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010021 }
Richard Smithc406cb72013-01-17 01:17:56 +000010022 }
10023 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010024 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010025 {
10026 SequencedSubexpression Sequenced(*this);
10027 Visit(BO->getLHS());
10028 }
10029
10030 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010031 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010032 if (Result)
10033 Visit(BO->getRHS());
10034 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010035 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010036 }
Richard Smithc406cb72013-01-17 01:17:56 +000010037 }
10038
10039 // Only visit the condition, unless we can be sure which subexpression will
10040 // be chosen.
10041 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010042 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010043 {
10044 SequencedSubexpression Sequenced(*this);
10045 Visit(CO->getCond());
10046 }
Richard Smithc406cb72013-01-17 01:17:56 +000010047
10048 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010049 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010050 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010051 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010052 WorkList.push_back(CO->getTrueExpr());
10053 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010054 }
Richard Smithc406cb72013-01-17 01:17:56 +000010055 }
10056
Richard Smithe3dbfe02013-06-30 10:40:20 +000010057 void VisitCallExpr(CallExpr *CE) {
10058 // C++11 [intro.execution]p15:
10059 // When calling a function [...], every value computation and side effect
10060 // associated with any argument expression, or with the postfix expression
10061 // designating the called function, is sequenced before execution of every
10062 // expression or statement in the body of the function [and thus before
10063 // the value computation of its result].
10064 SequencedSubexpression Sequenced(*this);
10065 Base::VisitCallExpr(CE);
10066
10067 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10068 }
10069
Richard Smithc406cb72013-01-17 01:17:56 +000010070 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010071 // This is a call, so all subexpressions are sequenced before the result.
10072 SequencedSubexpression Sequenced(*this);
10073
Richard Smithc406cb72013-01-17 01:17:56 +000010074 if (!CCE->isListInitialization())
10075 return VisitExpr(CCE);
10076
10077 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010078 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010079 SequenceTree::Seq Parent = Region;
10080 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10081 E = CCE->arg_end();
10082 I != E; ++I) {
10083 Region = Tree.allocate(Parent);
10084 Elts.push_back(Region);
10085 Visit(*I);
10086 }
10087
10088 // Forget that the initializers are sequenced.
10089 Region = Parent;
10090 for (unsigned I = 0; I < Elts.size(); ++I)
10091 Tree.merge(Elts[I]);
10092 }
10093
10094 void VisitInitListExpr(InitListExpr *ILE) {
10095 if (!SemaRef.getLangOpts().CPlusPlus11)
10096 return VisitExpr(ILE);
10097
10098 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010099 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010100 SequenceTree::Seq Parent = Region;
10101 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10102 Expr *E = ILE->getInit(I);
10103 if (!E) continue;
10104 Region = Tree.allocate(Parent);
10105 Elts.push_back(Region);
10106 Visit(E);
10107 }
10108
10109 // Forget that the initializers are sequenced.
10110 Region = Parent;
10111 for (unsigned I = 0; I < Elts.size(); ++I)
10112 Tree.merge(Elts[I]);
10113 }
10114};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010115} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010116
10117void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010118 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010119 WorkList.push_back(E);
10120 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010121 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010122 SequenceChecker(*this, Item, WorkList);
10123 }
Richard Smithc406cb72013-01-17 01:17:56 +000010124}
10125
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010126void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10127 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010128 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010129 if (!E->isInstantiationDependent())
10130 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010131 if (!IsConstexpr && !E->isValueDependent())
10132 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010133 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010134}
10135
John McCall1f425642010-11-11 03:21:53 +000010136void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10137 FieldDecl *BitField,
10138 Expr *Init) {
10139 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10140}
10141
David Majnemer61a5bbf2015-04-07 22:08:51 +000010142static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10143 SourceLocation Loc) {
10144 if (!PType->isVariablyModifiedType())
10145 return;
10146 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10147 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10148 return;
10149 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010150 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10151 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10152 return;
10153 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010154 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10155 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10156 return;
10157 }
10158
10159 const ArrayType *AT = S.Context.getAsArrayType(PType);
10160 if (!AT)
10161 return;
10162
10163 if (AT->getSizeModifier() != ArrayType::Star) {
10164 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10165 return;
10166 }
10167
10168 S.Diag(Loc, diag::err_array_star_in_function_definition);
10169}
10170
Mike Stump0c2ec772010-01-21 03:59:47 +000010171/// CheckParmsForFunctionDef - Check that the parameters of the given
10172/// function are appropriate for the definition of a function. This
10173/// takes care of any checks that cannot be performed on the
10174/// declaration itself, e.g., that the types of each of the function
10175/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010176bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010177 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010178 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010179 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010180 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10181 // function declarator that is part of a function definition of
10182 // that function shall not have incomplete type.
10183 //
10184 // This is also C++ [dcl.fct]p6.
10185 if (!Param->isInvalidDecl() &&
10186 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010187 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010188 Param->setInvalidDecl();
10189 HasInvalidParm = true;
10190 }
10191
10192 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10193 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010194 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010195 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010196 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010197 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010198 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010199
10200 // C99 6.7.5.3p12:
10201 // If the function declarator is not part of a definition of that
10202 // function, parameters may have incomplete type and may use the [*]
10203 // notation in their sequences of declarator specifiers to specify
10204 // variable length array types.
10205 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010206 // FIXME: This diagnostic should point the '[*]' if source-location
10207 // information is added for it.
10208 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010209
10210 // MSVC destroys objects passed by value in the callee. Therefore a
10211 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010212 // object's destructor. However, we don't perform any direct access check
10213 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010214 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10215 .getCXXABI()
10216 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010217 if (!Param->isInvalidDecl()) {
10218 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10219 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10220 if (!ClassDecl->isInvalidDecl() &&
10221 !ClassDecl->hasIrrelevantDestructor() &&
10222 !ClassDecl->isDependentContext()) {
10223 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10224 MarkFunctionReferenced(Param->getLocation(), Destructor);
10225 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10226 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010227 }
10228 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010229 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010230
10231 // Parameters with the pass_object_size attribute only need to be marked
10232 // constant at function definitions. Because we lack information about
10233 // whether we're on a declaration or definition when we're instantiating the
10234 // attribute, we need to check for constness here.
10235 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10236 if (!Param->getType().isConstQualified())
10237 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10238 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010239 }
10240
10241 return HasInvalidParm;
10242}
John McCall2b5c1b22010-08-12 21:44:57 +000010243
10244/// CheckCastAlign - Implements -Wcast-align, which warns when a
10245/// pointer cast increases the alignment requirements.
10246void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10247 // This is actually a lot of work to potentially be doing on every
10248 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010249 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010250 return;
10251
10252 // Ignore dependent types.
10253 if (T->isDependentType() || Op->getType()->isDependentType())
10254 return;
10255
10256 // Require that the destination be a pointer type.
10257 const PointerType *DestPtr = T->getAs<PointerType>();
10258 if (!DestPtr) return;
10259
10260 // If the destination has alignment 1, we're done.
10261 QualType DestPointee = DestPtr->getPointeeType();
10262 if (DestPointee->isIncompleteType()) return;
10263 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10264 if (DestAlign.isOne()) return;
10265
10266 // Require that the source be a pointer type.
10267 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10268 if (!SrcPtr) return;
10269 QualType SrcPointee = SrcPtr->getPointeeType();
10270
10271 // Whitelist casts from cv void*. We already implicitly
10272 // whitelisted casts to cv void*, since they have alignment 1.
10273 // Also whitelist casts involving incomplete types, which implicitly
10274 // includes 'void'.
10275 if (SrcPointee->isIncompleteType()) return;
10276
10277 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10278 if (SrcAlign >= DestAlign) return;
10279
10280 Diag(TRange.getBegin(), diag::warn_cast_align)
10281 << Op->getType() << T
10282 << static_cast<unsigned>(SrcAlign.getQuantity())
10283 << static_cast<unsigned>(DestAlign.getQuantity())
10284 << TRange << Op->getSourceRange();
10285}
10286
Chandler Carruth28389f02011-08-05 09:10:50 +000010287/// \brief Check whether this array fits the idiom of a size-one tail padded
10288/// array member of a struct.
10289///
10290/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10291/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010292static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010293 const NamedDecl *ND) {
10294 if (Size != 1 || !ND) return false;
10295
10296 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10297 if (!FD) return false;
10298
10299 // Don't consider sizes resulting from macro expansions or template argument
10300 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010301
10302 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010303 while (TInfo) {
10304 TypeLoc TL = TInfo->getTypeLoc();
10305 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010306 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10307 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010308 TInfo = TDL->getTypeSourceInfo();
10309 continue;
10310 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010311 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10312 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010313 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10314 return false;
10315 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010316 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010317 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010318
10319 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010320 if (!RD) return false;
10321 if (RD->isUnion()) return false;
10322 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10323 if (!CRD->isStandardLayout()) return false;
10324 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010325
Benjamin Kramer8c543672011-08-06 03:04:42 +000010326 // See if this is the last field decl in the record.
10327 const Decl *D = FD;
10328 while ((D = D->getNextDeclInContext()))
10329 if (isa<FieldDecl>(D))
10330 return false;
10331 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010332}
10333
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010334void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010335 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010336 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010337 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010338 if (IndexExpr->isValueDependent())
10339 return;
10340
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010341 const Type *EffectiveType =
10342 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010343 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010344 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010345 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010346 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010347 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010348
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010349 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010350 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010351 return;
Richard Smith13f67182011-12-16 19:31:14 +000010352 if (IndexNegated)
10353 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010354
Craig Topperc3ec1492014-05-26 06:22:03 +000010355 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010356 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10357 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010358 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010359 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010360
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010361 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010362 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010363 if (!size.isStrictlyPositive())
10364 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010365
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010366 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010367 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010368 // Make sure we're comparing apples to apples when comparing index to size
10369 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10370 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010371 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010372 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010373 if (ptrarith_typesize != array_typesize) {
10374 // There's a cast to a different size type involved
10375 uint64_t ratio = array_typesize / ptrarith_typesize;
10376 // TODO: Be smarter about handling cases where array_typesize is not a
10377 // multiple of ptrarith_typesize
10378 if (ptrarith_typesize * ratio == array_typesize)
10379 size *= llvm::APInt(size.getBitWidth(), ratio);
10380 }
10381 }
10382
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010383 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010384 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010385 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010386 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010387
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010388 // For array subscripting the index must be less than size, but for pointer
10389 // arithmetic also allow the index (offset) to be equal to size since
10390 // computing the next address after the end of the array is legal and
10391 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010392 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010393 return;
10394
10395 // Also don't warn for arrays of size 1 which are members of some
10396 // structure. These are often used to approximate flexible arrays in C89
10397 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010398 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010399 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010400
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010401 // Suppress the warning if the subscript expression (as identified by the
10402 // ']' location) and the index expression are both from macro expansions
10403 // within a system header.
10404 if (ASE) {
10405 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10406 ASE->getRBracketLoc());
10407 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10408 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10409 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010410 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010411 return;
10412 }
10413 }
10414
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010415 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010416 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010417 DiagID = diag::warn_array_index_exceeds_bounds;
10418
10419 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10420 PDiag(DiagID) << index.toString(10, true)
10421 << size.toString(10, true)
10422 << (unsigned)size.getLimitedValue(~0U)
10423 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010424 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010425 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010426 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010427 DiagID = diag::warn_ptr_arith_precedes_bounds;
10428 if (index.isNegative()) index = -index;
10429 }
10430
10431 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10432 PDiag(DiagID) << index.toString(10, true)
10433 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010434 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010435
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010436 if (!ND) {
10437 // Try harder to find a NamedDecl to point at in the note.
10438 while (const ArraySubscriptExpr *ASE =
10439 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10440 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10441 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10442 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10443 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10444 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10445 }
10446
Chandler Carruth1af88f12011-02-17 21:10:52 +000010447 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010448 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10449 PDiag(diag::note_array_index_out_of_bounds)
10450 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010451}
10452
Ted Kremenekdf26df72011-03-01 18:41:00 +000010453void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010454 int AllowOnePastEnd = 0;
10455 while (expr) {
10456 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010457 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010458 case Stmt::ArraySubscriptExprClass: {
10459 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010460 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010461 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010462 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010463 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010464 case Stmt::OMPArraySectionExprClass: {
10465 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10466 if (ASE->getLowerBound())
10467 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10468 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10469 return;
10470 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010471 case Stmt::UnaryOperatorClass: {
10472 // Only unwrap the * and & unary operators
10473 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10474 expr = UO->getSubExpr();
10475 switch (UO->getOpcode()) {
10476 case UO_AddrOf:
10477 AllowOnePastEnd++;
10478 break;
10479 case UO_Deref:
10480 AllowOnePastEnd--;
10481 break;
10482 default:
10483 return;
10484 }
10485 break;
10486 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010487 case Stmt::ConditionalOperatorClass: {
10488 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10489 if (const Expr *lhs = cond->getLHS())
10490 CheckArrayAccess(lhs);
10491 if (const Expr *rhs = cond->getRHS())
10492 CheckArrayAccess(rhs);
10493 return;
10494 }
10495 default:
10496 return;
10497 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010498 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010499}
John McCall31168b02011-06-15 23:02:42 +000010500
10501//===--- CHECK: Objective-C retain cycles ----------------------------------//
10502
10503namespace {
10504 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010505 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010506 VarDecl *Variable;
10507 SourceRange Range;
10508 SourceLocation Loc;
10509 bool Indirect;
10510
10511 void setLocsFrom(Expr *e) {
10512 Loc = e->getExprLoc();
10513 Range = e->getSourceRange();
10514 }
10515 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010516} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010517
10518/// Consider whether capturing the given variable can possibly lead to
10519/// a retain cycle.
10520static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010521 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010522 // lifetime. In MRR, it's captured strongly if the variable is
10523 // __block and has an appropriate type.
10524 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10525 return false;
10526
10527 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010528 if (ref)
10529 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010530 return true;
10531}
10532
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010533static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010534 while (true) {
10535 e = e->IgnoreParens();
10536 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10537 switch (cast->getCastKind()) {
10538 case CK_BitCast:
10539 case CK_LValueBitCast:
10540 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010541 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010542 e = cast->getSubExpr();
10543 continue;
10544
John McCall31168b02011-06-15 23:02:42 +000010545 default:
10546 return false;
10547 }
10548 }
10549
10550 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10551 ObjCIvarDecl *ivar = ref->getDecl();
10552 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10553 return false;
10554
10555 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010556 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010557 return false;
10558
10559 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10560 owner.Indirect = true;
10561 return true;
10562 }
10563
10564 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10565 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10566 if (!var) return false;
10567 return considerVariable(var, ref, owner);
10568 }
10569
John McCall31168b02011-06-15 23:02:42 +000010570 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10571 if (member->isArrow()) return false;
10572
10573 // Don't count this as an indirect ownership.
10574 e = member->getBase();
10575 continue;
10576 }
10577
John McCallfe96e0b2011-11-06 09:01:30 +000010578 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10579 // Only pay attention to pseudo-objects on property references.
10580 ObjCPropertyRefExpr *pre
10581 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10582 ->IgnoreParens());
10583 if (!pre) return false;
10584 if (pre->isImplicitProperty()) return false;
10585 ObjCPropertyDecl *property = pre->getExplicitProperty();
10586 if (!property->isRetaining() &&
10587 !(property->getPropertyIvarDecl() &&
10588 property->getPropertyIvarDecl()->getType()
10589 .getObjCLifetime() == Qualifiers::OCL_Strong))
10590 return false;
10591
10592 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010593 if (pre->isSuperReceiver()) {
10594 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10595 if (!owner.Variable)
10596 return false;
10597 owner.Loc = pre->getLocation();
10598 owner.Range = pre->getSourceRange();
10599 return true;
10600 }
John McCallfe96e0b2011-11-06 09:01:30 +000010601 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10602 ->getSourceExpr());
10603 continue;
10604 }
10605
John McCall31168b02011-06-15 23:02:42 +000010606 // Array ivars?
10607
10608 return false;
10609 }
10610}
10611
10612namespace {
10613 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10614 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10615 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010616 Context(Context), Variable(variable), Capturer(nullptr),
10617 VarWillBeReased(false) {}
10618 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010619 VarDecl *Variable;
10620 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010621 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010622
10623 void VisitDeclRefExpr(DeclRefExpr *ref) {
10624 if (ref->getDecl() == Variable && !Capturer)
10625 Capturer = ref;
10626 }
10627
John McCall31168b02011-06-15 23:02:42 +000010628 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10629 if (Capturer) return;
10630 Visit(ref->getBase());
10631 if (Capturer && ref->isFreeIvar())
10632 Capturer = ref;
10633 }
10634
10635 void VisitBlockExpr(BlockExpr *block) {
10636 // Look inside nested blocks
10637 if (block->getBlockDecl()->capturesVariable(Variable))
10638 Visit(block->getBlockDecl()->getBody());
10639 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000010640
10641 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10642 if (Capturer) return;
10643 if (OVE->getSourceExpr())
10644 Visit(OVE->getSourceExpr());
10645 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010646 void VisitBinaryOperator(BinaryOperator *BinOp) {
10647 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10648 return;
10649 Expr *LHS = BinOp->getLHS();
10650 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10651 if (DRE->getDecl() != Variable)
10652 return;
10653 if (Expr *RHS = BinOp->getRHS()) {
10654 RHS = RHS->IgnoreParenCasts();
10655 llvm::APSInt Value;
10656 VarWillBeReased =
10657 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10658 }
10659 }
10660 }
John McCall31168b02011-06-15 23:02:42 +000010661 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010662} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010663
10664/// Check whether the given argument is a block which captures a
10665/// variable.
10666static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10667 assert(owner.Variable && owner.Loc.isValid());
10668
10669 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000010670
10671 // Look through [^{...} copy] and Block_copy(^{...}).
10672 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10673 Selector Cmd = ME->getSelector();
10674 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10675 e = ME->getInstanceReceiver();
10676 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000010677 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000010678 e = e->IgnoreParenCasts();
10679 }
10680 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10681 if (CE->getNumArgs() == 1) {
10682 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000010683 if (Fn) {
10684 const IdentifierInfo *FnI = Fn->getIdentifier();
10685 if (FnI && FnI->isStr("_Block_copy")) {
10686 e = CE->getArg(0)->IgnoreParenCasts();
10687 }
10688 }
Jordan Rose67e887c2012-09-17 17:54:30 +000010689 }
10690 }
10691
John McCall31168b02011-06-15 23:02:42 +000010692 BlockExpr *block = dyn_cast<BlockExpr>(e);
10693 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000010694 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000010695
10696 FindCaptureVisitor visitor(S.Context, owner.Variable);
10697 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010698 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000010699}
10700
10701static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10702 RetainCycleOwner &owner) {
10703 assert(capturer);
10704 assert(owner.Variable && owner.Loc.isValid());
10705
10706 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10707 << owner.Variable << capturer->getSourceRange();
10708 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10709 << owner.Indirect << owner.Range;
10710}
10711
10712/// Check for a keyword selector that starts with the word 'add' or
10713/// 'set'.
10714static bool isSetterLikeSelector(Selector sel) {
10715 if (sel.isUnarySelector()) return false;
10716
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010717 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000010718 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010719 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000010720 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000010721 else if (str.startswith("add")) {
10722 // Specially whitelist 'addOperationWithBlock:'.
10723 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10724 return false;
10725 str = str.substr(3);
10726 }
John McCall31168b02011-06-15 23:02:42 +000010727 else
10728 return false;
10729
10730 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000010731 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000010732}
10733
Benjamin Kramer3a743452015-03-09 15:03:32 +000010734static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10735 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010736 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10737 Message->getReceiverInterface(),
10738 NSAPI::ClassId_NSMutableArray);
10739 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010740 return None;
10741 }
10742
10743 Selector Sel = Message->getSelector();
10744
10745 Optional<NSAPI::NSArrayMethodKind> MKOpt =
10746 S.NSAPIObj->getNSArrayMethodKind(Sel);
10747 if (!MKOpt) {
10748 return None;
10749 }
10750
10751 NSAPI::NSArrayMethodKind MK = *MKOpt;
10752
10753 switch (MK) {
10754 case NSAPI::NSMutableArr_addObject:
10755 case NSAPI::NSMutableArr_insertObjectAtIndex:
10756 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10757 return 0;
10758 case NSAPI::NSMutableArr_replaceObjectAtIndex:
10759 return 1;
10760
10761 default:
10762 return None;
10763 }
10764
10765 return None;
10766}
10767
10768static
10769Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10770 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010771 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10772 Message->getReceiverInterface(),
10773 NSAPI::ClassId_NSMutableDictionary);
10774 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010775 return None;
10776 }
10777
10778 Selector Sel = Message->getSelector();
10779
10780 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10781 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10782 if (!MKOpt) {
10783 return None;
10784 }
10785
10786 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10787
10788 switch (MK) {
10789 case NSAPI::NSMutableDict_setObjectForKey:
10790 case NSAPI::NSMutableDict_setValueForKey:
10791 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10792 return 0;
10793
10794 default:
10795 return None;
10796 }
10797
10798 return None;
10799}
10800
10801static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010802 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10803 Message->getReceiverInterface(),
10804 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000010805
Alex Denisov5dfac812015-08-06 04:51:14 +000010806 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10807 Message->getReceiverInterface(),
10808 NSAPI::ClassId_NSMutableOrderedSet);
10809 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010810 return None;
10811 }
10812
10813 Selector Sel = Message->getSelector();
10814
10815 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10816 if (!MKOpt) {
10817 return None;
10818 }
10819
10820 NSAPI::NSSetMethodKind MK = *MKOpt;
10821
10822 switch (MK) {
10823 case NSAPI::NSMutableSet_addObject:
10824 case NSAPI::NSOrderedSet_setObjectAtIndex:
10825 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10826 case NSAPI::NSOrderedSet_insertObjectAtIndex:
10827 return 0;
10828 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10829 return 1;
10830 }
10831
10832 return None;
10833}
10834
10835void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10836 if (!Message->isInstanceMessage()) {
10837 return;
10838 }
10839
10840 Optional<int> ArgOpt;
10841
10842 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10843 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10844 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10845 return;
10846 }
10847
10848 int ArgIndex = *ArgOpt;
10849
Alex Denisove1d882c2015-03-04 17:55:52 +000010850 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10851 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10852 Arg = OE->getSourceExpr()->IgnoreImpCasts();
10853 }
10854
Alex Denisov5dfac812015-08-06 04:51:14 +000010855 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010856 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000010857 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000010858 Diag(Message->getSourceRange().getBegin(),
10859 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000010860 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000010861 }
10862 }
Alex Denisov5dfac812015-08-06 04:51:14 +000010863 } else {
10864 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10865
10866 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10867 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10868 }
10869
10870 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10871 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10872 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10873 ValueDecl *Decl = ReceiverRE->getDecl();
10874 Diag(Message->getSourceRange().getBegin(),
10875 diag::warn_objc_circular_container)
10876 << Decl->getName() << Decl->getName();
10877 if (!ArgRE->isObjCSelfExpr()) {
10878 Diag(Decl->getLocation(),
10879 diag::note_objc_circular_container_declared_here)
10880 << Decl->getName();
10881 }
10882 }
10883 }
10884 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10885 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10886 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10887 ObjCIvarDecl *Decl = IvarRE->getDecl();
10888 Diag(Message->getSourceRange().getBegin(),
10889 diag::warn_objc_circular_container)
10890 << Decl->getName() << Decl->getName();
10891 Diag(Decl->getLocation(),
10892 diag::note_objc_circular_container_declared_here)
10893 << Decl->getName();
10894 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010895 }
10896 }
10897 }
Alex Denisove1d882c2015-03-04 17:55:52 +000010898}
10899
John McCall31168b02011-06-15 23:02:42 +000010900/// Check a message send to see if it's likely to cause a retain cycle.
10901void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10902 // Only check instance methods whose selector looks like a setter.
10903 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10904 return;
10905
10906 // Try to find a variable that the receiver is strongly owned by.
10907 RetainCycleOwner owner;
10908 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010909 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000010910 return;
10911 } else {
10912 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10913 owner.Variable = getCurMethodDecl()->getSelfDecl();
10914 owner.Loc = msg->getSuperLoc();
10915 owner.Range = msg->getSuperLoc();
10916 }
10917
10918 // Check whether the receiver is captured by any of the arguments.
10919 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10920 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10921 return diagnoseRetainCycle(*this, capturer, owner);
10922}
10923
10924/// Check a property assign to see if it's likely to cause a retain cycle.
10925void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10926 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010927 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000010928 return;
10929
10930 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10931 diagnoseRetainCycle(*this, capturer, owner);
10932}
10933
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010934void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10935 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000010936 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010937 return;
10938
10939 // Because we don't have an expression for the variable, we have to set the
10940 // location explicitly here.
10941 Owner.Loc = Var->getLocation();
10942 Owner.Range = Var->getSourceRange();
10943
10944 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10945 diagnoseRetainCycle(*this, Capturer, Owner);
10946}
10947
Ted Kremenek9304da92012-12-21 08:04:28 +000010948static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10949 Expr *RHS, bool isProperty) {
10950 // Check if RHS is an Objective-C object literal, which also can get
10951 // immediately zapped in a weak reference. Note that we explicitly
10952 // allow ObjCStringLiterals, since those are designed to never really die.
10953 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010954
Ted Kremenek64873352012-12-21 22:46:35 +000010955 // This enum needs to match with the 'select' in
10956 // warn_objc_arc_literal_assign (off-by-1).
10957 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10958 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10959 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010960
10961 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000010962 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000010963 << (isProperty ? 0 : 1)
10964 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000010965
10966 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000010967}
10968
Ted Kremenekc1f014a2012-12-21 19:45:30 +000010969static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10970 Qualifiers::ObjCLifetime LT,
10971 Expr *RHS, bool isProperty) {
10972 // Strip off any implicit cast added to get to the one ARC-specific.
10973 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10974 if (cast->getCastKind() == CK_ARCConsumeObject) {
10975 S.Diag(Loc, diag::warn_arc_retained_assign)
10976 << (LT == Qualifiers::OCL_ExplicitNone)
10977 << (isProperty ? 0 : 1)
10978 << RHS->getSourceRange();
10979 return true;
10980 }
10981 RHS = cast->getSubExpr();
10982 }
10983
10984 if (LT == Qualifiers::OCL_Weak &&
10985 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10986 return true;
10987
10988 return false;
10989}
10990
Ted Kremenekb36234d2012-12-21 08:04:20 +000010991bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10992 QualType LHS, Expr *RHS) {
10993 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10994
10995 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10996 return false;
10997
10998 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10999 return true;
11000
11001 return false;
11002}
11003
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011004void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11005 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011006 QualType LHSType;
11007 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011008 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011009 ObjCPropertyRefExpr *PRE
11010 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11011 if (PRE && !PRE->isImplicitProperty()) {
11012 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11013 if (PD)
11014 LHSType = PD->getType();
11015 }
11016
11017 if (LHSType.isNull())
11018 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011019
11020 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11021
11022 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011023 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011024 getCurFunction()->markSafeWeakUse(LHS);
11025 }
11026
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011027 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11028 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011029
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011030 // FIXME. Check for other life times.
11031 if (LT != Qualifiers::OCL_None)
11032 return;
11033
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011034 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011035 if (PRE->isImplicitProperty())
11036 return;
11037 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11038 if (!PD)
11039 return;
11040
Bill Wendling44426052012-12-20 19:22:21 +000011041 unsigned Attributes = PD->getPropertyAttributes();
11042 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011043 // when 'assign' attribute was not explicitly specified
11044 // by user, ignore it and rely on property type itself
11045 // for lifetime info.
11046 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11047 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11048 LHSType->isObjCRetainableType())
11049 return;
11050
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011051 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011052 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011053 Diag(Loc, diag::warn_arc_retained_property_assign)
11054 << RHS->getSourceRange();
11055 return;
11056 }
11057 RHS = cast->getSubExpr();
11058 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011059 }
Bill Wendling44426052012-12-20 19:22:21 +000011060 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011061 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11062 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011063 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011064 }
11065}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011066
11067//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11068
11069namespace {
11070bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11071 SourceLocation StmtLoc,
11072 const NullStmt *Body) {
11073 // Do not warn if the body is a macro that expands to nothing, e.g:
11074 //
11075 // #define CALL(x)
11076 // if (condition)
11077 // CALL(0);
11078 //
11079 if (Body->hasLeadingEmptyMacro())
11080 return false;
11081
11082 // Get line numbers of statement and body.
11083 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011084 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011085 &StmtLineInvalid);
11086 if (StmtLineInvalid)
11087 return false;
11088
11089 bool BodyLineInvalid;
11090 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11091 &BodyLineInvalid);
11092 if (BodyLineInvalid)
11093 return false;
11094
11095 // Warn if null statement and body are on the same line.
11096 if (StmtLine != BodyLine)
11097 return false;
11098
11099 return true;
11100}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011101} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011102
11103void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11104 const Stmt *Body,
11105 unsigned DiagID) {
11106 // Since this is a syntactic check, don't emit diagnostic for template
11107 // instantiations, this just adds noise.
11108 if (CurrentInstantiationScope)
11109 return;
11110
11111 // The body should be a null statement.
11112 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11113 if (!NBody)
11114 return;
11115
11116 // Do the usual checks.
11117 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11118 return;
11119
11120 Diag(NBody->getSemiLoc(), DiagID);
11121 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11122}
11123
11124void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11125 const Stmt *PossibleBody) {
11126 assert(!CurrentInstantiationScope); // Ensured by caller
11127
11128 SourceLocation StmtLoc;
11129 const Stmt *Body;
11130 unsigned DiagID;
11131 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11132 StmtLoc = FS->getRParenLoc();
11133 Body = FS->getBody();
11134 DiagID = diag::warn_empty_for_body;
11135 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11136 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11137 Body = WS->getBody();
11138 DiagID = diag::warn_empty_while_body;
11139 } else
11140 return; // Neither `for' nor `while'.
11141
11142 // The body should be a null statement.
11143 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11144 if (!NBody)
11145 return;
11146
11147 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011148 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011149 return;
11150
11151 // Do the usual checks.
11152 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11153 return;
11154
11155 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11156 // noise level low, emit diagnostics only if for/while is followed by a
11157 // CompoundStmt, e.g.:
11158 // for (int i = 0; i < n; i++);
11159 // {
11160 // a(i);
11161 // }
11162 // or if for/while is followed by a statement with more indentation
11163 // than for/while itself:
11164 // for (int i = 0; i < n; i++);
11165 // a(i);
11166 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11167 if (!ProbableTypo) {
11168 bool BodyColInvalid;
11169 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11170 PossibleBody->getLocStart(),
11171 &BodyColInvalid);
11172 if (BodyColInvalid)
11173 return;
11174
11175 bool StmtColInvalid;
11176 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11177 S->getLocStart(),
11178 &StmtColInvalid);
11179 if (StmtColInvalid)
11180 return;
11181
11182 if (BodyCol > StmtCol)
11183 ProbableTypo = true;
11184 }
11185
11186 if (ProbableTypo) {
11187 Diag(NBody->getSemiLoc(), DiagID);
11188 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11189 }
11190}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011191
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011192//===--- CHECK: Warn on self move with std::move. -------------------------===//
11193
11194/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11195void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11196 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011197 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11198 return;
11199
11200 if (!ActiveTemplateInstantiations.empty())
11201 return;
11202
11203 // Strip parens and casts away.
11204 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11205 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11206
11207 // Check for a call expression
11208 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11209 if (!CE || CE->getNumArgs() != 1)
11210 return;
11211
11212 // Check for a call to std::move
11213 const FunctionDecl *FD = CE->getDirectCallee();
11214 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11215 !FD->getIdentifier()->isStr("move"))
11216 return;
11217
11218 // Get argument from std::move
11219 RHSExpr = CE->getArg(0);
11220
11221 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11222 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11223
11224 // Two DeclRefExpr's, check that the decls are the same.
11225 if (LHSDeclRef && RHSDeclRef) {
11226 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11227 return;
11228 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11229 RHSDeclRef->getDecl()->getCanonicalDecl())
11230 return;
11231
11232 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11233 << LHSExpr->getSourceRange()
11234 << RHSExpr->getSourceRange();
11235 return;
11236 }
11237
11238 // Member variables require a different approach to check for self moves.
11239 // MemberExpr's are the same if every nested MemberExpr refers to the same
11240 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11241 // the base Expr's are CXXThisExpr's.
11242 const Expr *LHSBase = LHSExpr;
11243 const Expr *RHSBase = RHSExpr;
11244 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11245 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11246 if (!LHSME || !RHSME)
11247 return;
11248
11249 while (LHSME && RHSME) {
11250 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11251 RHSME->getMemberDecl()->getCanonicalDecl())
11252 return;
11253
11254 LHSBase = LHSME->getBase();
11255 RHSBase = RHSME->getBase();
11256 LHSME = dyn_cast<MemberExpr>(LHSBase);
11257 RHSME = dyn_cast<MemberExpr>(RHSBase);
11258 }
11259
11260 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11261 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11262 if (LHSDeclRef && RHSDeclRef) {
11263 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11264 return;
11265 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11266 RHSDeclRef->getDecl()->getCanonicalDecl())
11267 return;
11268
11269 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11270 << LHSExpr->getSourceRange()
11271 << RHSExpr->getSourceRange();
11272 return;
11273 }
11274
11275 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11276 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11277 << LHSExpr->getSourceRange()
11278 << RHSExpr->getSourceRange();
11279}
11280
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011281//===--- Layout compatibility ----------------------------------------------//
11282
11283namespace {
11284
11285bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11286
11287/// \brief Check if two enumeration types are layout-compatible.
11288bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11289 // C++11 [dcl.enum] p8:
11290 // Two enumeration types are layout-compatible if they have the same
11291 // underlying type.
11292 return ED1->isComplete() && ED2->isComplete() &&
11293 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11294}
11295
11296/// \brief Check if two fields are layout-compatible.
11297bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11298 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11299 return false;
11300
11301 if (Field1->isBitField() != Field2->isBitField())
11302 return false;
11303
11304 if (Field1->isBitField()) {
11305 // Make sure that the bit-fields are the same length.
11306 unsigned Bits1 = Field1->getBitWidthValue(C);
11307 unsigned Bits2 = Field2->getBitWidthValue(C);
11308
11309 if (Bits1 != Bits2)
11310 return false;
11311 }
11312
11313 return true;
11314}
11315
11316/// \brief Check if two standard-layout structs are layout-compatible.
11317/// (C++11 [class.mem] p17)
11318bool isLayoutCompatibleStruct(ASTContext &C,
11319 RecordDecl *RD1,
11320 RecordDecl *RD2) {
11321 // If both records are C++ classes, check that base classes match.
11322 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11323 // If one of records is a CXXRecordDecl we are in C++ mode,
11324 // thus the other one is a CXXRecordDecl, too.
11325 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11326 // Check number of base classes.
11327 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11328 return false;
11329
11330 // Check the base classes.
11331 for (CXXRecordDecl::base_class_const_iterator
11332 Base1 = D1CXX->bases_begin(),
11333 BaseEnd1 = D1CXX->bases_end(),
11334 Base2 = D2CXX->bases_begin();
11335 Base1 != BaseEnd1;
11336 ++Base1, ++Base2) {
11337 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11338 return false;
11339 }
11340 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11341 // If only RD2 is a C++ class, it should have zero base classes.
11342 if (D2CXX->getNumBases() > 0)
11343 return false;
11344 }
11345
11346 // Check the fields.
11347 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11348 Field2End = RD2->field_end(),
11349 Field1 = RD1->field_begin(),
11350 Field1End = RD1->field_end();
11351 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11352 if (!isLayoutCompatible(C, *Field1, *Field2))
11353 return false;
11354 }
11355 if (Field1 != Field1End || Field2 != Field2End)
11356 return false;
11357
11358 return true;
11359}
11360
11361/// \brief Check if two standard-layout unions are layout-compatible.
11362/// (C++11 [class.mem] p18)
11363bool isLayoutCompatibleUnion(ASTContext &C,
11364 RecordDecl *RD1,
11365 RecordDecl *RD2) {
11366 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011367 for (auto *Field2 : RD2->fields())
11368 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011369
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011370 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011371 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11372 I = UnmatchedFields.begin(),
11373 E = UnmatchedFields.end();
11374
11375 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011376 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011377 bool Result = UnmatchedFields.erase(*I);
11378 (void) Result;
11379 assert(Result);
11380 break;
11381 }
11382 }
11383 if (I == E)
11384 return false;
11385 }
11386
11387 return UnmatchedFields.empty();
11388}
11389
11390bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11391 if (RD1->isUnion() != RD2->isUnion())
11392 return false;
11393
11394 if (RD1->isUnion())
11395 return isLayoutCompatibleUnion(C, RD1, RD2);
11396 else
11397 return isLayoutCompatibleStruct(C, RD1, RD2);
11398}
11399
11400/// \brief Check if two types are layout-compatible in C++11 sense.
11401bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11402 if (T1.isNull() || T2.isNull())
11403 return false;
11404
11405 // C++11 [basic.types] p11:
11406 // If two types T1 and T2 are the same type, then T1 and T2 are
11407 // layout-compatible types.
11408 if (C.hasSameType(T1, T2))
11409 return true;
11410
11411 T1 = T1.getCanonicalType().getUnqualifiedType();
11412 T2 = T2.getCanonicalType().getUnqualifiedType();
11413
11414 const Type::TypeClass TC1 = T1->getTypeClass();
11415 const Type::TypeClass TC2 = T2->getTypeClass();
11416
11417 if (TC1 != TC2)
11418 return false;
11419
11420 if (TC1 == Type::Enum) {
11421 return isLayoutCompatible(C,
11422 cast<EnumType>(T1)->getDecl(),
11423 cast<EnumType>(T2)->getDecl());
11424 } else if (TC1 == Type::Record) {
11425 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11426 return false;
11427
11428 return isLayoutCompatible(C,
11429 cast<RecordType>(T1)->getDecl(),
11430 cast<RecordType>(T2)->getDecl());
11431 }
11432
11433 return false;
11434}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011435} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011436
11437//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11438
11439namespace {
11440/// \brief Given a type tag expression find the type tag itself.
11441///
11442/// \param TypeExpr Type tag expression, as it appears in user's code.
11443///
11444/// \param VD Declaration of an identifier that appears in a type tag.
11445///
11446/// \param MagicValue Type tag magic value.
11447bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11448 const ValueDecl **VD, uint64_t *MagicValue) {
11449 while(true) {
11450 if (!TypeExpr)
11451 return false;
11452
11453 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11454
11455 switch (TypeExpr->getStmtClass()) {
11456 case Stmt::UnaryOperatorClass: {
11457 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11458 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11459 TypeExpr = UO->getSubExpr();
11460 continue;
11461 }
11462 return false;
11463 }
11464
11465 case Stmt::DeclRefExprClass: {
11466 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11467 *VD = DRE->getDecl();
11468 return true;
11469 }
11470
11471 case Stmt::IntegerLiteralClass: {
11472 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11473 llvm::APInt MagicValueAPInt = IL->getValue();
11474 if (MagicValueAPInt.getActiveBits() <= 64) {
11475 *MagicValue = MagicValueAPInt.getZExtValue();
11476 return true;
11477 } else
11478 return false;
11479 }
11480
11481 case Stmt::BinaryConditionalOperatorClass:
11482 case Stmt::ConditionalOperatorClass: {
11483 const AbstractConditionalOperator *ACO =
11484 cast<AbstractConditionalOperator>(TypeExpr);
11485 bool Result;
11486 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11487 if (Result)
11488 TypeExpr = ACO->getTrueExpr();
11489 else
11490 TypeExpr = ACO->getFalseExpr();
11491 continue;
11492 }
11493 return false;
11494 }
11495
11496 case Stmt::BinaryOperatorClass: {
11497 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11498 if (BO->getOpcode() == BO_Comma) {
11499 TypeExpr = BO->getRHS();
11500 continue;
11501 }
11502 return false;
11503 }
11504
11505 default:
11506 return false;
11507 }
11508 }
11509}
11510
11511/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11512///
11513/// \param TypeExpr Expression that specifies a type tag.
11514///
11515/// \param MagicValues Registered magic values.
11516///
11517/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11518/// kind.
11519///
11520/// \param TypeInfo Information about the corresponding C type.
11521///
11522/// \returns true if the corresponding C type was found.
11523bool GetMatchingCType(
11524 const IdentifierInfo *ArgumentKind,
11525 const Expr *TypeExpr, const ASTContext &Ctx,
11526 const llvm::DenseMap<Sema::TypeTagMagicValue,
11527 Sema::TypeTagData> *MagicValues,
11528 bool &FoundWrongKind,
11529 Sema::TypeTagData &TypeInfo) {
11530 FoundWrongKind = false;
11531
11532 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011533 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011534
11535 uint64_t MagicValue;
11536
11537 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11538 return false;
11539
11540 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011541 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011542 if (I->getArgumentKind() != ArgumentKind) {
11543 FoundWrongKind = true;
11544 return false;
11545 }
11546 TypeInfo.Type = I->getMatchingCType();
11547 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11548 TypeInfo.MustBeNull = I->getMustBeNull();
11549 return true;
11550 }
11551 return false;
11552 }
11553
11554 if (!MagicValues)
11555 return false;
11556
11557 llvm::DenseMap<Sema::TypeTagMagicValue,
11558 Sema::TypeTagData>::const_iterator I =
11559 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11560 if (I == MagicValues->end())
11561 return false;
11562
11563 TypeInfo = I->second;
11564 return true;
11565}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011566} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011567
11568void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11569 uint64_t MagicValue, QualType Type,
11570 bool LayoutCompatible,
11571 bool MustBeNull) {
11572 if (!TypeTagForDatatypeMagicValues)
11573 TypeTagForDatatypeMagicValues.reset(
11574 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11575
11576 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11577 (*TypeTagForDatatypeMagicValues)[Magic] =
11578 TypeTagData(Type, LayoutCompatible, MustBeNull);
11579}
11580
11581namespace {
11582bool IsSameCharType(QualType T1, QualType T2) {
11583 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11584 if (!BT1)
11585 return false;
11586
11587 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11588 if (!BT2)
11589 return false;
11590
11591 BuiltinType::Kind T1Kind = BT1->getKind();
11592 BuiltinType::Kind T2Kind = BT2->getKind();
11593
11594 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11595 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11596 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11597 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11598}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011599} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011600
11601void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11602 const Expr * const *ExprArgs) {
11603 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11604 bool IsPointerAttr = Attr->getIsPointer();
11605
11606 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11607 bool FoundWrongKind;
11608 TypeTagData TypeInfo;
11609 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11610 TypeTagForDatatypeMagicValues.get(),
11611 FoundWrongKind, TypeInfo)) {
11612 if (FoundWrongKind)
11613 Diag(TypeTagExpr->getExprLoc(),
11614 diag::warn_type_tag_for_datatype_wrong_kind)
11615 << TypeTagExpr->getSourceRange();
11616 return;
11617 }
11618
11619 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11620 if (IsPointerAttr) {
11621 // Skip implicit cast of pointer to `void *' (as a function argument).
11622 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011623 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011624 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011625 ArgumentExpr = ICE->getSubExpr();
11626 }
11627 QualType ArgumentType = ArgumentExpr->getType();
11628
11629 // Passing a `void*' pointer shouldn't trigger a warning.
11630 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11631 return;
11632
11633 if (TypeInfo.MustBeNull) {
11634 // Type tag with matching void type requires a null pointer.
11635 if (!ArgumentExpr->isNullPointerConstant(Context,
11636 Expr::NPC_ValueDependentIsNotNull)) {
11637 Diag(ArgumentExpr->getExprLoc(),
11638 diag::warn_type_safety_null_pointer_required)
11639 << ArgumentKind->getName()
11640 << ArgumentExpr->getSourceRange()
11641 << TypeTagExpr->getSourceRange();
11642 }
11643 return;
11644 }
11645
11646 QualType RequiredType = TypeInfo.Type;
11647 if (IsPointerAttr)
11648 RequiredType = Context.getPointerType(RequiredType);
11649
11650 bool mismatch = false;
11651 if (!TypeInfo.LayoutCompatible) {
11652 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11653
11654 // C++11 [basic.fundamental] p1:
11655 // Plain char, signed char, and unsigned char are three distinct types.
11656 //
11657 // But we treat plain `char' as equivalent to `signed char' or `unsigned
11658 // char' depending on the current char signedness mode.
11659 if (mismatch)
11660 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11661 RequiredType->getPointeeType())) ||
11662 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11663 mismatch = false;
11664 } else
11665 if (IsPointerAttr)
11666 mismatch = !isLayoutCompatible(Context,
11667 ArgumentType->getPointeeType(),
11668 RequiredType->getPointeeType());
11669 else
11670 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11671
11672 if (mismatch)
11673 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000011674 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011675 << TypeInfo.LayoutCompatible << RequiredType
11676 << ArgumentExpr->getSourceRange()
11677 << TypeTagExpr->getSourceRange();
11678}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011679
11680void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11681 CharUnits Alignment) {
11682 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11683}
11684
11685void Sema::DiagnoseMisalignedMembers() {
11686 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000011687 const NamedDecl *ND = m.RD;
11688 if (ND->getName().empty()) {
11689 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11690 ND = TD;
11691 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011692 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000011693 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011694 }
11695 MisalignedMembers.clear();
11696}
11697
11698void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11699 if (!T->isPointerType())
11700 return;
11701 if (isa<UnaryOperator>(E) &&
11702 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11703 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11704 if (isa<MemberExpr>(Op)) {
11705 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11706 MisalignedMember(Op));
11707 if (MA != MisalignedMembers.end() &&
11708 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11709 MisalignedMembers.erase(MA);
11710 }
11711 }
11712}
11713
11714void Sema::RefersToMemberWithReducedAlignment(
11715 Expr *E,
11716 std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11717 const auto *ME = dyn_cast<MemberExpr>(E);
11718 while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11719 QualType BaseType = ME->getBase()->getType();
11720 if (ME->isArrow())
11721 BaseType = BaseType->getPointeeType();
11722 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11723
11724 ValueDecl *MD = ME->getMemberDecl();
11725 bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11726 if (ByteAligned) // Attribute packed does not have any effect.
11727 break;
11728
11729 if (!ByteAligned &&
11730 (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11731 CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11732 Context.getTypeAlignInChars(BaseType));
11733 // Notify that this expression designates a member with reduced alignment
11734 Action(E, RD, MD, Alignment);
11735 break;
11736 }
11737 ME = dyn_cast<MemberExpr>(ME->getBase());
11738 }
11739}
11740
11741void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11742 using namespace std::placeholders;
11743 RefersToMemberWithReducedAlignment(
11744 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11745 _2, _3, _4));
11746}
11747