blob: b2223b75506142c798d3ccd88adc457ae353cf07 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb87b1b32007-08-10 20:18:51 +000015#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000020#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000021#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000022#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000023#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000035#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000039#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000040#include "llvm/Support/Format.h"
41#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000043
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000045using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000046
Chris Lattnera26fb342009-02-18 17:49:48 +000047SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000049 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000051}
52
John McCallbebede42011-02-26 05:39:39 +000053/// Checks that a call expression's argument count is the desired number.
54/// This is useful when doing custom type-checking. Returns true on error.
55static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56 unsigned argCount = call->getNumArgs();
57 if (argCount == desiredArgCount) return false;
58
59 if (argCount < desiredArgCount)
60 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 /*function call*/ << desiredArgCount << argCount
62 << call->getSourceRange();
63
64 // Highlight all the excess arguments.
65 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66 call->getArg(argCount - 1)->getLocEnd());
67
68 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 /*function call*/ << desiredArgCount << argCount
70 << call->getArg(1)->getSourceRange();
71}
72
Julien Lerouge4a5b4442012-04-28 17:39:16 +000073/// Check that the first argument to __builtin_annotation is an integer
74/// and the second argument is a non-wide string literal.
75static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76 if (checkArgCount(S, TheCall, 2))
77 return true;
78
79 // First argument should be an integer.
80 Expr *ValArg = TheCall->getArg(0);
81 QualType Ty = ValArg->getType();
82 if (!Ty->isIntegerType()) {
83 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000085 return true;
86 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000087
88 // Second argument should be a constant string.
89 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91 if (!Literal || !Literal->isAscii()) {
92 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93 << StrArg->getSourceRange();
94 return true;
95 }
96
97 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000098 return false;
99}
100
Richard Smith6cbd65d2013-07-11 02:27:57 +0000101/// Check that the argument to __builtin_addressof is a glvalue, and set the
102/// result type to the corresponding pointer type.
103static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104 if (checkArgCount(S, TheCall, 1))
105 return true;
106
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000107 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000108 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109 if (ResultType.isNull())
110 return true;
111
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000112 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000113 TheCall->setType(ResultType);
114 return false;
115}
116
John McCall03107a42015-10-29 20:48:01 +0000117static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118 if (checkArgCount(S, TheCall, 3))
119 return true;
120
121 // First two arguments should be integers.
122 for (unsigned I = 0; I < 2; ++I) {
123 Expr *Arg = TheCall->getArg(I);
124 QualType Ty = Arg->getType();
125 if (!Ty->isIntegerType()) {
126 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127 << Ty << Arg->getSourceRange();
128 return true;
129 }
130 }
131
132 // Third argument should be a pointer to a non-const integer.
133 // IRGen correctly handles volatile, restrict, and address spaces, and
134 // the other qualifiers aren't possible.
135 {
136 Expr *Arg = TheCall->getArg(2);
137 QualType Ty = Arg->getType();
138 const auto *PtrTy = Ty->getAs<PointerType>();
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
141 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142 << Ty << Arg->getSourceRange();
143 return true;
144 }
145 }
146
147 return false;
148}
149
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000150static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 CallExpr *TheCall, unsigned SizeIdx,
152 unsigned DstSizeIdx) {
153 if (TheCall->getNumArgs() <= SizeIdx ||
154 TheCall->getNumArgs() <= DstSizeIdx)
155 return;
156
157 const Expr *SizeArg = TheCall->getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159
160 llvm::APSInt Size, DstSize;
161
162 // find out if both sizes are known at compile time
163 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165 return;
166
167 if (Size.ule(DstSize))
168 return;
169
170 // confirmed overflow so generate the diagnostic.
171 IdentifierInfo *FnName = FDecl->getIdentifier();
172 SourceLocation SL = TheCall->getLocStart();
173 SourceRange SR = TheCall->getSourceRange();
174
175 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176}
177
Peter Collingbournef7706832014-12-12 23:41:25 +0000178static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179 if (checkArgCount(S, BuiltinCall, 2))
180 return true;
181
182 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184 Expr *Call = BuiltinCall->getArg(0);
185 Expr *Chain = BuiltinCall->getArg(1);
186
187 if (Call->getStmtClass() != Stmt::CallExprClass) {
188 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189 << Call->getSourceRange();
190 return true;
191 }
192
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196 << Call->getSourceRange();
197 return true;
198 }
199
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204 << Call->getSourceRange();
205 return true;
206 }
207
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210 << Call->getSourceRange();
211 return true;
212 }
213
214 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215 if (ChainResult.isInvalid())
216 return true;
217 if (!ChainResult.get()->getType()->isPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219 << Chain->getSourceRange();
220 return true;
221 }
222
David Majnemerced8bdf2015-02-25 17:36:15 +0000223 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000224 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225 QualType BuiltinTy = S.Context.getFunctionType(
226 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228
229 Builtin =
230 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231
232 BuiltinCall->setType(CE->getType());
233 BuiltinCall->setValueKind(CE->getValueKind());
234 BuiltinCall->setObjectKind(CE->getObjectKind());
235 BuiltinCall->setCallee(Builtin);
236 BuiltinCall->setArg(1, ChainResult.get());
237
238 return false;
239}
240
Reid Kleckner1d59f992015-01-22 01:36:17 +0000241static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242 Scope::ScopeFlags NeededScopeFlags,
243 unsigned DiagID) {
244 // Scopes aren't available during instantiation. Fortunately, builtin
245 // functions cannot be template args so they cannot be formed through template
246 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000247 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000248 return false;
249
250 Scope *S = SemaRef.getCurScope();
251 while (S && !S->isSEHExceptScope())
252 S = S->getParent();
253 if (!S || !(S->getFlags() & NeededScopeFlags)) {
254 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256 << DRE->getDecl()->getIdentifier();
257 return true;
258 }
259
260 return false;
261}
262
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000263static inline bool isBlockPointer(Expr *Arg) {
264 return Arg->getType()->isBlockPointerType();
265}
266
267/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268/// void*, which is a requirement of device side enqueue.
269static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270 const BlockPointerType *BPT =
271 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272 ArrayRef<QualType> Params =
273 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274 unsigned ArgCounter = 0;
275 bool IllegalParams = false;
276 // Iterate through the block parameters until either one is found that is not
277 // a local void*, or the block is valid.
278 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279 I != E; ++I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282 LangAS::opencl_local) {
283 // Get the location of the error. If a block literal has been passed
284 // (BlockExpr) then we can point straight to the offending argument,
285 // else we just point to the variable reference.
286 SourceLocation ErrorLoc;
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290 } else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292 }
293 S.Diag(ErrorLoc,
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams = true;
296 }
297 }
298
299 return IllegalParams;
300}
301
302/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303/// get_kernel_work_group_size
304/// and get_kernel_preferred_work_group_size_multiple builtin functions.
305static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306 if (checkArgCount(S, TheCall, 1))
307 return true;
308
309 Expr *BlockArg = TheCall->getArg(0);
310 if (!isBlockPointer(BlockArg)) {
311 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000312 diag::err_opencl_builtin_expected_type)
313 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000314 return true;
315 }
316 return checkOpenCLBlockArgs(S, BlockArg);
317}
318
Simon Pilgrim2c518802017-03-30 14:13:19 +0000319/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000320static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
321 const QualType &IntType);
322
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000323static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000324 unsigned Start, unsigned End) {
325 bool IllegalParams = false;
326 for (unsigned I = Start; I <= End; ++I)
327 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
328 S.Context.getSizeType());
329 return IllegalParams;
330}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000331
332/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
333/// 'local void*' parameter of passed block.
334static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
335 Expr *BlockArg,
336 unsigned NumNonVarArgs) {
337 const BlockPointerType *BPT =
338 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
339 unsigned NumBlockParams =
340 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
341 unsigned TotalNumArgs = TheCall->getNumArgs();
342
343 // For each argument passed to the block, a corresponding uint needs to
344 // be passed to describe the size of the local memory.
345 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
346 S.Diag(TheCall->getLocStart(),
347 diag::err_opencl_enqueue_kernel_local_size_args);
348 return true;
349 }
350
351 // Check that the sizes of the local memory are specified by integers.
352 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
353 TotalNumArgs - 1);
354}
355
356/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
357/// overload formats specified in Table 6.13.17.1.
358/// int enqueue_kernel(queue_t queue,
359/// kernel_enqueue_flags_t flags,
360/// const ndrange_t ndrange,
361/// void (^block)(void))
362/// int enqueue_kernel(queue_t queue,
363/// kernel_enqueue_flags_t flags,
364/// const ndrange_t ndrange,
365/// uint num_events_in_wait_list,
366/// clk_event_t *event_wait_list,
367/// clk_event_t *event_ret,
368/// void (^block)(void))
369/// int enqueue_kernel(queue_t queue,
370/// kernel_enqueue_flags_t flags,
371/// const ndrange_t ndrange,
372/// void (^block)(local void*, ...),
373/// uint size0, ...)
374/// int enqueue_kernel(queue_t queue,
375/// kernel_enqueue_flags_t flags,
376/// const ndrange_t ndrange,
377/// uint num_events_in_wait_list,
378/// clk_event_t *event_wait_list,
379/// clk_event_t *event_ret,
380/// void (^block)(local void*, ...),
381/// uint size0, ...)
382static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
383 unsigned NumArgs = TheCall->getNumArgs();
384
385 if (NumArgs < 4) {
386 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
387 return true;
388 }
389
390 Expr *Arg0 = TheCall->getArg(0);
391 Expr *Arg1 = TheCall->getArg(1);
392 Expr *Arg2 = TheCall->getArg(2);
393 Expr *Arg3 = TheCall->getArg(3);
394
395 // First argument always needs to be a queue_t type.
396 if (!Arg0->getType()->isQueueT()) {
397 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000400 return true;
401 }
402
403 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
404 if (!Arg1->getType()->isIntegerType()) {
405 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000408 return true;
409 }
410
411 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000412 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000413 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000414 diag::err_opencl_builtin_expected_type)
415 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000416 return true;
417 }
418
419 // With four arguments, there is only one form that the function could be
420 // called in: no events and no variable arguments.
421 if (NumArgs == 4) {
422 // check that the last argument is the right block type.
423 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000424 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
425 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426 return true;
427 }
428 // we have a block type, check the prototype
429 const BlockPointerType *BPT =
430 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
431 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
432 S.Diag(Arg3->getLocStart(),
433 diag::err_opencl_enqueue_kernel_blocks_no_args);
434 return true;
435 }
436 return false;
437 }
438 // we can have block + varargs.
439 if (isBlockPointer(Arg3))
440 return (checkOpenCLBlockArgs(S, Arg3) ||
441 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
442 // last two cases with either exactly 7 args or 7 args and varargs.
443 if (NumArgs >= 7) {
444 // check common block argument.
445 Expr *Arg6 = TheCall->getArg(6);
446 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000447 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
448 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000449 return true;
450 }
451 if (checkOpenCLBlockArgs(S, Arg6))
452 return true;
453
454 // Forth argument has to be any integer type.
455 if (!Arg3->getType()->isIntegerType()) {
456 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000457 diag::err_opencl_builtin_expected_type)
458 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000459 return true;
460 }
461 // check remaining common arguments.
462 Expr *Arg4 = TheCall->getArg(4);
463 Expr *Arg5 = TheCall->getArg(5);
464
Anastasia Stulova2b461202016-11-14 15:34:01 +0000465 // Fifth argument is always passed as a pointer to clk_event_t.
466 if (!Arg4->isNullPointerConstant(S.Context,
467 Expr::NPC_ValueDependentIsNotNull) &&
468 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000469 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000470 diag::err_opencl_builtin_expected_type)
471 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000472 << S.Context.getPointerType(S.Context.OCLClkEventTy);
473 return true;
474 }
475
Anastasia Stulova2b461202016-11-14 15:34:01 +0000476 // Sixth argument is always passed as a pointer to clk_event_t.
477 if (!Arg5->isNullPointerConstant(S.Context,
478 Expr::NPC_ValueDependentIsNotNull) &&
479 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000480 Arg5->getType()->getPointeeType()->isClkEventT())) {
481 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000482 diag::err_opencl_builtin_expected_type)
483 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000484 << S.Context.getPointerType(S.Context.OCLClkEventTy);
485 return true;
486 }
487
488 if (NumArgs == 7)
489 return false;
490
491 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
492 }
493
494 // None of the specific case has been detected, give generic error
495 S.Diag(TheCall->getLocStart(),
496 diag::err_opencl_enqueue_kernel_incorrect_args);
497 return true;
498}
499
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000500/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000501static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000502 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000503}
504
505/// Returns true if pipe element type is different from the pointer.
506static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
507 const Expr *Arg0 = Call->getArg(0);
508 // First argument type should always be pipe.
509 if (!Arg0->getType()->isPipeType()) {
510 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000511 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000512 return true;
513 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000514 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000515 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
516 // Validates the access qualifier is compatible with the call.
517 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
518 // read_only and write_only, and assumed to be read_only if no qualifier is
519 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000520 switch (Call->getDirectCallee()->getBuiltinID()) {
521 case Builtin::BIread_pipe:
522 case Builtin::BIreserve_read_pipe:
523 case Builtin::BIcommit_read_pipe:
524 case Builtin::BIwork_group_reserve_read_pipe:
525 case Builtin::BIsub_group_reserve_read_pipe:
526 case Builtin::BIwork_group_commit_read_pipe:
527 case Builtin::BIsub_group_commit_read_pipe:
528 if (!(!AccessQual || AccessQual->isReadOnly())) {
529 S.Diag(Arg0->getLocStart(),
530 diag::err_opencl_builtin_pipe_invalid_access_modifier)
531 << "read_only" << Arg0->getSourceRange();
532 return true;
533 }
534 break;
535 case Builtin::BIwrite_pipe:
536 case Builtin::BIreserve_write_pipe:
537 case Builtin::BIcommit_write_pipe:
538 case Builtin::BIwork_group_reserve_write_pipe:
539 case Builtin::BIsub_group_reserve_write_pipe:
540 case Builtin::BIwork_group_commit_write_pipe:
541 case Builtin::BIsub_group_commit_write_pipe:
542 if (!(AccessQual && AccessQual->isWriteOnly())) {
543 S.Diag(Arg0->getLocStart(),
544 diag::err_opencl_builtin_pipe_invalid_access_modifier)
545 << "write_only" << Arg0->getSourceRange();
546 return true;
547 }
548 break;
549 default:
550 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000551 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000552 return false;
553}
554
555/// Returns true if pipe element type is different from the pointer.
556static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
557 const Expr *Arg0 = Call->getArg(0);
558 const Expr *ArgIdx = Call->getArg(Idx);
559 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000560 const QualType EltTy = PipeTy->getElementType();
561 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000562 // The Idx argument should be a pointer and the type of the pointer and
563 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000564 if (!ArgTy ||
565 !S.Context.hasSameType(
566 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000567 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000568 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000569 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000570 return true;
571 }
572 return false;
573}
574
575// \brief Performs semantic analysis for the read/write_pipe call.
576// \param S Reference to the semantic analyzer.
577// \param Call A pointer to the builtin call.
578// \return True if a semantic error has been found, false otherwise.
579static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000580 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
581 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000582 switch (Call->getNumArgs()) {
583 case 2: {
584 if (checkOpenCLPipeArg(S, Call))
585 return true;
586 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000587 // read/write_pipe(pipe T, T*).
588 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000589 if (checkOpenCLPipePacketType(S, Call, 1))
590 return true;
591 } break;
592
593 case 4: {
594 if (checkOpenCLPipeArg(S, Call))
595 return true;
596 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000597 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
598 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000599 if (!Call->getArg(1)->getType()->isReserveIDT()) {
600 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000601 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000602 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000603 return true;
604 }
605
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000606 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000607 const Expr *Arg2 = Call->getArg(2);
608 if (!Arg2->getType()->isIntegerType() &&
609 !Arg2->getType()->isUnsignedIntegerType()) {
610 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000611 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000612 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000613 return true;
614 }
615
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000616 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000617 if (checkOpenCLPipePacketType(S, Call, 3))
618 return true;
619 } break;
620 default:
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000622 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000623 return true;
624 }
625
626 return false;
627}
628
629// \brief Performs a semantic analysis on the {work_group_/sub_group_
630// /_}reserve_{read/write}_pipe
631// \param S Reference to the semantic analyzer.
632// \param Call The call to the builtin function to be analyzed.
633// \return True if a semantic error was found, false otherwise.
634static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
635 if (checkArgCount(S, Call, 2))
636 return true;
637
638 if (checkOpenCLPipeArg(S, Call))
639 return true;
640
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000641 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000642 if (!Call->getArg(1)->getType()->isIntegerType() &&
643 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
644 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000645 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000646 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000647 return true;
648 }
649
650 return false;
651}
652
653// \brief Performs a semantic analysis on {work_group_/sub_group_
654// /_}commit_{read/write}_pipe
655// \param S Reference to the semantic analyzer.
656// \param Call The call to the builtin function to be analyzed.
657// \return True if a semantic error was found, false otherwise.
658static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
659 if (checkArgCount(S, Call, 2))
660 return true;
661
662 if (checkOpenCLPipeArg(S, Call))
663 return true;
664
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000665 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000666 if (!Call->getArg(1)->getType()->isReserveIDT()) {
667 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000668 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000669 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000670 return true;
671 }
672
673 return false;
674}
675
676// \brief Performs a semantic analysis on the call to built-in Pipe
677// Query Functions.
678// \param S Reference to the semantic analyzer.
679// \param Call The call to the builtin function to be analyzed.
680// \return True if a semantic error was found, false otherwise.
681static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
682 if (checkArgCount(S, Call, 1))
683 return true;
684
685 if (!Call->getArg(0)->getType()->isPipeType()) {
686 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000687 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000688 return true;
689 }
690
691 return false;
692}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000693// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000694// \brief Performs semantic analysis for the to_global/local/private call.
695// \param S Reference to the semantic analyzer.
696// \param BuiltinID ID of the builtin function.
697// \param Call A pointer to the builtin call.
698// \return True if a semantic error has been found, false otherwise.
699static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
700 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000701 if (Call->getNumArgs() != 1) {
702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
703 << Call->getDirectCallee() << Call->getSourceRange();
704 return true;
705 }
706
707 auto RT = Call->getArg(0)->getType();
708 if (!RT->isPointerType() || RT->getPointeeType()
709 .getAddressSpace() == LangAS::opencl_constant) {
710 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
711 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
712 return true;
713 }
714
715 RT = RT->getPointeeType();
716 auto Qual = RT.getQualifiers();
717 switch (BuiltinID) {
718 case Builtin::BIto_global:
719 Qual.setAddressSpace(LangAS::opencl_global);
720 break;
721 case Builtin::BIto_local:
722 Qual.setAddressSpace(LangAS::opencl_local);
723 break;
724 default:
725 Qual.removeAddressSpace();
726 }
727 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
728 RT.getUnqualifiedType(), Qual)));
729
730 return false;
731}
732
John McCalldadc5752010-08-24 06:29:42 +0000733ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000734Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
735 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000736 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000737
Chris Lattner3be167f2010-10-01 23:23:24 +0000738 // Find out if any arguments are required to be integer constant expressions.
739 unsigned ICEArguments = 0;
740 ASTContext::GetBuiltinTypeError Error;
741 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
742 if (Error != ASTContext::GE_None)
743 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
744
745 // If any arguments are required to be ICE's, check and diagnose.
746 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
747 // Skip arguments not required to be ICE's.
748 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
749
750 llvm::APSInt Result;
751 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
752 return true;
753 ICEArguments &= ~(1 << ArgNo);
754 }
755
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000756 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000757 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000758 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000759 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000760 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000761 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000762 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000763 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000764 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000765 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000766 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000767 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000768 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000769 case Builtin::BI__va_start: {
770 switch (Context.getTargetInfo().getTriple().getArch()) {
771 case llvm::Triple::arm:
772 case llvm::Triple::thumb:
773 if (SemaBuiltinVAStartARM(TheCall))
774 return ExprError();
775 break;
776 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000777 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000778 return ExprError();
779 break;
780 }
781 break;
782 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000783 case Builtin::BI__builtin_isgreater:
784 case Builtin::BI__builtin_isgreaterequal:
785 case Builtin::BI__builtin_isless:
786 case Builtin::BI__builtin_islessequal:
787 case Builtin::BI__builtin_islessgreater:
788 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000789 if (SemaBuiltinUnorderedCompare(TheCall))
790 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000791 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000792 case Builtin::BI__builtin_fpclassify:
793 if (SemaBuiltinFPClassification(TheCall, 6))
794 return ExprError();
795 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000796 case Builtin::BI__builtin_isfinite:
797 case Builtin::BI__builtin_isinf:
798 case Builtin::BI__builtin_isinf_sign:
799 case Builtin::BI__builtin_isnan:
800 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000801 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000802 return ExprError();
803 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000804 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000805 return SemaBuiltinShuffleVector(TheCall);
806 // TheCall will be freed by the smart pointer here, but that's fine, since
807 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000808 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000809 if (SemaBuiltinPrefetch(TheCall))
810 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000811 break;
David Majnemer51169932016-10-31 05:37:48 +0000812 case Builtin::BI__builtin_alloca_with_align:
813 if (SemaBuiltinAllocaWithAlign(TheCall))
814 return ExprError();
815 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000816 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000817 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000818 if (SemaBuiltinAssume(TheCall))
819 return ExprError();
820 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000821 case Builtin::BI__builtin_assume_aligned:
822 if (SemaBuiltinAssumeAligned(TheCall))
823 return ExprError();
824 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000825 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000826 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000829 case Builtin::BI__builtin_longjmp:
830 if (SemaBuiltinLongjmp(TheCall))
831 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000832 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000833 case Builtin::BI__builtin_setjmp:
834 if (SemaBuiltinSetjmp(TheCall))
835 return ExprError();
836 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000837 case Builtin::BI_setjmp:
838 case Builtin::BI_setjmpex:
839 if (checkArgCount(*this, TheCall, 1))
840 return true;
841 break;
John McCallbebede42011-02-26 05:39:39 +0000842
843 case Builtin::BI__builtin_classify_type:
844 if (checkArgCount(*this, TheCall, 1)) return true;
845 TheCall->setType(Context.IntTy);
846 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000847 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000848 if (checkArgCount(*this, TheCall, 1)) return true;
849 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000850 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000851 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000852 case Builtin::BI__sync_fetch_and_add_1:
853 case Builtin::BI__sync_fetch_and_add_2:
854 case Builtin::BI__sync_fetch_and_add_4:
855 case Builtin::BI__sync_fetch_and_add_8:
856 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000857 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000858 case Builtin::BI__sync_fetch_and_sub_1:
859 case Builtin::BI__sync_fetch_and_sub_2:
860 case Builtin::BI__sync_fetch_and_sub_4:
861 case Builtin::BI__sync_fetch_and_sub_8:
862 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000863 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000864 case Builtin::BI__sync_fetch_and_or_1:
865 case Builtin::BI__sync_fetch_and_or_2:
866 case Builtin::BI__sync_fetch_and_or_4:
867 case Builtin::BI__sync_fetch_and_or_8:
868 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000869 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000870 case Builtin::BI__sync_fetch_and_and_1:
871 case Builtin::BI__sync_fetch_and_and_2:
872 case Builtin::BI__sync_fetch_and_and_4:
873 case Builtin::BI__sync_fetch_and_and_8:
874 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000875 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000876 case Builtin::BI__sync_fetch_and_xor_1:
877 case Builtin::BI__sync_fetch_and_xor_2:
878 case Builtin::BI__sync_fetch_and_xor_4:
879 case Builtin::BI__sync_fetch_and_xor_8:
880 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000881 case Builtin::BI__sync_fetch_and_nand:
882 case Builtin::BI__sync_fetch_and_nand_1:
883 case Builtin::BI__sync_fetch_and_nand_2:
884 case Builtin::BI__sync_fetch_and_nand_4:
885 case Builtin::BI__sync_fetch_and_nand_8:
886 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000887 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000888 case Builtin::BI__sync_add_and_fetch_1:
889 case Builtin::BI__sync_add_and_fetch_2:
890 case Builtin::BI__sync_add_and_fetch_4:
891 case Builtin::BI__sync_add_and_fetch_8:
892 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000893 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000894 case Builtin::BI__sync_sub_and_fetch_1:
895 case Builtin::BI__sync_sub_and_fetch_2:
896 case Builtin::BI__sync_sub_and_fetch_4:
897 case Builtin::BI__sync_sub_and_fetch_8:
898 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000899 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000900 case Builtin::BI__sync_and_and_fetch_1:
901 case Builtin::BI__sync_and_and_fetch_2:
902 case Builtin::BI__sync_and_and_fetch_4:
903 case Builtin::BI__sync_and_and_fetch_8:
904 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000905 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000906 case Builtin::BI__sync_or_and_fetch_1:
907 case Builtin::BI__sync_or_and_fetch_2:
908 case Builtin::BI__sync_or_and_fetch_4:
909 case Builtin::BI__sync_or_and_fetch_8:
910 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000911 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000912 case Builtin::BI__sync_xor_and_fetch_1:
913 case Builtin::BI__sync_xor_and_fetch_2:
914 case Builtin::BI__sync_xor_and_fetch_4:
915 case Builtin::BI__sync_xor_and_fetch_8:
916 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000917 case Builtin::BI__sync_nand_and_fetch:
918 case Builtin::BI__sync_nand_and_fetch_1:
919 case Builtin::BI__sync_nand_and_fetch_2:
920 case Builtin::BI__sync_nand_and_fetch_4:
921 case Builtin::BI__sync_nand_and_fetch_8:
922 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000923 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000924 case Builtin::BI__sync_val_compare_and_swap_1:
925 case Builtin::BI__sync_val_compare_and_swap_2:
926 case Builtin::BI__sync_val_compare_and_swap_4:
927 case Builtin::BI__sync_val_compare_and_swap_8:
928 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000929 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000930 case Builtin::BI__sync_bool_compare_and_swap_1:
931 case Builtin::BI__sync_bool_compare_and_swap_2:
932 case Builtin::BI__sync_bool_compare_and_swap_4:
933 case Builtin::BI__sync_bool_compare_and_swap_8:
934 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000935 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000936 case Builtin::BI__sync_lock_test_and_set_1:
937 case Builtin::BI__sync_lock_test_and_set_2:
938 case Builtin::BI__sync_lock_test_and_set_4:
939 case Builtin::BI__sync_lock_test_and_set_8:
940 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000941 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000942 case Builtin::BI__sync_lock_release_1:
943 case Builtin::BI__sync_lock_release_2:
944 case Builtin::BI__sync_lock_release_4:
945 case Builtin::BI__sync_lock_release_8:
946 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000947 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000948 case Builtin::BI__sync_swap_1:
949 case Builtin::BI__sync_swap_2:
950 case Builtin::BI__sync_swap_4:
951 case Builtin::BI__sync_swap_8:
952 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000953 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000954 case Builtin::BI__builtin_nontemporal_load:
955 case Builtin::BI__builtin_nontemporal_store:
956 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000957#define BUILTIN(ID, TYPE, ATTRS)
958#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
959 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000960 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000961#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000962 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000963 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000964 return ExprError();
965 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000966 case Builtin::BI__builtin_addressof:
967 if (SemaBuiltinAddressof(*this, TheCall))
968 return ExprError();
969 break;
John McCall03107a42015-10-29 20:48:01 +0000970 case Builtin::BI__builtin_add_overflow:
971 case Builtin::BI__builtin_sub_overflow:
972 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000973 if (SemaBuiltinOverflow(*this, TheCall))
974 return ExprError();
975 break;
Richard Smith760520b2014-06-03 23:27:44 +0000976 case Builtin::BI__builtin_operator_new:
977 case Builtin::BI__builtin_operator_delete:
978 if (!getLangOpts().CPlusPlus) {
979 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
980 << (BuiltinID == Builtin::BI__builtin_operator_new
981 ? "__builtin_operator_new"
982 : "__builtin_operator_delete")
983 << "C++";
984 return ExprError();
985 }
986 // CodeGen assumes it can find the global new and delete to call,
987 // so ensure that they are declared.
988 DeclareGlobalNewDelete();
989 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000990
991 // check secure string manipulation functions where overflows
992 // are detectable at compile time
993 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000994 case Builtin::BI__builtin___memmove_chk:
995 case Builtin::BI__builtin___memset_chk:
996 case Builtin::BI__builtin___strlcat_chk:
997 case Builtin::BI__builtin___strlcpy_chk:
998 case Builtin::BI__builtin___strncat_chk:
999 case Builtin::BI__builtin___strncpy_chk:
1000 case Builtin::BI__builtin___stpncpy_chk:
1001 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1002 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001003 case Builtin::BI__builtin___memccpy_chk:
1004 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1005 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001006 case Builtin::BI__builtin___snprintf_chk:
1007 case Builtin::BI__builtin___vsnprintf_chk:
1008 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1009 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001010 case Builtin::BI__builtin_call_with_static_chain:
1011 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1012 return ExprError();
1013 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001014 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001015 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001016 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1017 diag::err_seh___except_block))
1018 return ExprError();
1019 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001020 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001021 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001022 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1023 diag::err_seh___except_filter))
1024 return ExprError();
1025 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001026 case Builtin::BI__GetExceptionInfo:
1027 if (checkArgCount(*this, TheCall, 1))
1028 return ExprError();
1029
1030 if (CheckCXXThrowOperand(
1031 TheCall->getLocStart(),
1032 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1033 TheCall))
1034 return ExprError();
1035
1036 TheCall->setType(Context.VoidPtrTy);
1037 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001038 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001039 case Builtin::BIread_pipe:
1040 case Builtin::BIwrite_pipe:
1041 // Since those two functions are declared with var args, we need a semantic
1042 // check for the argument.
1043 if (SemaBuiltinRWPipe(*this, TheCall))
1044 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001045 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001046 break;
1047 case Builtin::BIreserve_read_pipe:
1048 case Builtin::BIreserve_write_pipe:
1049 case Builtin::BIwork_group_reserve_read_pipe:
1050 case Builtin::BIwork_group_reserve_write_pipe:
1051 case Builtin::BIsub_group_reserve_read_pipe:
1052 case Builtin::BIsub_group_reserve_write_pipe:
1053 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1054 return ExprError();
1055 // Since return type of reserve_read/write_pipe built-in function is
1056 // reserve_id_t, which is not defined in the builtin def file , we used int
1057 // as return type and need to override the return type of these functions.
1058 TheCall->setType(Context.OCLReserveIDTy);
1059 break;
1060 case Builtin::BIcommit_read_pipe:
1061 case Builtin::BIcommit_write_pipe:
1062 case Builtin::BIwork_group_commit_read_pipe:
1063 case Builtin::BIwork_group_commit_write_pipe:
1064 case Builtin::BIsub_group_commit_read_pipe:
1065 case Builtin::BIsub_group_commit_write_pipe:
1066 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1067 return ExprError();
1068 break;
1069 case Builtin::BIget_pipe_num_packets:
1070 case Builtin::BIget_pipe_max_packets:
1071 if (SemaBuiltinPipePackets(*this, TheCall))
1072 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001073 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001074 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001075 case Builtin::BIto_global:
1076 case Builtin::BIto_local:
1077 case Builtin::BIto_private:
1078 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1079 return ExprError();
1080 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001081 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1082 case Builtin::BIenqueue_kernel:
1083 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1084 return ExprError();
1085 break;
1086 case Builtin::BIget_kernel_work_group_size:
1087 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1088 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1089 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001090 break;
1091 case Builtin::BI__builtin_os_log_format:
1092 case Builtin::BI__builtin_os_log_format_buffer_size:
1093 if (SemaBuiltinOSLogFormat(TheCall)) {
1094 return ExprError();
1095 }
1096 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001097 }
Richard Smith760520b2014-06-03 23:27:44 +00001098
Nate Begeman4904e322010-06-08 02:47:44 +00001099 // Since the target specific builtins for each arch overlap, only check those
1100 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001101 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001102 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001103 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001104 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001105 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001106 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001107 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1108 return ExprError();
1109 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001110 case llvm::Triple::aarch64:
1111 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001112 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001113 return ExprError();
1114 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001115 case llvm::Triple::mips:
1116 case llvm::Triple::mipsel:
1117 case llvm::Triple::mips64:
1118 case llvm::Triple::mips64el:
1119 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1120 return ExprError();
1121 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001122 case llvm::Triple::systemz:
1123 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1124 return ExprError();
1125 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001126 case llvm::Triple::x86:
1127 case llvm::Triple::x86_64:
1128 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1129 return ExprError();
1130 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001131 case llvm::Triple::ppc:
1132 case llvm::Triple::ppc64:
1133 case llvm::Triple::ppc64le:
1134 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1135 return ExprError();
1136 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001137 default:
1138 break;
1139 }
1140 }
1141
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001142 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001143}
1144
Nate Begeman91e1fea2010-06-14 05:21:25 +00001145// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001146static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001147 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001148 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001149 switch (Type.getEltType()) {
1150 case NeonTypeFlags::Int8:
1151 case NeonTypeFlags::Poly8:
1152 return shift ? 7 : (8 << IsQuad) - 1;
1153 case NeonTypeFlags::Int16:
1154 case NeonTypeFlags::Poly16:
1155 return shift ? 15 : (4 << IsQuad) - 1;
1156 case NeonTypeFlags::Int32:
1157 return shift ? 31 : (2 << IsQuad) - 1;
1158 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001159 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001160 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001161 case NeonTypeFlags::Poly128:
1162 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001163 case NeonTypeFlags::Float16:
1164 assert(!shift && "cannot shift float types!");
1165 return (4 << IsQuad) - 1;
1166 case NeonTypeFlags::Float32:
1167 assert(!shift && "cannot shift float types!");
1168 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001169 case NeonTypeFlags::Float64:
1170 assert(!shift && "cannot shift float types!");
1171 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001172 }
David Blaikie8a40f702012-01-17 06:56:22 +00001173 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001174}
1175
Bob Wilsone4d77232011-11-08 05:04:11 +00001176/// getNeonEltType - Return the QualType corresponding to the elements of
1177/// the vector type specified by the NeonTypeFlags. This is used to check
1178/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001179static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001180 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001181 switch (Flags.getEltType()) {
1182 case NeonTypeFlags::Int8:
1183 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1184 case NeonTypeFlags::Int16:
1185 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1186 case NeonTypeFlags::Int32:
1187 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1188 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001189 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001190 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1191 else
1192 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1193 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001194 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001195 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001196 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001197 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001198 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001199 if (IsInt64Long)
1200 return Context.UnsignedLongTy;
1201 else
1202 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001203 case NeonTypeFlags::Poly128:
1204 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001205 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001206 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001207 case NeonTypeFlags::Float32:
1208 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001209 case NeonTypeFlags::Float64:
1210 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001211 }
David Blaikie8a40f702012-01-17 06:56:22 +00001212 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001213}
1214
Tim Northover12670412014-02-19 10:37:05 +00001215bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001216 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001217 uint64_t mask = 0;
1218 unsigned TV = 0;
1219 int PtrArgNum = -1;
1220 bool HasConstPtr = false;
1221 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001222#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001223#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001224#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001225 }
1226
1227 // For NEON intrinsics which are overloaded on vector element type, validate
1228 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001229 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001230 if (mask) {
1231 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1232 return true;
1233
1234 TV = Result.getLimitedValue(64);
1235 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1236 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001237 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001238 }
1239
1240 if (PtrArgNum >= 0) {
1241 // Check that pointer arguments have the specified type.
1242 Expr *Arg = TheCall->getArg(PtrArgNum);
1243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1244 Arg = ICE->getSubExpr();
1245 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1246 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001247
Tim Northovera2ee4332014-03-29 15:09:45 +00001248 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001249 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1250 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001251 bool IsInt64Long =
1252 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1253 QualType EltTy =
1254 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001255 if (HasConstPtr)
1256 EltTy = EltTy.withConst();
1257 QualType LHSTy = Context.getPointerType(EltTy);
1258 AssignConvertType ConvTy;
1259 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1260 if (RHS.isInvalid())
1261 return true;
1262 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1263 RHS.get(), AA_Assigning))
1264 return true;
1265 }
1266
1267 // For NEON intrinsics which take an immediate value as part of the
1268 // instruction, range check them here.
1269 unsigned i = 0, l = 0, u = 0;
1270 switch (BuiltinID) {
1271 default:
1272 return false;
Tim Northover12670412014-02-19 10:37:05 +00001273#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001274#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001275#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001276 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001277
Richard Sandiford28940af2014-04-16 08:47:51 +00001278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001279}
1280
Tim Northovera2ee4332014-03-29 15:09:45 +00001281bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1282 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001283 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001284 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001285 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001286 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001287 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001288 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_strex ||
1290 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001291 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001292 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001293 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1294 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1295 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001296
1297 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1298
1299 // Ensure that we have the proper number of arguments.
1300 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1301 return true;
1302
1303 // Inspect the pointer argument of the atomic builtin. This should always be
1304 // a pointer type, whose element is an integral scalar or pointer type.
1305 // Because it is a pointer type, we don't have to worry about any implicit
1306 // casts here.
1307 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1308 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1309 if (PointerArgRes.isInvalid())
1310 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001311 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001312
1313 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1314 if (!pointerType) {
1315 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1316 << PointerArg->getType() << PointerArg->getSourceRange();
1317 return true;
1318 }
1319
1320 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1321 // task is to insert the appropriate casts into the AST. First work out just
1322 // what the appropriate type is.
1323 QualType ValType = pointerType->getPointeeType();
1324 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1325 if (IsLdrex)
1326 AddrType.addConst();
1327
1328 // Issue a warning if the cast is dodgy.
1329 CastKind CastNeeded = CK_NoOp;
1330 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1331 CastNeeded = CK_BitCast;
1332 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1333 << PointerArg->getType()
1334 << Context.getPointerType(AddrType)
1335 << AA_Passing << PointerArg->getSourceRange();
1336 }
1337
1338 // Finally, do the cast and replace the argument with the corrected version.
1339 AddrType = Context.getPointerType(AddrType);
1340 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1341 if (PointerArgRes.isInvalid())
1342 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001343 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001344
1345 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1346
1347 // In general, we allow ints, floats and pointers to be loaded and stored.
1348 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1349 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1350 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1351 << PointerArg->getType() << PointerArg->getSourceRange();
1352 return true;
1353 }
1354
1355 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001356 if (Context.getTypeSize(ValType) > MaxWidth) {
1357 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001358 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1359 << PointerArg->getType() << PointerArg->getSourceRange();
1360 return true;
1361 }
1362
1363 switch (ValType.getObjCLifetime()) {
1364 case Qualifiers::OCL_None:
1365 case Qualifiers::OCL_ExplicitNone:
1366 // okay
1367 break;
1368
1369 case Qualifiers::OCL_Weak:
1370 case Qualifiers::OCL_Strong:
1371 case Qualifiers::OCL_Autoreleasing:
1372 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1373 << ValType << PointerArg->getSourceRange();
1374 return true;
1375 }
1376
Tim Northover6aacd492013-07-16 09:47:53 +00001377 if (IsLdrex) {
1378 TheCall->setType(ValType);
1379 return false;
1380 }
1381
1382 // Initialize the argument to be stored.
1383 ExprResult ValArg = TheCall->getArg(0);
1384 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1385 Context, ValType, /*consume*/ false);
1386 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1387 if (ValArg.isInvalid())
1388 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001389 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001390
1391 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1392 // but the custom checker bypasses all default analysis.
1393 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001394 return false;
1395}
1396
Nate Begeman4904e322010-06-08 02:47:44 +00001397bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001398 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001399 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1400 BuiltinID == ARM::BI__builtin_arm_strex ||
1401 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001402 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001403 }
1404
Yi Kong26d104a2014-08-13 19:18:14 +00001405 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1406 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1407 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1408 }
1409
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001410 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1411 BuiltinID == ARM::BI__builtin_arm_wsr64)
1412 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1413
1414 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1415 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1416 BuiltinID == ARM::BI__builtin_arm_wsr ||
1417 BuiltinID == ARM::BI__builtin_arm_wsrp)
1418 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1419
Tim Northover12670412014-02-19 10:37:05 +00001420 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1421 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001422
Yi Kong4efadfb2014-07-03 16:01:25 +00001423 // For intrinsics which take an immediate value as part of the instruction,
1424 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001425 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001426 switch (BuiltinID) {
1427 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001428 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1429 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001430 case ARM::BI__builtin_arm_vcvtr_f:
1431 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001432 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001433 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001434 case ARM::BI__builtin_arm_isb:
1435 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001436 }
Nate Begemand773fe62010-06-13 04:47:52 +00001437
Nate Begemanf568b072010-08-03 21:32:34 +00001438 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001439 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001440}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001441
Tim Northover573cbee2014-05-24 12:52:07 +00001442bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001443 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1449 }
1450
Yi Konga5548432014-08-13 19:18:20 +00001451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1456 }
1457
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001461
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1467
Tim Northovera2ee4332014-03-29 15:09:45 +00001468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1469 return true;
1470
Yi Kong19a29ac2014-07-17 10:52:06 +00001471 // For intrinsics which take an immediate value as part of the instruction,
1472 // range check them here.
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default: return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1479 }
1480
Yi Kong19a29ac2014-07-17 10:52:06 +00001481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001482}
1483
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001484// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1485// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1486// ordering for DSP is unspecified. MSA is ordered by the data format used
1487// by the underlying instruction i.e., df/m, df/n and then by size.
1488//
1489// FIXME: The size tests here should instead be tablegen'd along with the
1490// definitions from include/clang/Basic/BuiltinsMips.def.
1491// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1492// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001493bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001494 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001495 switch (BuiltinID) {
1496 default: return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001504 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1505 // df/m field.
1506 // These intrinsics take an unsigned 3 bit immediate.
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1519 // These intrinsics take an unsigned 4 bit immediate.
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1532 // These intrinsics take an unsigned 5 bit immedate.
1533 // The first block of intrinsics actually have an unsigned 5 bit field,
1534 // not a df/n field.
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1571 // These intrinsics take an unsigned 6 bit immediate.
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1584 // These intrinsics take a signed 5 bit immediate.
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1605 // These intrinsics take an unsigned 8 bit immediate.
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1616 // df/n format
1617 // These intrinsics take an unsigned 4 bit immediate.
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1623 // These intrinsics take an unsigned 3 bit immediate.
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1629 // These intrinsics take an unsigned 2 bit immediate.
1630 case Mips::BI__builtin_msa_copy_s_w:
1631 case Mips::BI__builtin_msa_copy_u_w:
1632 case Mips::BI__builtin_msa_insve_w:
1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1635 // These intrinsics take an unsigned 1 bit immediate.
1636 case Mips::BI__builtin_msa_copy_s_d:
1637 case Mips::BI__builtin_msa_copy_u_d:
1638 case Mips::BI__builtin_msa_insve_d:
1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1641 // Memory offsets and immediate loads.
1642 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001644 case Mips::BI__builtin_msa_ldi_h:
1645 case Mips::BI__builtin_msa_ldi_w:
1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001655 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001656
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001657 if (!m)
1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1659
1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1661 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001662}
1663
Kit Bartone50adcb2015-03-30 19:40:59 +00001664bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1665 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1667 BuiltinID == PPC::BI__builtin_divdeu ||
1668 BuiltinID == PPC::BI__builtin_bpermd;
1669 bool IsTarget64Bit = Context.getTargetInfo()
1670 .getTypeWidth(Context
1671 .getTargetInfo()
1672 .getIntPtrType()) == 64;
1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1674 BuiltinID == PPC::BI__builtin_divweu ||
1675 BuiltinID == PPC::BI__builtin_divde ||
1676 BuiltinID == PPC::BI__builtin_divdeu;
1677
1678 if (Is64BitBltin && !IsTarget64Bit)
1679 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1680 << TheCall->getSourceRange();
1681
1682 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1683 (BuiltinID == PPC::BI__builtin_bpermd &&
1684 !Context.getTargetInfo().hasFeature("bpermd")))
1685 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1686 << TheCall->getSourceRange();
1687
Kit Bartone50adcb2015-03-30 19:40:59 +00001688 switch (BuiltinID) {
1689 default: return false;
1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1691 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1694 case PPC::BI__builtin_tbegin:
1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1697 case PPC::BI__builtin_tabortwc:
1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1699 case PPC::BI__builtin_tabortwci:
1700 case PPC::BI__builtin_tabortdci:
1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001703 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001704 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001705 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001706 }
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1708}
1709
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001710bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1711 CallExpr *TheCall) {
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1713 Expr *Arg = TheCall->getArg(0);
1714 llvm::APSInt AbortCode(32);
1715 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1718 << Arg->getSourceRange();
1719 }
1720
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001743 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001744 case SystemZ::BI__builtin_s390_vfidb:
1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001747 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001748 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1749 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1750 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1751 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1752 case SystemZ::BI__builtin_s390_vstrcb:
1753 case SystemZ::BI__builtin_s390_vstrch:
1754 case SystemZ::BI__builtin_s390_vstrcf:
1755 case SystemZ::BI__builtin_s390_vstrczb:
1756 case SystemZ::BI__builtin_s390_vstrczh:
1757 case SystemZ::BI__builtin_s390_vstrczf:
1758 case SystemZ::BI__builtin_s390_vstrcbs:
1759 case SystemZ::BI__builtin_s390_vstrchs:
1760 case SystemZ::BI__builtin_s390_vstrcfs:
1761 case SystemZ::BI__builtin_s390_vstrczbs:
1762 case SystemZ::BI__builtin_s390_vstrczhs:
1763 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001764 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1765 case SystemZ::BI__builtin_s390_vfminsb:
1766 case SystemZ::BI__builtin_s390_vfmaxsb:
1767 case SystemZ::BI__builtin_s390_vfmindb:
1768 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001769 }
1770 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001771}
1772
Craig Topper5ba2c502015-11-07 08:08:31 +00001773/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1774/// This checks that the target supports __builtin_cpu_supports and
1775/// that the string argument is constant and valid.
1776static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1777 Expr *Arg = TheCall->getArg(0);
1778
1779 // Check if the argument is a string literal.
1780 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1781 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1782 << Arg->getSourceRange();
1783
1784 // Check the contents of the string.
1785 StringRef Feature =
1786 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1787 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1788 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1789 << Arg->getSourceRange();
1790 return false;
1791}
1792
Craig Toppera7e253e2016-09-23 04:48:31 +00001793// Check if the rounding mode is legal.
1794bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1795 // Indicates if this instruction has rounding control or just SAE.
1796 bool HasRC = false;
1797
1798 unsigned ArgNum = 0;
1799 switch (BuiltinID) {
1800 default:
1801 return false;
1802 case X86::BI__builtin_ia32_vcvttsd2si32:
1803 case X86::BI__builtin_ia32_vcvttsd2si64:
1804 case X86::BI__builtin_ia32_vcvttsd2usi32:
1805 case X86::BI__builtin_ia32_vcvttsd2usi64:
1806 case X86::BI__builtin_ia32_vcvttss2si32:
1807 case X86::BI__builtin_ia32_vcvttss2si64:
1808 case X86::BI__builtin_ia32_vcvttss2usi32:
1809 case X86::BI__builtin_ia32_vcvttss2usi64:
1810 ArgNum = 1;
1811 break;
1812 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1813 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1814 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1815 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1816 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1817 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1818 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1819 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1820 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1821 case X86::BI__builtin_ia32_exp2pd_mask:
1822 case X86::BI__builtin_ia32_exp2ps_mask:
1823 case X86::BI__builtin_ia32_getexppd512_mask:
1824 case X86::BI__builtin_ia32_getexpps512_mask:
1825 case X86::BI__builtin_ia32_rcp28pd_mask:
1826 case X86::BI__builtin_ia32_rcp28ps_mask:
1827 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1828 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1829 case X86::BI__builtin_ia32_vcomisd:
1830 case X86::BI__builtin_ia32_vcomiss:
1831 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1832 ArgNum = 3;
1833 break;
1834 case X86::BI__builtin_ia32_cmppd512_mask:
1835 case X86::BI__builtin_ia32_cmpps512_mask:
1836 case X86::BI__builtin_ia32_cmpsd_mask:
1837 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001838 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001839 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1840 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001841 case X86::BI__builtin_ia32_maxpd512_mask:
1842 case X86::BI__builtin_ia32_maxps512_mask:
1843 case X86::BI__builtin_ia32_maxsd_round_mask:
1844 case X86::BI__builtin_ia32_maxss_round_mask:
1845 case X86::BI__builtin_ia32_minpd512_mask:
1846 case X86::BI__builtin_ia32_minps512_mask:
1847 case X86::BI__builtin_ia32_minsd_round_mask:
1848 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001849 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1850 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1851 case X86::BI__builtin_ia32_reducepd512_mask:
1852 case X86::BI__builtin_ia32_reduceps512_mask:
1853 case X86::BI__builtin_ia32_rndscalepd_mask:
1854 case X86::BI__builtin_ia32_rndscaleps_mask:
1855 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1856 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1857 ArgNum = 4;
1858 break;
1859 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001860 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001861 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001862 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001863 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001864 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001865 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001866 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001867 case X86::BI__builtin_ia32_rangepd512_mask:
1868 case X86::BI__builtin_ia32_rangeps512_mask:
1869 case X86::BI__builtin_ia32_rangesd128_round_mask:
1870 case X86::BI__builtin_ia32_rangess128_round_mask:
1871 case X86::BI__builtin_ia32_reducesd_mask:
1872 case X86::BI__builtin_ia32_reducess_mask:
1873 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1874 case X86::BI__builtin_ia32_rndscaless_round_mask:
1875 ArgNum = 5;
1876 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001877 case X86::BI__builtin_ia32_vcvtsd2si64:
1878 case X86::BI__builtin_ia32_vcvtsd2si32:
1879 case X86::BI__builtin_ia32_vcvtsd2usi32:
1880 case X86::BI__builtin_ia32_vcvtsd2usi64:
1881 case X86::BI__builtin_ia32_vcvtss2si32:
1882 case X86::BI__builtin_ia32_vcvtss2si64:
1883 case X86::BI__builtin_ia32_vcvtss2usi32:
1884 case X86::BI__builtin_ia32_vcvtss2usi64:
1885 ArgNum = 1;
1886 HasRC = true;
1887 break;
Craig Topper8e066312016-11-07 07:01:09 +00001888 case X86::BI__builtin_ia32_cvtsi2sd64:
1889 case X86::BI__builtin_ia32_cvtsi2ss32:
1890 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001891 case X86::BI__builtin_ia32_cvtusi2sd64:
1892 case X86::BI__builtin_ia32_cvtusi2ss32:
1893 case X86::BI__builtin_ia32_cvtusi2ss64:
1894 ArgNum = 2;
1895 HasRC = true;
1896 break;
1897 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1898 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1901 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1902 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1903 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1904 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1905 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1906 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1907 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001908 case X86::BI__builtin_ia32_sqrtpd512_mask:
1909 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001910 ArgNum = 3;
1911 HasRC = true;
1912 break;
1913 case X86::BI__builtin_ia32_addpd512_mask:
1914 case X86::BI__builtin_ia32_addps512_mask:
1915 case X86::BI__builtin_ia32_divpd512_mask:
1916 case X86::BI__builtin_ia32_divps512_mask:
1917 case X86::BI__builtin_ia32_mulpd512_mask:
1918 case X86::BI__builtin_ia32_mulps512_mask:
1919 case X86::BI__builtin_ia32_subpd512_mask:
1920 case X86::BI__builtin_ia32_subps512_mask:
1921 case X86::BI__builtin_ia32_addss_round_mask:
1922 case X86::BI__builtin_ia32_addsd_round_mask:
1923 case X86::BI__builtin_ia32_divss_round_mask:
1924 case X86::BI__builtin_ia32_divsd_round_mask:
1925 case X86::BI__builtin_ia32_mulss_round_mask:
1926 case X86::BI__builtin_ia32_mulsd_round_mask:
1927 case X86::BI__builtin_ia32_subss_round_mask:
1928 case X86::BI__builtin_ia32_subsd_round_mask:
1929 case X86::BI__builtin_ia32_scalefpd512_mask:
1930 case X86::BI__builtin_ia32_scalefps512_mask:
1931 case X86::BI__builtin_ia32_scalefsd_round_mask:
1932 case X86::BI__builtin_ia32_scalefss_round_mask:
1933 case X86::BI__builtin_ia32_getmantpd512_mask:
1934 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001935 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1936 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1937 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001938 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1944 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1945 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1947 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1948 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1949 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1950 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1952 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1953 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1954 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1955 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1956 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1957 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1958 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1959 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1960 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1961 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1962 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1963 case X86::BI__builtin_ia32_vfmaddss3_mask:
1964 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1965 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1966 ArgNum = 4;
1967 HasRC = true;
1968 break;
1969 case X86::BI__builtin_ia32_getmantsd_round_mask:
1970 case X86::BI__builtin_ia32_getmantss_round_mask:
1971 ArgNum = 5;
1972 HasRC = true;
1973 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001974 }
1975
1976 llvm::APSInt Result;
1977
1978 // We can't check the value of a dependent argument.
1979 Expr *Arg = TheCall->getArg(ArgNum);
1980 if (Arg->isTypeDependent() || Arg->isValueDependent())
1981 return false;
1982
1983 // Check constant-ness first.
1984 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1985 return true;
1986
1987 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1988 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1989 // combined with ROUND_NO_EXC.
1990 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1991 Result == 8/*ROUND_NO_EXC*/ ||
1992 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1993 return false;
1994
1995 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1996 << Arg->getSourceRange();
1997}
1998
Craig Topperdf5beb22017-03-13 17:16:50 +00001999// Check if the gather/scatter scale is legal.
2000bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2001 CallExpr *TheCall) {
2002 unsigned ArgNum = 0;
2003 switch (BuiltinID) {
2004 default:
2005 return false;
2006 case X86::BI__builtin_ia32_gatherpfdpd:
2007 case X86::BI__builtin_ia32_gatherpfdps:
2008 case X86::BI__builtin_ia32_gatherpfqpd:
2009 case X86::BI__builtin_ia32_gatherpfqps:
2010 case X86::BI__builtin_ia32_scatterpfdpd:
2011 case X86::BI__builtin_ia32_scatterpfdps:
2012 case X86::BI__builtin_ia32_scatterpfqpd:
2013 case X86::BI__builtin_ia32_scatterpfqps:
2014 ArgNum = 3;
2015 break;
2016 case X86::BI__builtin_ia32_gatherd_pd:
2017 case X86::BI__builtin_ia32_gatherd_pd256:
2018 case X86::BI__builtin_ia32_gatherq_pd:
2019 case X86::BI__builtin_ia32_gatherq_pd256:
2020 case X86::BI__builtin_ia32_gatherd_ps:
2021 case X86::BI__builtin_ia32_gatherd_ps256:
2022 case X86::BI__builtin_ia32_gatherq_ps:
2023 case X86::BI__builtin_ia32_gatherq_ps256:
2024 case X86::BI__builtin_ia32_gatherd_q:
2025 case X86::BI__builtin_ia32_gatherd_q256:
2026 case X86::BI__builtin_ia32_gatherq_q:
2027 case X86::BI__builtin_ia32_gatherq_q256:
2028 case X86::BI__builtin_ia32_gatherd_d:
2029 case X86::BI__builtin_ia32_gatherd_d256:
2030 case X86::BI__builtin_ia32_gatherq_d:
2031 case X86::BI__builtin_ia32_gatherq_d256:
2032 case X86::BI__builtin_ia32_gather3div2df:
2033 case X86::BI__builtin_ia32_gather3div2di:
2034 case X86::BI__builtin_ia32_gather3div4df:
2035 case X86::BI__builtin_ia32_gather3div4di:
2036 case X86::BI__builtin_ia32_gather3div4sf:
2037 case X86::BI__builtin_ia32_gather3div4si:
2038 case X86::BI__builtin_ia32_gather3div8sf:
2039 case X86::BI__builtin_ia32_gather3div8si:
2040 case X86::BI__builtin_ia32_gather3siv2df:
2041 case X86::BI__builtin_ia32_gather3siv2di:
2042 case X86::BI__builtin_ia32_gather3siv4df:
2043 case X86::BI__builtin_ia32_gather3siv4di:
2044 case X86::BI__builtin_ia32_gather3siv4sf:
2045 case X86::BI__builtin_ia32_gather3siv4si:
2046 case X86::BI__builtin_ia32_gather3siv8sf:
2047 case X86::BI__builtin_ia32_gather3siv8si:
2048 case X86::BI__builtin_ia32_gathersiv8df:
2049 case X86::BI__builtin_ia32_gathersiv16sf:
2050 case X86::BI__builtin_ia32_gatherdiv8df:
2051 case X86::BI__builtin_ia32_gatherdiv16sf:
2052 case X86::BI__builtin_ia32_gathersiv8di:
2053 case X86::BI__builtin_ia32_gathersiv16si:
2054 case X86::BI__builtin_ia32_gatherdiv8di:
2055 case X86::BI__builtin_ia32_gatherdiv16si:
2056 case X86::BI__builtin_ia32_scatterdiv2df:
2057 case X86::BI__builtin_ia32_scatterdiv2di:
2058 case X86::BI__builtin_ia32_scatterdiv4df:
2059 case X86::BI__builtin_ia32_scatterdiv4di:
2060 case X86::BI__builtin_ia32_scatterdiv4sf:
2061 case X86::BI__builtin_ia32_scatterdiv4si:
2062 case X86::BI__builtin_ia32_scatterdiv8sf:
2063 case X86::BI__builtin_ia32_scatterdiv8si:
2064 case X86::BI__builtin_ia32_scattersiv2df:
2065 case X86::BI__builtin_ia32_scattersiv2di:
2066 case X86::BI__builtin_ia32_scattersiv4df:
2067 case X86::BI__builtin_ia32_scattersiv4di:
2068 case X86::BI__builtin_ia32_scattersiv4sf:
2069 case X86::BI__builtin_ia32_scattersiv4si:
2070 case X86::BI__builtin_ia32_scattersiv8sf:
2071 case X86::BI__builtin_ia32_scattersiv8si:
2072 case X86::BI__builtin_ia32_scattersiv8df:
2073 case X86::BI__builtin_ia32_scattersiv16sf:
2074 case X86::BI__builtin_ia32_scatterdiv8df:
2075 case X86::BI__builtin_ia32_scatterdiv16sf:
2076 case X86::BI__builtin_ia32_scattersiv8di:
2077 case X86::BI__builtin_ia32_scattersiv16si:
2078 case X86::BI__builtin_ia32_scatterdiv8di:
2079 case X86::BI__builtin_ia32_scatterdiv16si:
2080 ArgNum = 4;
2081 break;
2082 }
2083
2084 llvm::APSInt Result;
2085
2086 // We can't check the value of a dependent argument.
2087 Expr *Arg = TheCall->getArg(ArgNum);
2088 if (Arg->isTypeDependent() || Arg->isValueDependent())
2089 return false;
2090
2091 // Check constant-ness first.
2092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2093 return true;
2094
2095 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2096 return false;
2097
2098 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2099 << Arg->getSourceRange();
2100}
2101
Craig Topperf0ddc892016-09-23 04:48:27 +00002102bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2103 if (BuiltinID == X86::BI__builtin_cpu_supports)
2104 return SemaBuiltinCpuSupports(*this, TheCall);
2105
Craig Toppera7e253e2016-09-23 04:48:31 +00002106 // If the intrinsic has rounding or SAE make sure its valid.
2107 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2108 return true;
2109
Craig Topperdf5beb22017-03-13 17:16:50 +00002110 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2111 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2112 return true;
2113
Craig Topperf0ddc892016-09-23 04:48:27 +00002114 // For intrinsics which take an immediate value as part of the instruction,
2115 // range check them here.
2116 int i = 0, l = 0, u = 0;
2117 switch (BuiltinID) {
2118 default:
2119 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002120 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002121 i = 1; l = 0; u = 3;
2122 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002123 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002124 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2125 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2126 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2127 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002128 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002129 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002130 case X86::BI__builtin_ia32_vpermil2pd:
2131 case X86::BI__builtin_ia32_vpermil2pd256:
2132 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002133 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002134 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002135 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002136 case X86::BI__builtin_ia32_cmpb128_mask:
2137 case X86::BI__builtin_ia32_cmpw128_mask:
2138 case X86::BI__builtin_ia32_cmpd128_mask:
2139 case X86::BI__builtin_ia32_cmpq128_mask:
2140 case X86::BI__builtin_ia32_cmpb256_mask:
2141 case X86::BI__builtin_ia32_cmpw256_mask:
2142 case X86::BI__builtin_ia32_cmpd256_mask:
2143 case X86::BI__builtin_ia32_cmpq256_mask:
2144 case X86::BI__builtin_ia32_cmpb512_mask:
2145 case X86::BI__builtin_ia32_cmpw512_mask:
2146 case X86::BI__builtin_ia32_cmpd512_mask:
2147 case X86::BI__builtin_ia32_cmpq512_mask:
2148 case X86::BI__builtin_ia32_ucmpb128_mask:
2149 case X86::BI__builtin_ia32_ucmpw128_mask:
2150 case X86::BI__builtin_ia32_ucmpd128_mask:
2151 case X86::BI__builtin_ia32_ucmpq128_mask:
2152 case X86::BI__builtin_ia32_ucmpb256_mask:
2153 case X86::BI__builtin_ia32_ucmpw256_mask:
2154 case X86::BI__builtin_ia32_ucmpd256_mask:
2155 case X86::BI__builtin_ia32_ucmpq256_mask:
2156 case X86::BI__builtin_ia32_ucmpb512_mask:
2157 case X86::BI__builtin_ia32_ucmpw512_mask:
2158 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002159 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002160 case X86::BI__builtin_ia32_vpcomub:
2161 case X86::BI__builtin_ia32_vpcomuw:
2162 case X86::BI__builtin_ia32_vpcomud:
2163 case X86::BI__builtin_ia32_vpcomuq:
2164 case X86::BI__builtin_ia32_vpcomb:
2165 case X86::BI__builtin_ia32_vpcomw:
2166 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002167 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002168 i = 2; l = 0; u = 7;
2169 break;
2170 case X86::BI__builtin_ia32_roundps:
2171 case X86::BI__builtin_ia32_roundpd:
2172 case X86::BI__builtin_ia32_roundps256:
2173 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002174 i = 1; l = 0; u = 15;
2175 break;
2176 case X86::BI__builtin_ia32_roundss:
2177 case X86::BI__builtin_ia32_roundsd:
2178 case X86::BI__builtin_ia32_rangepd128_mask:
2179 case X86::BI__builtin_ia32_rangepd256_mask:
2180 case X86::BI__builtin_ia32_rangepd512_mask:
2181 case X86::BI__builtin_ia32_rangeps128_mask:
2182 case X86::BI__builtin_ia32_rangeps256_mask:
2183 case X86::BI__builtin_ia32_rangeps512_mask:
2184 case X86::BI__builtin_ia32_getmantsd_round_mask:
2185 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002186 i = 2; l = 0; u = 15;
2187 break;
2188 case X86::BI__builtin_ia32_cmpps:
2189 case X86::BI__builtin_ia32_cmpss:
2190 case X86::BI__builtin_ia32_cmppd:
2191 case X86::BI__builtin_ia32_cmpsd:
2192 case X86::BI__builtin_ia32_cmpps256:
2193 case X86::BI__builtin_ia32_cmppd256:
2194 case X86::BI__builtin_ia32_cmpps128_mask:
2195 case X86::BI__builtin_ia32_cmppd128_mask:
2196 case X86::BI__builtin_ia32_cmpps256_mask:
2197 case X86::BI__builtin_ia32_cmppd256_mask:
2198 case X86::BI__builtin_ia32_cmpps512_mask:
2199 case X86::BI__builtin_ia32_cmppd512_mask:
2200 case X86::BI__builtin_ia32_cmpsd_mask:
2201 case X86::BI__builtin_ia32_cmpss_mask:
2202 i = 2; l = 0; u = 31;
2203 break;
2204 case X86::BI__builtin_ia32_xabort:
2205 i = 0; l = -128; u = 255;
2206 break;
2207 case X86::BI__builtin_ia32_pshufw:
2208 case X86::BI__builtin_ia32_aeskeygenassist128:
2209 i = 1; l = -128; u = 255;
2210 break;
2211 case X86::BI__builtin_ia32_vcvtps2ph:
2212 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002213 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2214 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2215 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2216 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2217 case X86::BI__builtin_ia32_rndscaleps_mask:
2218 case X86::BI__builtin_ia32_rndscalepd_mask:
2219 case X86::BI__builtin_ia32_reducepd128_mask:
2220 case X86::BI__builtin_ia32_reducepd256_mask:
2221 case X86::BI__builtin_ia32_reducepd512_mask:
2222 case X86::BI__builtin_ia32_reduceps128_mask:
2223 case X86::BI__builtin_ia32_reduceps256_mask:
2224 case X86::BI__builtin_ia32_reduceps512_mask:
2225 case X86::BI__builtin_ia32_prold512_mask:
2226 case X86::BI__builtin_ia32_prolq512_mask:
2227 case X86::BI__builtin_ia32_prold128_mask:
2228 case X86::BI__builtin_ia32_prold256_mask:
2229 case X86::BI__builtin_ia32_prolq128_mask:
2230 case X86::BI__builtin_ia32_prolq256_mask:
2231 case X86::BI__builtin_ia32_prord128_mask:
2232 case X86::BI__builtin_ia32_prord256_mask:
2233 case X86::BI__builtin_ia32_prorq128_mask:
2234 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002235 case X86::BI__builtin_ia32_fpclasspd128_mask:
2236 case X86::BI__builtin_ia32_fpclasspd256_mask:
2237 case X86::BI__builtin_ia32_fpclassps128_mask:
2238 case X86::BI__builtin_ia32_fpclassps256_mask:
2239 case X86::BI__builtin_ia32_fpclassps512_mask:
2240 case X86::BI__builtin_ia32_fpclasspd512_mask:
2241 case X86::BI__builtin_ia32_fpclasssd_mask:
2242 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002243 i = 1; l = 0; u = 255;
2244 break;
2245 case X86::BI__builtin_ia32_palignr:
2246 case X86::BI__builtin_ia32_insertps128:
2247 case X86::BI__builtin_ia32_dpps:
2248 case X86::BI__builtin_ia32_dppd:
2249 case X86::BI__builtin_ia32_dpps256:
2250 case X86::BI__builtin_ia32_mpsadbw128:
2251 case X86::BI__builtin_ia32_mpsadbw256:
2252 case X86::BI__builtin_ia32_pcmpistrm128:
2253 case X86::BI__builtin_ia32_pcmpistri128:
2254 case X86::BI__builtin_ia32_pcmpistria128:
2255 case X86::BI__builtin_ia32_pcmpistric128:
2256 case X86::BI__builtin_ia32_pcmpistrio128:
2257 case X86::BI__builtin_ia32_pcmpistris128:
2258 case X86::BI__builtin_ia32_pcmpistriz128:
2259 case X86::BI__builtin_ia32_pclmulqdq128:
2260 case X86::BI__builtin_ia32_vperm2f128_pd256:
2261 case X86::BI__builtin_ia32_vperm2f128_ps256:
2262 case X86::BI__builtin_ia32_vperm2f128_si256:
2263 case X86::BI__builtin_ia32_permti256:
2264 i = 2; l = -128; u = 255;
2265 break;
2266 case X86::BI__builtin_ia32_palignr128:
2267 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002268 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002269 case X86::BI__builtin_ia32_vcomisd:
2270 case X86::BI__builtin_ia32_vcomiss:
2271 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2272 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2273 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2274 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002275 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2276 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2277 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2278 i = 2; l = 0; u = 255;
2279 break;
2280 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2281 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2282 case X86::BI__builtin_ia32_fixupimmps512_mask:
2283 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2284 case X86::BI__builtin_ia32_fixupimmsd_mask:
2285 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2286 case X86::BI__builtin_ia32_fixupimmss_mask:
2287 case X86::BI__builtin_ia32_fixupimmss_maskz:
2288 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2289 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2290 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2291 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2292 case X86::BI__builtin_ia32_fixupimmps128_mask:
2293 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2294 case X86::BI__builtin_ia32_fixupimmps256_mask:
2295 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2296 case X86::BI__builtin_ia32_pternlogd512_mask:
2297 case X86::BI__builtin_ia32_pternlogd512_maskz:
2298 case X86::BI__builtin_ia32_pternlogq512_mask:
2299 case X86::BI__builtin_ia32_pternlogq512_maskz:
2300 case X86::BI__builtin_ia32_pternlogd128_mask:
2301 case X86::BI__builtin_ia32_pternlogd128_maskz:
2302 case X86::BI__builtin_ia32_pternlogd256_mask:
2303 case X86::BI__builtin_ia32_pternlogd256_maskz:
2304 case X86::BI__builtin_ia32_pternlogq128_mask:
2305 case X86::BI__builtin_ia32_pternlogq128_maskz:
2306 case X86::BI__builtin_ia32_pternlogq256_mask:
2307 case X86::BI__builtin_ia32_pternlogq256_maskz:
2308 i = 3; l = 0; u = 255;
2309 break;
Craig Topper9625db02017-03-12 22:19:10 +00002310 case X86::BI__builtin_ia32_gatherpfdpd:
2311 case X86::BI__builtin_ia32_gatherpfdps:
2312 case X86::BI__builtin_ia32_gatherpfqpd:
2313 case X86::BI__builtin_ia32_gatherpfqps:
2314 case X86::BI__builtin_ia32_scatterpfdpd:
2315 case X86::BI__builtin_ia32_scatterpfdps:
2316 case X86::BI__builtin_ia32_scatterpfqpd:
2317 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002318 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002319 break;
Craig Topper39c87102016-05-18 03:18:12 +00002320 case X86::BI__builtin_ia32_pcmpestrm128:
2321 case X86::BI__builtin_ia32_pcmpestri128:
2322 case X86::BI__builtin_ia32_pcmpestria128:
2323 case X86::BI__builtin_ia32_pcmpestric128:
2324 case X86::BI__builtin_ia32_pcmpestrio128:
2325 case X86::BI__builtin_ia32_pcmpestris128:
2326 case X86::BI__builtin_ia32_pcmpestriz128:
2327 i = 4; l = -128; u = 255;
2328 break;
2329 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2330 case X86::BI__builtin_ia32_rndscaless_round_mask:
2331 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002332 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002333 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002334 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002335}
2336
Richard Smith55ce3522012-06-25 20:30:08 +00002337/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2338/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2339/// Returns true when the format fits the function and the FormatStringInfo has
2340/// been populated.
2341bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2342 FormatStringInfo *FSI) {
2343 FSI->HasVAListArg = Format->getFirstArg() == 0;
2344 FSI->FormatIdx = Format->getFormatIdx() - 1;
2345 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002346
Richard Smith55ce3522012-06-25 20:30:08 +00002347 // The way the format attribute works in GCC, the implicit this argument
2348 // of member functions is counted. However, it doesn't appear in our own
2349 // lists, so decrement format_idx in that case.
2350 if (IsCXXMember) {
2351 if(FSI->FormatIdx == 0)
2352 return false;
2353 --FSI->FormatIdx;
2354 if (FSI->FirstDataArg != 0)
2355 --FSI->FirstDataArg;
2356 }
2357 return true;
2358}
Mike Stump11289f42009-09-09 15:08:12 +00002359
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002360/// Checks if a the given expression evaluates to null.
2361///
2362/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002363static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002364 // If the expression has non-null type, it doesn't evaluate to null.
2365 if (auto nullability
2366 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2367 if (*nullability == NullabilityKind::NonNull)
2368 return false;
2369 }
2370
Ted Kremeneka146db32014-01-17 06:24:47 +00002371 // As a special case, transparent unions initialized with zero are
2372 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002373 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002374 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2375 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002376 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002377 if (const InitListExpr *ILE =
2378 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002379 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002380 }
2381
2382 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002383 return (!Expr->isValueDependent() &&
2384 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2385 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002386}
2387
2388static void CheckNonNullArgument(Sema &S,
2389 const Expr *ArgExpr,
2390 SourceLocation CallSiteLoc) {
2391 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002392 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2393 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002394}
2395
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002396bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2397 FormatStringInfo FSI;
2398 if ((GetFormatStringType(Format) == FST_NSString) &&
2399 getFormatStringInfo(Format, false, &FSI)) {
2400 Idx = FSI.FormatIdx;
2401 return true;
2402 }
2403 return false;
2404}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002405/// \brief Diagnose use of %s directive in an NSString which is being passed
2406/// as formatting string to formatting method.
2407static void
2408DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2409 const NamedDecl *FDecl,
2410 Expr **Args,
2411 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002412 unsigned Idx = 0;
2413 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002414 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2415 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002416 Idx = 2;
2417 Format = true;
2418 }
2419 else
2420 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2421 if (S.GetFormatNSStringIdx(I, Idx)) {
2422 Format = true;
2423 break;
2424 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002425 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002426 if (!Format || NumArgs <= Idx)
2427 return;
2428 const Expr *FormatExpr = Args[Idx];
2429 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2430 FormatExpr = CSCE->getSubExpr();
2431 const StringLiteral *FormatString;
2432 if (const ObjCStringLiteral *OSL =
2433 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2434 FormatString = OSL->getString();
2435 else
2436 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2437 if (!FormatString)
2438 return;
2439 if (S.FormatStringHasSArg(FormatString)) {
2440 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2441 << "%s" << 1 << 1;
2442 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2443 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002444 }
2445}
2446
Douglas Gregorb4866e82015-06-19 18:13:19 +00002447/// Determine whether the given type has a non-null nullability annotation.
2448static bool isNonNullType(ASTContext &ctx, QualType type) {
2449 if (auto nullability = type->getNullability(ctx))
2450 return *nullability == NullabilityKind::NonNull;
2451
2452 return false;
2453}
2454
Ted Kremenek2bc73332014-01-17 06:24:43 +00002455static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002456 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002457 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002458 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002459 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002460 assert((FDecl || Proto) && "Need a function declaration or prototype");
2461
Ted Kremenek9aedc152014-01-17 06:24:56 +00002462 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002463 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002464 if (FDecl) {
2465 // Handle the nonnull attribute on the function/method declaration itself.
2466 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2467 if (!NonNull->args_size()) {
2468 // Easy case: all pointer arguments are nonnull.
2469 for (const auto *Arg : Args)
2470 if (S.isValidPointerAttrType(Arg->getType()))
2471 CheckNonNullArgument(S, Arg, CallSiteLoc);
2472 return;
2473 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002474
Douglas Gregorb4866e82015-06-19 18:13:19 +00002475 for (unsigned Val : NonNull->args()) {
2476 if (Val >= Args.size())
2477 continue;
2478 if (NonNullArgs.empty())
2479 NonNullArgs.resize(Args.size());
2480 NonNullArgs.set(Val);
2481 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002482 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002483 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002484
Douglas Gregorb4866e82015-06-19 18:13:19 +00002485 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2486 // Handle the nonnull attribute on the parameters of the
2487 // function/method.
2488 ArrayRef<ParmVarDecl*> parms;
2489 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2490 parms = FD->parameters();
2491 else
2492 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2493
2494 unsigned ParamIndex = 0;
2495 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2496 I != E; ++I, ++ParamIndex) {
2497 const ParmVarDecl *PVD = *I;
2498 if (PVD->hasAttr<NonNullAttr>() ||
2499 isNonNullType(S.Context, PVD->getType())) {
2500 if (NonNullArgs.empty())
2501 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002502
Douglas Gregorb4866e82015-06-19 18:13:19 +00002503 NonNullArgs.set(ParamIndex);
2504 }
2505 }
2506 } else {
2507 // If we have a non-function, non-method declaration but no
2508 // function prototype, try to dig out the function prototype.
2509 if (!Proto) {
2510 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2511 QualType type = VD->getType().getNonReferenceType();
2512 if (auto pointerType = type->getAs<PointerType>())
2513 type = pointerType->getPointeeType();
2514 else if (auto blockType = type->getAs<BlockPointerType>())
2515 type = blockType->getPointeeType();
2516 // FIXME: data member pointers?
2517
2518 // Dig out the function prototype, if there is one.
2519 Proto = type->getAs<FunctionProtoType>();
2520 }
2521 }
2522
2523 // Fill in non-null argument information from the nullability
2524 // information on the parameter types (if we have them).
2525 if (Proto) {
2526 unsigned Index = 0;
2527 for (auto paramType : Proto->getParamTypes()) {
2528 if (isNonNullType(S.Context, paramType)) {
2529 if (NonNullArgs.empty())
2530 NonNullArgs.resize(Args.size());
2531
2532 NonNullArgs.set(Index);
2533 }
2534
2535 ++Index;
2536 }
2537 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002538 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002539
Douglas Gregorb4866e82015-06-19 18:13:19 +00002540 // Check for non-null arguments.
2541 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2542 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002543 if (NonNullArgs[ArgIndex])
2544 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002545 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002546}
2547
Richard Smith55ce3522012-06-25 20:30:08 +00002548/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002549/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2550/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002551void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002552 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2553 bool IsMemberFunction, SourceLocation Loc,
2554 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002555 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002556 if (CurContext->isDependentContext())
2557 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002558
Ted Kremenekb8176da2010-09-09 04:33:05 +00002559 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002560 llvm::SmallBitVector CheckedVarArgs;
2561 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002562 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002563 // Only create vector if there are format attributes.
2564 CheckedVarArgs.resize(Args.size());
2565
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002566 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002567 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002568 }
Richard Smithd7293d72013-08-05 18:49:43 +00002569 }
Richard Smith55ce3522012-06-25 20:30:08 +00002570
2571 // Refuse POD arguments that weren't caught by the format string
2572 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002573 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2574 if (CallType != VariadicDoesNotApply &&
2575 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002576 unsigned NumParams = Proto ? Proto->getNumParams()
2577 : FDecl && isa<FunctionDecl>(FDecl)
2578 ? cast<FunctionDecl>(FDecl)->getNumParams()
2579 : FDecl && isa<ObjCMethodDecl>(FDecl)
2580 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2581 : 0;
2582
Alp Toker9cacbab2014-01-20 20:26:09 +00002583 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002584 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002585 if (const Expr *Arg = Args[ArgIdx]) {
2586 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2587 checkVariadicArgument(Arg, CallType);
2588 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002589 }
Richard Smithd7293d72013-08-05 18:49:43 +00002590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Douglas Gregorb4866e82015-06-19 18:13:19 +00002592 if (FDecl || Proto) {
2593 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002594
Richard Trieu41bc0992013-06-22 00:20:41 +00002595 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002596 if (FDecl) {
2597 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2598 CheckArgumentWithTypeTag(I, Args.data());
2599 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002600 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002601
2602 if (FD)
2603 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002604}
2605
2606/// CheckConstructorCall - Check a constructor call for correctness and safety
2607/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002608void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2609 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002610 const FunctionProtoType *Proto,
2611 SourceLocation Loc) {
2612 VariadicCallType CallType =
2613 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002614 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2615 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002616}
2617
2618/// CheckFunctionCall - Check a direct function call for various correctness
2619/// and safety properties not strictly enforced by the C type system.
2620bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2621 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002622 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2623 isa<CXXMethodDecl>(FDecl);
2624 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2625 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002626 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2627 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002628 Expr** Args = TheCall->getArgs();
2629 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002630
2631 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002632 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002633 // If this is a call to a member operator, hide the first argument
2634 // from checkCall.
2635 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002636 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002637 ++Args;
2638 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002639 } else if (IsMemberFunction)
2640 ImplicitThis =
2641 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2642
2643 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002644 IsMemberFunction, TheCall->getRParenLoc(),
2645 TheCall->getCallee()->getSourceRange(), CallType);
2646
2647 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2648 // None of the checks below are needed for functions that don't have
2649 // simple names (e.g., C++ conversion functions).
2650 if (!FnInfo)
2651 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002652
Richard Trieua7f30b12016-12-06 01:42:28 +00002653 CheckAbsoluteValueFunction(TheCall, FDecl);
2654 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002655
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002656 if (getLangOpts().ObjC1)
2657 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002658
Anna Zaks22122702012-01-17 00:37:07 +00002659 unsigned CMId = FDecl->getMemoryFunctionKind();
2660 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002661 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002662
Anna Zaks201d4892012-01-13 21:52:01 +00002663 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002664 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002665 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002666 else if (CMId == Builtin::BIstrncat)
2667 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002668 else
Anna Zaks22122702012-01-17 00:37:07 +00002669 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002670
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002671 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002672}
2673
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002674bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002675 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002676 VariadicCallType CallType =
2677 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002678
George Burgess IVce6284b2017-01-28 02:19:40 +00002679 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2680 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002681 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002682
2683 return false;
2684}
2685
Richard Trieu664c4c62013-06-20 21:03:13 +00002686bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2687 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002688 QualType Ty;
2689 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002690 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002691 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002692 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002693 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002694 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002695
Douglas Gregorb4866e82015-06-19 18:13:19 +00002696 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2697 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002698 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002699
Richard Trieu664c4c62013-06-20 21:03:13 +00002700 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002701 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002702 CallType = VariadicDoesNotApply;
2703 } else if (Ty->isBlockPointerType()) {
2704 CallType = VariadicBlock;
2705 } else { // Ty->isFunctionPointerType()
2706 CallType = VariadicFunction;
2707 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002708
George Burgess IVce6284b2017-01-28 02:19:40 +00002709 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002710 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2711 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002712 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002713
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002714 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002715}
2716
Richard Trieu41bc0992013-06-22 00:20:41 +00002717/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2718/// such as function pointers returned from functions.
2719bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002720 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002721 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002722 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002723 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002724 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002725 TheCall->getCallee()->getSourceRange(), CallType);
2726
2727 return false;
2728}
2729
Tim Northovere94a34c2014-03-11 10:49:14 +00002730static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002731 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002732 return false;
2733
JF Bastiendda2cb12016-04-18 18:01:49 +00002734 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002735 switch (Op) {
2736 case AtomicExpr::AO__c11_atomic_init:
2737 llvm_unreachable("There is no ordering argument for an init");
2738
2739 case AtomicExpr::AO__c11_atomic_load:
2740 case AtomicExpr::AO__atomic_load_n:
2741 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002742 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2743 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002744
2745 case AtomicExpr::AO__c11_atomic_store:
2746 case AtomicExpr::AO__atomic_store:
2747 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002748 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2749 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2750 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002751
2752 default:
2753 return true;
2754 }
2755}
2756
Richard Smithfeea8832012-04-12 05:08:17 +00002757ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2758 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002759 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2760 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002761
Richard Smithfeea8832012-04-12 05:08:17 +00002762 // All these operations take one of the following forms:
2763 enum {
2764 // C __c11_atomic_init(A *, C)
2765 Init,
2766 // C __c11_atomic_load(A *, int)
2767 Load,
2768 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002769 LoadCopy,
2770 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002771 Copy,
2772 // C __c11_atomic_add(A *, M, int)
2773 Arithmetic,
2774 // C __atomic_exchange_n(A *, CP, int)
2775 Xchg,
2776 // void __atomic_exchange(A *, C *, CP, int)
2777 GNUXchg,
2778 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2779 C11CmpXchg,
2780 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2781 GNUCmpXchg
2782 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002783 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2784 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002785 // where:
2786 // C is an appropriate type,
2787 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2788 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2789 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2790 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002791
Gabor Horvath98bd0982015-03-16 09:59:54 +00002792 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2793 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2794 AtomicExpr::AO__atomic_load,
2795 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002796 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2797 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2798 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2799 Op == AtomicExpr::AO__atomic_store_n ||
2800 Op == AtomicExpr::AO__atomic_exchange_n ||
2801 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2802 bool IsAddSub = false;
2803
2804 switch (Op) {
2805 case AtomicExpr::AO__c11_atomic_init:
2806 Form = Init;
2807 break;
2808
2809 case AtomicExpr::AO__c11_atomic_load:
2810 case AtomicExpr::AO__atomic_load_n:
2811 Form = Load;
2812 break;
2813
Richard Smithfeea8832012-04-12 05:08:17 +00002814 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002815 Form = LoadCopy;
2816 break;
2817
2818 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002819 case AtomicExpr::AO__atomic_store:
2820 case AtomicExpr::AO__atomic_store_n:
2821 Form = Copy;
2822 break;
2823
2824 case AtomicExpr::AO__c11_atomic_fetch_add:
2825 case AtomicExpr::AO__c11_atomic_fetch_sub:
2826 case AtomicExpr::AO__atomic_fetch_add:
2827 case AtomicExpr::AO__atomic_fetch_sub:
2828 case AtomicExpr::AO__atomic_add_fetch:
2829 case AtomicExpr::AO__atomic_sub_fetch:
2830 IsAddSub = true;
2831 // Fall through.
2832 case AtomicExpr::AO__c11_atomic_fetch_and:
2833 case AtomicExpr::AO__c11_atomic_fetch_or:
2834 case AtomicExpr::AO__c11_atomic_fetch_xor:
2835 case AtomicExpr::AO__atomic_fetch_and:
2836 case AtomicExpr::AO__atomic_fetch_or:
2837 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002838 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002839 case AtomicExpr::AO__atomic_and_fetch:
2840 case AtomicExpr::AO__atomic_or_fetch:
2841 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002842 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002843 Form = Arithmetic;
2844 break;
2845
2846 case AtomicExpr::AO__c11_atomic_exchange:
2847 case AtomicExpr::AO__atomic_exchange_n:
2848 Form = Xchg;
2849 break;
2850
2851 case AtomicExpr::AO__atomic_exchange:
2852 Form = GNUXchg;
2853 break;
2854
2855 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2856 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2857 Form = C11CmpXchg;
2858 break;
2859
2860 case AtomicExpr::AO__atomic_compare_exchange:
2861 case AtomicExpr::AO__atomic_compare_exchange_n:
2862 Form = GNUCmpXchg;
2863 break;
2864 }
2865
2866 // Check we have the right number of arguments.
2867 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002868 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002869 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002870 << TheCall->getCallee()->getSourceRange();
2871 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002872 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2873 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002874 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002875 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002876 << TheCall->getCallee()->getSourceRange();
2877 return ExprError();
2878 }
2879
Richard Smithfeea8832012-04-12 05:08:17 +00002880 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002881 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002882 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2883 if (ConvertedPtr.isInvalid())
2884 return ExprError();
2885
2886 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002887 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2888 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002889 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002890 << Ptr->getType() << Ptr->getSourceRange();
2891 return ExprError();
2892 }
2893
Richard Smithfeea8832012-04-12 05:08:17 +00002894 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2895 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2896 QualType ValType = AtomTy; // 'C'
2897 if (IsC11) {
2898 if (!AtomTy->isAtomicType()) {
2899 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2900 << Ptr->getType() << Ptr->getSourceRange();
2901 return ExprError();
2902 }
Richard Smithe00921a2012-09-15 06:09:58 +00002903 if (AtomTy.isConstQualified()) {
2904 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2905 << Ptr->getType() << Ptr->getSourceRange();
2906 return ExprError();
2907 }
Richard Smithfeea8832012-04-12 05:08:17 +00002908 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002909 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002910 if (ValType.isConstQualified()) {
2911 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2912 << Ptr->getType() << Ptr->getSourceRange();
2913 return ExprError();
2914 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002915 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002916
Richard Smithfeea8832012-04-12 05:08:17 +00002917 // For an arithmetic operation, the implied arithmetic must be well-formed.
2918 if (Form == Arithmetic) {
2919 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2920 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2921 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2922 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2923 return ExprError();
2924 }
2925 if (!IsAddSub && !ValType->isIntegerType()) {
2926 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2927 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2928 return ExprError();
2929 }
David Majnemere85cff82015-01-28 05:48:06 +00002930 if (IsC11 && ValType->isPointerType() &&
2931 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2932 diag::err_incomplete_type)) {
2933 return ExprError();
2934 }
Richard Smithfeea8832012-04-12 05:08:17 +00002935 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2936 // For __atomic_*_n operations, the value type must be a scalar integral or
2937 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002938 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002939 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2940 return ExprError();
2941 }
2942
Eli Friedmanaa769812013-09-11 03:49:34 +00002943 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2944 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002945 // For GNU atomics, require a trivially-copyable type. This is not part of
2946 // the GNU atomics specification, but we enforce it for sanity.
2947 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002948 << Ptr->getType() << Ptr->getSourceRange();
2949 return ExprError();
2950 }
2951
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002952 switch (ValType.getObjCLifetime()) {
2953 case Qualifiers::OCL_None:
2954 case Qualifiers::OCL_ExplicitNone:
2955 // okay
2956 break;
2957
2958 case Qualifiers::OCL_Weak:
2959 case Qualifiers::OCL_Strong:
2960 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002961 // FIXME: Can this happen? By this point, ValType should be known
2962 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002963 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2964 << ValType << Ptr->getSourceRange();
2965 return ExprError();
2966 }
2967
David Majnemerc6eb6502015-06-03 00:26:35 +00002968 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2969 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002970 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002971 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002972 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002973 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002974 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002975 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002976 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002977 ResultType = Context.BoolTy;
2978
Richard Smithfeea8832012-04-12 05:08:17 +00002979 // The type of a parameter passed 'by value'. In the GNU atomics, such
2980 // arguments are actually passed as pointers.
2981 QualType ByValType = ValType; // 'CP'
2982 if (!IsC11 && !IsN)
2983 ByValType = Ptr->getType();
2984
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002985 // The first argument --- the pointer --- has a fixed type; we
2986 // deduce the types of the rest of the arguments accordingly. Walk
2987 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002988 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002989 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002990 if (i < NumVals[Form] + 1) {
2991 switch (i) {
2992 case 1:
2993 // The second argument is the non-atomic operand. For arithmetic, this
2994 // is always passed by value, and for a compare_exchange it is always
2995 // passed by address. For the rest, GNU uses by-address and C11 uses
2996 // by-value.
2997 assert(Form != Load);
2998 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2999 Ty = ValType;
3000 else if (Form == Copy || Form == Xchg)
3001 Ty = ByValType;
3002 else if (Form == Arithmetic)
3003 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003004 else {
3005 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003006 // Treat this argument as _Nonnull as we want to show a warning if
3007 // NULL is passed into it.
3008 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003009 unsigned AS = 0;
3010 // Keep address space of non-atomic pointer type.
3011 if (const PointerType *PtrTy =
3012 ValArg->getType()->getAs<PointerType>()) {
3013 AS = PtrTy->getPointeeType().getAddressSpace();
3014 }
3015 Ty = Context.getPointerType(
3016 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3017 }
Richard Smithfeea8832012-04-12 05:08:17 +00003018 break;
3019 case 2:
3020 // The third argument to compare_exchange / GNU exchange is a
3021 // (pointer to a) desired value.
3022 Ty = ByValType;
3023 break;
3024 case 3:
3025 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3026 Ty = Context.BoolTy;
3027 break;
3028 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003029 } else {
3030 // The order(s) are always converted to int.
3031 Ty = Context.IntTy;
3032 }
Richard Smithfeea8832012-04-12 05:08:17 +00003033
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003034 InitializedEntity Entity =
3035 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003036 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003037 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3038 if (Arg.isInvalid())
3039 return true;
3040 TheCall->setArg(i, Arg.get());
3041 }
3042
Richard Smithfeea8832012-04-12 05:08:17 +00003043 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003044 SmallVector<Expr*, 5> SubExprs;
3045 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003046 switch (Form) {
3047 case Init:
3048 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003049 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003050 break;
3051 case Load:
3052 SubExprs.push_back(TheCall->getArg(1)); // Order
3053 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003054 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003055 case Copy:
3056 case Arithmetic:
3057 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003058 SubExprs.push_back(TheCall->getArg(2)); // Order
3059 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003060 break;
3061 case GNUXchg:
3062 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3063 SubExprs.push_back(TheCall->getArg(3)); // Order
3064 SubExprs.push_back(TheCall->getArg(1)); // Val1
3065 SubExprs.push_back(TheCall->getArg(2)); // Val2
3066 break;
3067 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003068 SubExprs.push_back(TheCall->getArg(3)); // Order
3069 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003070 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003071 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003072 break;
3073 case GNUCmpXchg:
3074 SubExprs.push_back(TheCall->getArg(4)); // Order
3075 SubExprs.push_back(TheCall->getArg(1)); // Val1
3076 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3077 SubExprs.push_back(TheCall->getArg(2)); // Val2
3078 SubExprs.push_back(TheCall->getArg(3)); // Weak
3079 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003080 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003081
3082 if (SubExprs.size() >= 2 && Form != Init) {
3083 llvm::APSInt Result(32);
3084 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3085 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003086 Diag(SubExprs[1]->getLocStart(),
3087 diag::warn_atomic_op_has_invalid_memory_order)
3088 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003089 }
3090
Fariborz Jahanian615de762013-05-28 17:37:39 +00003091 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3092 SubExprs, ResultType, Op,
3093 TheCall->getRParenLoc());
3094
3095 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3096 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3097 Context.AtomicUsesUnsupportedLibcall(AE))
3098 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3099 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003100
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003101 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003102}
3103
John McCall29ad95b2011-08-27 01:09:30 +00003104/// checkBuiltinArgument - Given a call to a builtin function, perform
3105/// normal type-checking on the given argument, updating the call in
3106/// place. This is useful when a builtin function requires custom
3107/// type-checking for some of its arguments but not necessarily all of
3108/// them.
3109///
3110/// Returns true on error.
3111static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3112 FunctionDecl *Fn = E->getDirectCallee();
3113 assert(Fn && "builtin call without direct callee!");
3114
3115 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3116 InitializedEntity Entity =
3117 InitializedEntity::InitializeParameter(S.Context, Param);
3118
3119 ExprResult Arg = E->getArg(0);
3120 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3121 if (Arg.isInvalid())
3122 return true;
3123
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003124 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003125 return false;
3126}
3127
Chris Lattnerdc046542009-05-08 06:58:22 +00003128/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3129/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3130/// type of its first argument. The main ActOnCallExpr routines have already
3131/// promoted the types of arguments because all of these calls are prototyped as
3132/// void(...).
3133///
3134/// This function goes through and does final semantic checking for these
3135/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003136ExprResult
3137Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003138 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003139 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3140 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3141
3142 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003143 if (TheCall->getNumArgs() < 1) {
3144 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3145 << 0 << 1 << TheCall->getNumArgs()
3146 << TheCall->getCallee()->getSourceRange();
3147 return ExprError();
3148 }
Mike Stump11289f42009-09-09 15:08:12 +00003149
Chris Lattnerdc046542009-05-08 06:58:22 +00003150 // Inspect the first argument of the atomic builtin. This should always be
3151 // a pointer type, whose element is an integral scalar or pointer type.
3152 // Because it is a pointer type, we don't have to worry about any implicit
3153 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003154 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003155 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003156 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3157 if (FirstArgResult.isInvalid())
3158 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003159 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003160 TheCall->setArg(0, FirstArg);
3161
John McCall31168b02011-06-15 23:02:42 +00003162 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3163 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003164 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3165 << FirstArg->getType() << FirstArg->getSourceRange();
3166 return ExprError();
3167 }
Mike Stump11289f42009-09-09 15:08:12 +00003168
John McCall31168b02011-06-15 23:02:42 +00003169 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003170 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003171 !ValType->isBlockPointerType()) {
3172 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3173 << FirstArg->getType() << FirstArg->getSourceRange();
3174 return ExprError();
3175 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003176
John McCall31168b02011-06-15 23:02:42 +00003177 switch (ValType.getObjCLifetime()) {
3178 case Qualifiers::OCL_None:
3179 case Qualifiers::OCL_ExplicitNone:
3180 // okay
3181 break;
3182
3183 case Qualifiers::OCL_Weak:
3184 case Qualifiers::OCL_Strong:
3185 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003186 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003187 << ValType << FirstArg->getSourceRange();
3188 return ExprError();
3189 }
3190
John McCallb50451a2011-10-05 07:41:44 +00003191 // Strip any qualifiers off ValType.
3192 ValType = ValType.getUnqualifiedType();
3193
Chandler Carruth3973af72010-07-18 20:54:12 +00003194 // The majority of builtins return a value, but a few have special return
3195 // types, so allow them to override appropriately below.
3196 QualType ResultType = ValType;
3197
Chris Lattnerdc046542009-05-08 06:58:22 +00003198 // We need to figure out which concrete builtin this maps onto. For example,
3199 // __sync_fetch_and_add with a 2 byte object turns into
3200 // __sync_fetch_and_add_2.
3201#define BUILTIN_ROW(x) \
3202 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3203 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003204
Chris Lattnerdc046542009-05-08 06:58:22 +00003205 static const unsigned BuiltinIndices[][5] = {
3206 BUILTIN_ROW(__sync_fetch_and_add),
3207 BUILTIN_ROW(__sync_fetch_and_sub),
3208 BUILTIN_ROW(__sync_fetch_and_or),
3209 BUILTIN_ROW(__sync_fetch_and_and),
3210 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003211 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003212
Chris Lattnerdc046542009-05-08 06:58:22 +00003213 BUILTIN_ROW(__sync_add_and_fetch),
3214 BUILTIN_ROW(__sync_sub_and_fetch),
3215 BUILTIN_ROW(__sync_and_and_fetch),
3216 BUILTIN_ROW(__sync_or_and_fetch),
3217 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003218 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003219
Chris Lattnerdc046542009-05-08 06:58:22 +00003220 BUILTIN_ROW(__sync_val_compare_and_swap),
3221 BUILTIN_ROW(__sync_bool_compare_and_swap),
3222 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003223 BUILTIN_ROW(__sync_lock_release),
3224 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003225 };
Mike Stump11289f42009-09-09 15:08:12 +00003226#undef BUILTIN_ROW
3227
Chris Lattnerdc046542009-05-08 06:58:22 +00003228 // Determine the index of the size.
3229 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003230 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003231 case 1: SizeIndex = 0; break;
3232 case 2: SizeIndex = 1; break;
3233 case 4: SizeIndex = 2; break;
3234 case 8: SizeIndex = 3; break;
3235 case 16: SizeIndex = 4; break;
3236 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003237 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3238 << FirstArg->getType() << FirstArg->getSourceRange();
3239 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Chris Lattnerdc046542009-05-08 06:58:22 +00003242 // Each of these builtins has one pointer argument, followed by some number of
3243 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3244 // that we ignore. Find out which row of BuiltinIndices to read from as well
3245 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003246 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003247 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003248 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003249 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003250 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003251 case Builtin::BI__sync_fetch_and_add:
3252 case Builtin::BI__sync_fetch_and_add_1:
3253 case Builtin::BI__sync_fetch_and_add_2:
3254 case Builtin::BI__sync_fetch_and_add_4:
3255 case Builtin::BI__sync_fetch_and_add_8:
3256 case Builtin::BI__sync_fetch_and_add_16:
3257 BuiltinIndex = 0;
3258 break;
3259
3260 case Builtin::BI__sync_fetch_and_sub:
3261 case Builtin::BI__sync_fetch_and_sub_1:
3262 case Builtin::BI__sync_fetch_and_sub_2:
3263 case Builtin::BI__sync_fetch_and_sub_4:
3264 case Builtin::BI__sync_fetch_and_sub_8:
3265 case Builtin::BI__sync_fetch_and_sub_16:
3266 BuiltinIndex = 1;
3267 break;
3268
3269 case Builtin::BI__sync_fetch_and_or:
3270 case Builtin::BI__sync_fetch_and_or_1:
3271 case Builtin::BI__sync_fetch_and_or_2:
3272 case Builtin::BI__sync_fetch_and_or_4:
3273 case Builtin::BI__sync_fetch_and_or_8:
3274 case Builtin::BI__sync_fetch_and_or_16:
3275 BuiltinIndex = 2;
3276 break;
3277
3278 case Builtin::BI__sync_fetch_and_and:
3279 case Builtin::BI__sync_fetch_and_and_1:
3280 case Builtin::BI__sync_fetch_and_and_2:
3281 case Builtin::BI__sync_fetch_and_and_4:
3282 case Builtin::BI__sync_fetch_and_and_8:
3283 case Builtin::BI__sync_fetch_and_and_16:
3284 BuiltinIndex = 3;
3285 break;
Mike Stump11289f42009-09-09 15:08:12 +00003286
Douglas Gregor73722482011-11-28 16:30:08 +00003287 case Builtin::BI__sync_fetch_and_xor:
3288 case Builtin::BI__sync_fetch_and_xor_1:
3289 case Builtin::BI__sync_fetch_and_xor_2:
3290 case Builtin::BI__sync_fetch_and_xor_4:
3291 case Builtin::BI__sync_fetch_and_xor_8:
3292 case Builtin::BI__sync_fetch_and_xor_16:
3293 BuiltinIndex = 4;
3294 break;
3295
Hal Finkeld2208b52014-10-02 20:53:50 +00003296 case Builtin::BI__sync_fetch_and_nand:
3297 case Builtin::BI__sync_fetch_and_nand_1:
3298 case Builtin::BI__sync_fetch_and_nand_2:
3299 case Builtin::BI__sync_fetch_and_nand_4:
3300 case Builtin::BI__sync_fetch_and_nand_8:
3301 case Builtin::BI__sync_fetch_and_nand_16:
3302 BuiltinIndex = 5;
3303 WarnAboutSemanticsChange = true;
3304 break;
3305
Douglas Gregor73722482011-11-28 16:30:08 +00003306 case Builtin::BI__sync_add_and_fetch:
3307 case Builtin::BI__sync_add_and_fetch_1:
3308 case Builtin::BI__sync_add_and_fetch_2:
3309 case Builtin::BI__sync_add_and_fetch_4:
3310 case Builtin::BI__sync_add_and_fetch_8:
3311 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003312 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003313 break;
3314
3315 case Builtin::BI__sync_sub_and_fetch:
3316 case Builtin::BI__sync_sub_and_fetch_1:
3317 case Builtin::BI__sync_sub_and_fetch_2:
3318 case Builtin::BI__sync_sub_and_fetch_4:
3319 case Builtin::BI__sync_sub_and_fetch_8:
3320 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003321 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003322 break;
3323
3324 case Builtin::BI__sync_and_and_fetch:
3325 case Builtin::BI__sync_and_and_fetch_1:
3326 case Builtin::BI__sync_and_and_fetch_2:
3327 case Builtin::BI__sync_and_and_fetch_4:
3328 case Builtin::BI__sync_and_and_fetch_8:
3329 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003330 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003331 break;
3332
3333 case Builtin::BI__sync_or_and_fetch:
3334 case Builtin::BI__sync_or_and_fetch_1:
3335 case Builtin::BI__sync_or_and_fetch_2:
3336 case Builtin::BI__sync_or_and_fetch_4:
3337 case Builtin::BI__sync_or_and_fetch_8:
3338 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003339 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003340 break;
3341
3342 case Builtin::BI__sync_xor_and_fetch:
3343 case Builtin::BI__sync_xor_and_fetch_1:
3344 case Builtin::BI__sync_xor_and_fetch_2:
3345 case Builtin::BI__sync_xor_and_fetch_4:
3346 case Builtin::BI__sync_xor_and_fetch_8:
3347 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003348 BuiltinIndex = 10;
3349 break;
3350
3351 case Builtin::BI__sync_nand_and_fetch:
3352 case Builtin::BI__sync_nand_and_fetch_1:
3353 case Builtin::BI__sync_nand_and_fetch_2:
3354 case Builtin::BI__sync_nand_and_fetch_4:
3355 case Builtin::BI__sync_nand_and_fetch_8:
3356 case Builtin::BI__sync_nand_and_fetch_16:
3357 BuiltinIndex = 11;
3358 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003359 break;
Mike Stump11289f42009-09-09 15:08:12 +00003360
Chris Lattnerdc046542009-05-08 06:58:22 +00003361 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003362 case Builtin::BI__sync_val_compare_and_swap_1:
3363 case Builtin::BI__sync_val_compare_and_swap_2:
3364 case Builtin::BI__sync_val_compare_and_swap_4:
3365 case Builtin::BI__sync_val_compare_and_swap_8:
3366 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003367 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003368 NumFixed = 2;
3369 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003370
Chris Lattnerdc046542009-05-08 06:58:22 +00003371 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003372 case Builtin::BI__sync_bool_compare_and_swap_1:
3373 case Builtin::BI__sync_bool_compare_and_swap_2:
3374 case Builtin::BI__sync_bool_compare_and_swap_4:
3375 case Builtin::BI__sync_bool_compare_and_swap_8:
3376 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003377 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003378 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003379 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003380 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003381
3382 case Builtin::BI__sync_lock_test_and_set:
3383 case Builtin::BI__sync_lock_test_and_set_1:
3384 case Builtin::BI__sync_lock_test_and_set_2:
3385 case Builtin::BI__sync_lock_test_and_set_4:
3386 case Builtin::BI__sync_lock_test_and_set_8:
3387 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003388 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003389 break;
3390
Chris Lattnerdc046542009-05-08 06:58:22 +00003391 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003392 case Builtin::BI__sync_lock_release_1:
3393 case Builtin::BI__sync_lock_release_2:
3394 case Builtin::BI__sync_lock_release_4:
3395 case Builtin::BI__sync_lock_release_8:
3396 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003397 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003398 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003399 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003400 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003401
3402 case Builtin::BI__sync_swap:
3403 case Builtin::BI__sync_swap_1:
3404 case Builtin::BI__sync_swap_2:
3405 case Builtin::BI__sync_swap_4:
3406 case Builtin::BI__sync_swap_8:
3407 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003408 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003409 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003410 }
Mike Stump11289f42009-09-09 15:08:12 +00003411
Chris Lattnerdc046542009-05-08 06:58:22 +00003412 // Now that we know how many fixed arguments we expect, first check that we
3413 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003414 if (TheCall->getNumArgs() < 1+NumFixed) {
3415 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3416 << 0 << 1+NumFixed << TheCall->getNumArgs()
3417 << TheCall->getCallee()->getSourceRange();
3418 return ExprError();
3419 }
Mike Stump11289f42009-09-09 15:08:12 +00003420
Hal Finkeld2208b52014-10-02 20:53:50 +00003421 if (WarnAboutSemanticsChange) {
3422 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3423 << TheCall->getCallee()->getSourceRange();
3424 }
3425
Chris Lattner5b9241b2009-05-08 15:36:58 +00003426 // Get the decl for the concrete builtin from this, we can tell what the
3427 // concrete integer type we should convert to is.
3428 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003429 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003430 FunctionDecl *NewBuiltinDecl;
3431 if (NewBuiltinID == BuiltinID)
3432 NewBuiltinDecl = FDecl;
3433 else {
3434 // Perform builtin lookup to avoid redeclaring it.
3435 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3436 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3437 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3438 assert(Res.getFoundDecl());
3439 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003440 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003441 return ExprError();
3442 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003443
John McCallcf142162010-08-07 06:22:56 +00003444 // The first argument --- the pointer --- has a fixed type; we
3445 // deduce the types of the rest of the arguments accordingly. Walk
3446 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003447 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003448 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattnerdc046542009-05-08 06:58:22 +00003450 // GCC does an implicit conversion to the pointer or integer ValType. This
3451 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003452 // Initialize the argument.
3453 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3454 ValType, /*consume*/ false);
3455 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003456 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003457 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003458
Chris Lattnerdc046542009-05-08 06:58:22 +00003459 // Okay, we have something that *can* be converted to the right type. Check
3460 // to see if there is a potentially weird extension going on here. This can
3461 // happen when you do an atomic operation on something like an char* and
3462 // pass in 42. The 42 gets converted to char. This is even more strange
3463 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003464 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003465 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003466 }
Mike Stump11289f42009-09-09 15:08:12 +00003467
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003468 ASTContext& Context = this->getASTContext();
3469
3470 // Create a new DeclRefExpr to refer to the new decl.
3471 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3472 Context,
3473 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003474 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003475 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003476 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003477 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003478 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003479 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003480
Chris Lattnerdc046542009-05-08 06:58:22 +00003481 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003482 // FIXME: This loses syntactic information.
3483 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3484 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3485 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003486 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003487
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003488 // Change the result type of the call to match the original value type. This
3489 // is arbitrary, but the codegen for these builtins ins design to handle it
3490 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003491 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003492
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003493 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003494}
3495
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003496/// SemaBuiltinNontemporalOverloaded - We have a call to
3497/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3498/// overloaded function based on the pointer type of its last argument.
3499///
3500/// This function goes through and does final semantic checking for these
3501/// builtins.
3502ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3503 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3504 DeclRefExpr *DRE =
3505 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3506 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3507 unsigned BuiltinID = FDecl->getBuiltinID();
3508 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3509 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3510 "Unexpected nontemporal load/store builtin!");
3511 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3512 unsigned numArgs = isStore ? 2 : 1;
3513
3514 // Ensure that we have the proper number of arguments.
3515 if (checkArgCount(*this, TheCall, numArgs))
3516 return ExprError();
3517
3518 // Inspect the last argument of the nontemporal builtin. This should always
3519 // be a pointer type, from which we imply the type of the memory access.
3520 // Because it is a pointer type, we don't have to worry about any implicit
3521 // casts here.
3522 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3523 ExprResult PointerArgResult =
3524 DefaultFunctionArrayLvalueConversion(PointerArg);
3525
3526 if (PointerArgResult.isInvalid())
3527 return ExprError();
3528 PointerArg = PointerArgResult.get();
3529 TheCall->setArg(numArgs - 1, PointerArg);
3530
3531 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3532 if (!pointerType) {
3533 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3534 << PointerArg->getType() << PointerArg->getSourceRange();
3535 return ExprError();
3536 }
3537
3538 QualType ValType = pointerType->getPointeeType();
3539
3540 // Strip any qualifiers off ValType.
3541 ValType = ValType.getUnqualifiedType();
3542 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3543 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3544 !ValType->isVectorType()) {
3545 Diag(DRE->getLocStart(),
3546 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3547 << PointerArg->getType() << PointerArg->getSourceRange();
3548 return ExprError();
3549 }
3550
3551 if (!isStore) {
3552 TheCall->setType(ValType);
3553 return TheCallResult;
3554 }
3555
3556 ExprResult ValArg = TheCall->getArg(0);
3557 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3558 Context, ValType, /*consume*/ false);
3559 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3560 if (ValArg.isInvalid())
3561 return ExprError();
3562
3563 TheCall->setArg(0, ValArg.get());
3564 TheCall->setType(Context.VoidTy);
3565 return TheCallResult;
3566}
3567
Chris Lattner6436fb62009-02-18 06:01:06 +00003568/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003569/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003570/// Note: It might also make sense to do the UTF-16 conversion here (would
3571/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003572bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003573 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003574 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3575
Douglas Gregorfb65e592011-07-27 05:40:30 +00003576 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003577 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3578 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003579 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003580 }
Mike Stump11289f42009-09-09 15:08:12 +00003581
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003582 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003583 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003584 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003585 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3586 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3587 llvm::UTF16 *ToPtr = &ToBuf[0];
3588
3589 llvm::ConversionResult Result =
3590 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3591 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003592 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003593 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003594 Diag(Arg->getLocStart(),
3595 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3596 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003597 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003598}
3599
Mehdi Amini06d367c2016-10-24 20:39:34 +00003600/// CheckObjCString - Checks that the format string argument to the os_log()
3601/// and os_trace() functions is correct, and converts it to const char *.
3602ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3603 Arg = Arg->IgnoreParenCasts();
3604 auto *Literal = dyn_cast<StringLiteral>(Arg);
3605 if (!Literal) {
3606 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3607 Literal = ObjcLiteral->getString();
3608 }
3609 }
3610
3611 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3612 return ExprError(
3613 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3614 << Arg->getSourceRange());
3615 }
3616
3617 ExprResult Result(Literal);
3618 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3619 InitializedEntity Entity =
3620 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3621 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3622 return Result;
3623}
3624
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003625/// Check that the user is calling the appropriate va_start builtin for the
3626/// target and calling convention.
3627static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3628 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3629 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003630 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003631 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003632 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3633 if (IsX64 || IsAArch64) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003634 clang::CallingConv CC = CC_C;
3635 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3636 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3637 if (IsMSVAStart) {
3638 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003639 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003640 return S.Diag(Fn->getLocStart(),
3641 diag::err_ms_va_start_used_in_sysv_function);
3642 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003643 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003644 // On x64 Windows, don't allow this in System V ABI functions.
3645 // (Yes, that means there's no corresponding way to support variadic
3646 // System V ABI functions on Windows.)
3647 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003648 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003649 return S.Diag(Fn->getLocStart(),
3650 diag::err_va_start_used_in_wrong_abi_function)
3651 << !IsWindows;
3652 }
3653 return false;
3654 }
3655
3656 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003657 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003658 return false;
3659}
3660
3661static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3662 ParmVarDecl **LastParam = nullptr) {
3663 // Determine whether the current function, block, or obj-c method is variadic
3664 // and get its parameter list.
3665 bool IsVariadic = false;
3666 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003667 DeclContext *Caller = S.CurContext;
3668 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3669 IsVariadic = Block->isVariadic();
3670 Params = Block->parameters();
3671 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003672 IsVariadic = FD->isVariadic();
3673 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003674 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003675 IsVariadic = MD->isVariadic();
3676 // FIXME: This isn't correct for methods (results in bogus warning).
3677 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003678 } else if (isa<CapturedDecl>(Caller)) {
3679 // We don't support va_start in a CapturedDecl.
3680 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3681 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003682 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003683 // This must be some other declcontext that parses exprs.
3684 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3685 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003686 }
3687
3688 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003689 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003690 return true;
3691 }
3692
3693 if (LastParam)
3694 *LastParam = Params.empty() ? nullptr : Params.back();
3695
3696 return false;
3697}
3698
Charles Davisc7d5c942015-09-17 20:55:33 +00003699/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3700/// for validity. Emit an error and return true on failure; return false
3701/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003702bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003703 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003704
3705 if (checkVAStartABI(*this, BuiltinID, Fn))
3706 return true;
3707
Chris Lattner08464942007-12-28 05:29:59 +00003708 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003709 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003710 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003711 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3712 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003713 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003714 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003715 return true;
3716 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003717
3718 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003719 return Diag(TheCall->getLocEnd(),
3720 diag::err_typecheck_call_too_few_args_at_least)
3721 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003722 }
3723
John McCall29ad95b2011-08-27 01:09:30 +00003724 // Type-check the first argument normally.
3725 if (checkBuiltinArgument(*this, TheCall, 0))
3726 return true;
3727
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003728 // Check that the current function is variadic, and get its last parameter.
3729 ParmVarDecl *LastParam;
3730 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003731 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003732
Chris Lattner43be2e62007-12-19 23:59:04 +00003733 // Verify that the second argument to the builtin is the last argument of the
3734 // current function or method.
3735 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003736 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003737
Nico Weber9eea7642013-05-24 23:31:57 +00003738 // These are valid if SecondArgIsLastNamedArgument is false after the next
3739 // block.
3740 QualType Type;
3741 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003742 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003743
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003744 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3745 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003746 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003747
3748 Type = PV->getType();
3749 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003750 IsCRegister =
3751 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003752 }
3753 }
Mike Stump11289f42009-09-09 15:08:12 +00003754
Chris Lattner43be2e62007-12-19 23:59:04 +00003755 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003756 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003757 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003758 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003759 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3760 // Promotable integers are UB, but enumerations need a bit of
3761 // extra checking to see what their promotable type actually is.
3762 if (!Type->isPromotableIntegerType())
3763 return false;
3764 if (!Type->isEnumeralType())
3765 return true;
3766 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3767 return !(ED &&
3768 Context.typesAreCompatible(ED->getPromotionType(), Type));
3769 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003770 unsigned Reason = 0;
3771 if (Type->isReferenceType()) Reason = 1;
3772 else if (IsCRegister) Reason = 2;
3773 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003774 Diag(ParamLoc, diag::note_parameter_type) << Type;
3775 }
3776
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003777 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003778 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003779}
Chris Lattner43be2e62007-12-19 23:59:04 +00003780
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003781bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3782 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3783 // const char *named_addr);
3784
3785 Expr *Func = Call->getCallee();
3786
3787 if (Call->getNumArgs() < 3)
3788 return Diag(Call->getLocEnd(),
3789 diag::err_typecheck_call_too_few_args_at_least)
3790 << 0 /*function call*/ << 3 << Call->getNumArgs();
3791
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003792 // Type-check the first argument normally.
3793 if (checkBuiltinArgument(*this, Call, 0))
3794 return true;
3795
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003796 // Check that the current function is variadic.
3797 if (checkVAStartIsInVariadicFunction(*this, Func))
3798 return true;
3799
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003800 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003801 unsigned ArgNo;
3802 QualType Type;
3803 } ArgumentTypes[] = {
3804 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3805 { 2, Context.getSizeType() },
3806 };
3807
3808 for (const auto &AT : ArgumentTypes) {
3809 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3810 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3811 continue;
3812 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3813 << Arg->getType() << AT.Type << 1 /* different class */
3814 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3815 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3816 }
3817
3818 return false;
3819}
3820
Chris Lattner2da14fb2007-12-20 00:26:33 +00003821/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3822/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003823bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3824 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003825 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003826 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003827 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003828 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003829 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003830 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003831 << SourceRange(TheCall->getArg(2)->getLocStart(),
3832 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003833
John Wiegley01296292011-04-08 18:41:53 +00003834 ExprResult OrigArg0 = TheCall->getArg(0);
3835 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003836
Chris Lattner2da14fb2007-12-20 00:26:33 +00003837 // Do standard promotions between the two arguments, returning their common
3838 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003839 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003840 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3841 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003842
3843 // Make sure any conversions are pushed back into the call; this is
3844 // type safe since unordered compare builtins are declared as "_Bool
3845 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003846 TheCall->setArg(0, OrigArg0.get());
3847 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003848
John Wiegley01296292011-04-08 18:41:53 +00003849 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003850 return false;
3851
Chris Lattner2da14fb2007-12-20 00:26:33 +00003852 // If the common type isn't a real floating type, then the arguments were
3853 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003854 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003855 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003856 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003857 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3858 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003859
Chris Lattner2da14fb2007-12-20 00:26:33 +00003860 return false;
3861}
3862
Benjamin Kramer634fc102010-02-15 22:42:31 +00003863/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3864/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003865/// to check everything. We expect the last argument to be a floating point
3866/// value.
3867bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3868 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003869 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003870 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003871 if (TheCall->getNumArgs() > NumArgs)
3872 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003873 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003874 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003875 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003876 (*(TheCall->arg_end()-1))->getLocEnd());
3877
Benjamin Kramer64aae502010-02-16 10:07:31 +00003878 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003879
Eli Friedman7e4faac2009-08-31 20:06:00 +00003880 if (OrigArg->isTypeDependent())
3881 return false;
3882
Chris Lattner68784ef2010-05-06 05:50:07 +00003883 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003884 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003885 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003886 diag::err_typecheck_call_invalid_unary_fp)
3887 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003888
Neil Hickey88c0fac2016-12-13 16:22:50 +00003889 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003890 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003891 // Only remove standard FloatCasts, leaving other casts inplace
3892 if (Cast->getCastKind() == CK_FloatingCast) {
3893 Expr *CastArg = Cast->getSubExpr();
3894 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3895 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3896 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3897 "promotion from float to either float or double is the only expected cast here");
3898 Cast->setSubExpr(nullptr);
3899 TheCall->setArg(NumArgs-1, CastArg);
3900 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003901 }
3902 }
3903
Eli Friedman7e4faac2009-08-31 20:06:00 +00003904 return false;
3905}
3906
Tony Jiangbbc48e92017-05-24 15:13:32 +00003907// Customized Sema Checking for VSX builtins that have the following signature:
3908// vector [...] builtinName(vector [...], vector [...], const int);
3909// Which takes the same type of vectors (any legal vector type) for the first
3910// two arguments and takes compile time constant for the third argument.
3911// Example builtins are :
3912// vector double vec_xxpermdi(vector double, vector double, int);
3913// vector short vec_xxsldwi(vector short, vector short, int);
3914bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3915 unsigned ExpectedNumArgs = 3;
3916 if (TheCall->getNumArgs() < ExpectedNumArgs)
3917 return Diag(TheCall->getLocEnd(),
3918 diag::err_typecheck_call_too_few_args_at_least)
3919 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3920 << TheCall->getSourceRange();
3921
3922 if (TheCall->getNumArgs() > ExpectedNumArgs)
3923 return Diag(TheCall->getLocEnd(),
3924 diag::err_typecheck_call_too_many_args_at_most)
3925 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3926 << TheCall->getSourceRange();
3927
3928 // Check the third argument is a compile time constant
3929 llvm::APSInt Value;
3930 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3931 return Diag(TheCall->getLocStart(),
3932 diag::err_vsx_builtin_nonconstant_argument)
3933 << 3 /* argument index */ << TheCall->getDirectCallee()
3934 << SourceRange(TheCall->getArg(2)->getLocStart(),
3935 TheCall->getArg(2)->getLocEnd());
3936
3937 QualType Arg1Ty = TheCall->getArg(0)->getType();
3938 QualType Arg2Ty = TheCall->getArg(1)->getType();
3939
3940 // Check the type of argument 1 and argument 2 are vectors.
3941 SourceLocation BuiltinLoc = TheCall->getLocStart();
3942 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3943 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3944 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3945 << TheCall->getDirectCallee()
3946 << SourceRange(TheCall->getArg(0)->getLocStart(),
3947 TheCall->getArg(1)->getLocEnd());
3948 }
3949
3950 // Check the first two arguments are the same type.
3951 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3952 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3953 << TheCall->getDirectCallee()
3954 << SourceRange(TheCall->getArg(0)->getLocStart(),
3955 TheCall->getArg(1)->getLocEnd());
3956 }
3957
3958 // When default clang type checking is turned off and the customized type
3959 // checking is used, the returning type of the function must be explicitly
3960 // set. Otherwise it is _Bool by default.
3961 TheCall->setType(Arg1Ty);
3962
3963 return false;
3964}
3965
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003966/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3967// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003968ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003969 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003970 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003971 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003972 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3973 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003974
Nate Begemana0110022010-06-08 00:16:34 +00003975 // Determine which of the following types of shufflevector we're checking:
3976 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003977 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003978 QualType resType = TheCall->getArg(0)->getType();
3979 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003980
Douglas Gregorc25f7662009-05-19 22:10:17 +00003981 if (!TheCall->getArg(0)->isTypeDependent() &&
3982 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003983 QualType LHSType = TheCall->getArg(0)->getType();
3984 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003985
Craig Topperbaca3892013-07-29 06:47:04 +00003986 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3987 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003988 diag::err_vec_builtin_non_vector)
3989 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003990 << SourceRange(TheCall->getArg(0)->getLocStart(),
3991 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003992
Nate Begemana0110022010-06-08 00:16:34 +00003993 numElements = LHSType->getAs<VectorType>()->getNumElements();
3994 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003995
Nate Begemana0110022010-06-08 00:16:34 +00003996 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3997 // with mask. If so, verify that RHS is an integer vector type with the
3998 // same number of elts as lhs.
3999 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004000 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004001 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004002 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004003 diag::err_vec_builtin_incompatible_vector)
4004 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004005 << SourceRange(TheCall->getArg(1)->getLocStart(),
4006 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004007 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004008 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004009 diag::err_vec_builtin_incompatible_vector)
4010 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004011 << SourceRange(TheCall->getArg(0)->getLocStart(),
4012 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004013 } else if (numElements != numResElements) {
4014 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004015 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004016 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004017 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004018 }
4019
4020 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004021 if (TheCall->getArg(i)->isTypeDependent() ||
4022 TheCall->getArg(i)->isValueDependent())
4023 continue;
4024
Nate Begemana0110022010-06-08 00:16:34 +00004025 llvm::APSInt Result(32);
4026 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4027 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004028 diag::err_shufflevector_nonconstant_argument)
4029 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004030
Craig Topper50ad5b72013-08-03 17:40:38 +00004031 // Allow -1 which will be translated to undef in the IR.
4032 if (Result.isSigned() && Result.isAllOnesValue())
4033 continue;
4034
Chris Lattner7ab824e2008-08-10 02:05:13 +00004035 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004036 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004037 diag::err_shufflevector_argument_too_large)
4038 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004039 }
4040
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004041 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004042
Chris Lattner7ab824e2008-08-10 02:05:13 +00004043 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004044 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004045 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004046 }
4047
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004048 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4049 TheCall->getCallee()->getLocStart(),
4050 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004051}
Chris Lattner43be2e62007-12-19 23:59:04 +00004052
Hal Finkelc4d7c822013-09-18 03:29:45 +00004053/// SemaConvertVectorExpr - Handle __builtin_convertvector
4054ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4055 SourceLocation BuiltinLoc,
4056 SourceLocation RParenLoc) {
4057 ExprValueKind VK = VK_RValue;
4058 ExprObjectKind OK = OK_Ordinary;
4059 QualType DstTy = TInfo->getType();
4060 QualType SrcTy = E->getType();
4061
4062 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4063 return ExprError(Diag(BuiltinLoc,
4064 diag::err_convertvector_non_vector)
4065 << E->getSourceRange());
4066 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4067 return ExprError(Diag(BuiltinLoc,
4068 diag::err_convertvector_non_vector_type));
4069
4070 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4071 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4072 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4073 if (SrcElts != DstElts)
4074 return ExprError(Diag(BuiltinLoc,
4075 diag::err_convertvector_incompatible_vector)
4076 << E->getSourceRange());
4077 }
4078
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004079 return new (Context)
4080 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004081}
4082
Daniel Dunbarb7257262008-07-21 22:59:13 +00004083/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4084// This is declared to take (const void*, ...) and can take two
4085// optional constant int args.
4086bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004087 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004088
Chris Lattner3b054132008-11-19 05:08:23 +00004089 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004090 return Diag(TheCall->getLocEnd(),
4091 diag::err_typecheck_call_too_many_args_at_most)
4092 << 0 /*function call*/ << 3 << NumArgs
4093 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004094
4095 // Argument 0 is checked for us and the remaining arguments must be
4096 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004097 for (unsigned i = 1; i != NumArgs; ++i)
4098 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004099 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004100
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004101 return false;
4102}
4103
Hal Finkelf0417332014-07-17 14:25:55 +00004104/// SemaBuiltinAssume - Handle __assume (MS Extension).
4105// __assume does not evaluate its arguments, and should warn if its argument
4106// has side effects.
4107bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4108 Expr *Arg = TheCall->getArg(0);
4109 if (Arg->isInstantiationDependent()) return false;
4110
4111 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004112 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004113 << Arg->getSourceRange()
4114 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4115
4116 return false;
4117}
4118
David Majnemer86b1bfa2016-10-31 18:07:57 +00004119/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004120/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4121/// than 8.
4122bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4123 // The alignment must be a constant integer.
4124 Expr *Arg = TheCall->getArg(1);
4125
4126 // We can't check the value of a dependent argument.
4127 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004128 if (const auto *UE =
4129 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4130 if (UE->getKind() == UETT_AlignOf)
4131 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4132 << Arg->getSourceRange();
4133
David Majnemer51169932016-10-31 05:37:48 +00004134 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4135
4136 if (!Result.isPowerOf2())
4137 return Diag(TheCall->getLocStart(),
4138 diag::err_alignment_not_power_of_two)
4139 << Arg->getSourceRange();
4140
4141 if (Result < Context.getCharWidth())
4142 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4143 << (unsigned)Context.getCharWidth()
4144 << Arg->getSourceRange();
4145
4146 if (Result > INT32_MAX)
4147 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4148 << INT32_MAX
4149 << Arg->getSourceRange();
4150 }
4151
4152 return false;
4153}
4154
4155/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004156/// as (const void*, size_t, ...) and can take one optional constant int arg.
4157bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4158 unsigned NumArgs = TheCall->getNumArgs();
4159
4160 if (NumArgs > 3)
4161 return Diag(TheCall->getLocEnd(),
4162 diag::err_typecheck_call_too_many_args_at_most)
4163 << 0 /*function call*/ << 3 << NumArgs
4164 << TheCall->getSourceRange();
4165
4166 // The alignment must be a constant integer.
4167 Expr *Arg = TheCall->getArg(1);
4168
4169 // We can't check the value of a dependent argument.
4170 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4171 llvm::APSInt Result;
4172 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4173 return true;
4174
4175 if (!Result.isPowerOf2())
4176 return Diag(TheCall->getLocStart(),
4177 diag::err_alignment_not_power_of_two)
4178 << Arg->getSourceRange();
4179 }
4180
4181 if (NumArgs > 2) {
4182 ExprResult Arg(TheCall->getArg(2));
4183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4184 Context.getSizeType(), false);
4185 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4186 if (Arg.isInvalid()) return true;
4187 TheCall->setArg(2, Arg.get());
4188 }
Hal Finkelf0417332014-07-17 14:25:55 +00004189
4190 return false;
4191}
4192
Mehdi Amini06d367c2016-10-24 20:39:34 +00004193bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4194 unsigned BuiltinID =
4195 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4196 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4197
4198 unsigned NumArgs = TheCall->getNumArgs();
4199 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4200 if (NumArgs < NumRequiredArgs) {
4201 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4202 << 0 /* function call */ << NumRequiredArgs << NumArgs
4203 << TheCall->getSourceRange();
4204 }
4205 if (NumArgs >= NumRequiredArgs + 0x100) {
4206 return Diag(TheCall->getLocEnd(),
4207 diag::err_typecheck_call_too_many_args_at_most)
4208 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4209 << TheCall->getSourceRange();
4210 }
4211 unsigned i = 0;
4212
4213 // For formatting call, check buffer arg.
4214 if (!IsSizeCall) {
4215 ExprResult Arg(TheCall->getArg(i));
4216 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4217 Context, Context.VoidPtrTy, false);
4218 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4219 if (Arg.isInvalid())
4220 return true;
4221 TheCall->setArg(i, Arg.get());
4222 i++;
4223 }
4224
4225 // Check string literal arg.
4226 unsigned FormatIdx = i;
4227 {
4228 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4229 if (Arg.isInvalid())
4230 return true;
4231 TheCall->setArg(i, Arg.get());
4232 i++;
4233 }
4234
4235 // Make sure variadic args are scalar.
4236 unsigned FirstDataArg = i;
4237 while (i < NumArgs) {
4238 ExprResult Arg = DefaultVariadicArgumentPromotion(
4239 TheCall->getArg(i), VariadicFunction, nullptr);
4240 if (Arg.isInvalid())
4241 return true;
4242 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4243 if (ArgSize.getQuantity() >= 0x100) {
4244 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4245 << i << (int)ArgSize.getQuantity() << 0xff
4246 << TheCall->getSourceRange();
4247 }
4248 TheCall->setArg(i, Arg.get());
4249 i++;
4250 }
4251
4252 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4253 // call to avoid duplicate diagnostics.
4254 if (!IsSizeCall) {
4255 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4256 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4257 bool Success = CheckFormatArguments(
4258 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4259 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4260 CheckedVarArgs);
4261 if (!Success)
4262 return true;
4263 }
4264
4265 if (IsSizeCall) {
4266 TheCall->setType(Context.getSizeType());
4267 } else {
4268 TheCall->setType(Context.VoidPtrTy);
4269 }
4270 return false;
4271}
4272
Eric Christopher8d0c6212010-04-17 02:26:23 +00004273/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4274/// TheCall is a constant expression.
4275bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4276 llvm::APSInt &Result) {
4277 Expr *Arg = TheCall->getArg(ArgNum);
4278 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4280
4281 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4282
4283 if (!Arg->isIntegerConstantExpr(Result, Context))
4284 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004285 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004286
Chris Lattnerd545ad12009-09-23 06:06:36 +00004287 return false;
4288}
4289
Richard Sandiford28940af2014-04-16 08:47:51 +00004290/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4291/// TheCall is a constant expression in the range [Low, High].
4292bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4293 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004294 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004295
4296 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004297 Expr *Arg = TheCall->getArg(ArgNum);
4298 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004299 return false;
4300
Eric Christopher8d0c6212010-04-17 02:26:23 +00004301 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004302 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004303 return true;
4304
Richard Sandiford28940af2014-04-16 08:47:51 +00004305 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004306 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004307 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004308
4309 return false;
4310}
4311
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004312/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4313/// TheCall is a constant expression is a multiple of Num..
4314bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4315 unsigned Num) {
4316 llvm::APSInt Result;
4317
4318 // We can't check the value of a dependent argument.
4319 Expr *Arg = TheCall->getArg(ArgNum);
4320 if (Arg->isTypeDependent() || Arg->isValueDependent())
4321 return false;
4322
4323 // Check constant-ness first.
4324 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4325 return true;
4326
4327 if (Result.getSExtValue() % Num != 0)
4328 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4329 << Num << Arg->getSourceRange();
4330
4331 return false;
4332}
4333
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004334/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4335/// TheCall is an ARM/AArch64 special register string literal.
4336bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4337 int ArgNum, unsigned ExpectedFieldNum,
4338 bool AllowName) {
4339 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4340 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4341 BuiltinID == ARM::BI__builtin_arm_rsr ||
4342 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4343 BuiltinID == ARM::BI__builtin_arm_wsr ||
4344 BuiltinID == ARM::BI__builtin_arm_wsrp;
4345 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4346 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4347 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4348 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4349 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4350 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4351 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4352
4353 // We can't check the value of a dependent argument.
4354 Expr *Arg = TheCall->getArg(ArgNum);
4355 if (Arg->isTypeDependent() || Arg->isValueDependent())
4356 return false;
4357
4358 // Check if the argument is a string literal.
4359 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4360 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4361 << Arg->getSourceRange();
4362
4363 // Check the type of special register given.
4364 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4365 SmallVector<StringRef, 6> Fields;
4366 Reg.split(Fields, ":");
4367
4368 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4369 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4370 << Arg->getSourceRange();
4371
4372 // If the string is the name of a register then we cannot check that it is
4373 // valid here but if the string is of one the forms described in ACLE then we
4374 // can check that the supplied fields are integers and within the valid
4375 // ranges.
4376 if (Fields.size() > 1) {
4377 bool FiveFields = Fields.size() == 5;
4378
4379 bool ValidString = true;
4380 if (IsARMBuiltin) {
4381 ValidString &= Fields[0].startswith_lower("cp") ||
4382 Fields[0].startswith_lower("p");
4383 if (ValidString)
4384 Fields[0] =
4385 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4386
4387 ValidString &= Fields[2].startswith_lower("c");
4388 if (ValidString)
4389 Fields[2] = Fields[2].drop_front(1);
4390
4391 if (FiveFields) {
4392 ValidString &= Fields[3].startswith_lower("c");
4393 if (ValidString)
4394 Fields[3] = Fields[3].drop_front(1);
4395 }
4396 }
4397
4398 SmallVector<int, 5> Ranges;
4399 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004400 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004401 else
4402 Ranges.append({15, 7, 15});
4403
4404 for (unsigned i=0; i<Fields.size(); ++i) {
4405 int IntField;
4406 ValidString &= !Fields[i].getAsInteger(10, IntField);
4407 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4408 }
4409
4410 if (!ValidString)
4411 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4412 << Arg->getSourceRange();
4413
4414 } else if (IsAArch64Builtin && Fields.size() == 1) {
4415 // If the register name is one of those that appear in the condition below
4416 // and the special register builtin being used is one of the write builtins,
4417 // then we require that the argument provided for writing to the register
4418 // is an integer constant expression. This is because it will be lowered to
4419 // an MSR (immediate) instruction, so we need to know the immediate at
4420 // compile time.
4421 if (TheCall->getNumArgs() != 2)
4422 return false;
4423
4424 std::string RegLower = Reg.lower();
4425 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4426 RegLower != "pan" && RegLower != "uao")
4427 return false;
4428
4429 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4430 }
4431
4432 return false;
4433}
4434
Eli Friedmanc97d0142009-05-03 06:04:26 +00004435/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004436/// This checks that the target supports __builtin_longjmp and
4437/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004438bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004439 if (!Context.getTargetInfo().hasSjLjLowering())
4440 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4441 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4442
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004443 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004444 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004445
Eric Christopher8d0c6212010-04-17 02:26:23 +00004446 // TODO: This is less than ideal. Overload this to take a value.
4447 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4448 return true;
4449
4450 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004451 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4452 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4453
4454 return false;
4455}
4456
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004457/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4458/// This checks that the target supports __builtin_setjmp.
4459bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4460 if (!Context.getTargetInfo().hasSjLjLowering())
4461 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4462 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4463 return false;
4464}
4465
Richard Smithd7293d72013-08-05 18:49:43 +00004466namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004467class UncoveredArgHandler {
4468 enum { Unknown = -1, AllCovered = -2 };
4469 signed FirstUncoveredArg;
4470 SmallVector<const Expr *, 4> DiagnosticExprs;
4471
4472public:
4473 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4474
4475 bool hasUncoveredArg() const {
4476 return (FirstUncoveredArg >= 0);
4477 }
4478
4479 unsigned getUncoveredArg() const {
4480 assert(hasUncoveredArg() && "no uncovered argument");
4481 return FirstUncoveredArg;
4482 }
4483
4484 void setAllCovered() {
4485 // A string has been found with all arguments covered, so clear out
4486 // the diagnostics.
4487 DiagnosticExprs.clear();
4488 FirstUncoveredArg = AllCovered;
4489 }
4490
4491 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4492 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4493
4494 // Don't update if a previous string covers all arguments.
4495 if (FirstUncoveredArg == AllCovered)
4496 return;
4497
4498 // UncoveredArgHandler tracks the highest uncovered argument index
4499 // and with it all the strings that match this index.
4500 if (NewFirstUncoveredArg == FirstUncoveredArg)
4501 DiagnosticExprs.push_back(StrExpr);
4502 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4503 DiagnosticExprs.clear();
4504 DiagnosticExprs.push_back(StrExpr);
4505 FirstUncoveredArg = NewFirstUncoveredArg;
4506 }
4507 }
4508
4509 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4510};
4511
Richard Smithd7293d72013-08-05 18:49:43 +00004512enum StringLiteralCheckType {
4513 SLCT_NotALiteral,
4514 SLCT_UncheckedLiteral,
4515 SLCT_CheckedLiteral
4516};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004517} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004518
Stephen Hines648c3692016-09-16 01:07:04 +00004519static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4520 BinaryOperatorKind BinOpKind,
4521 bool AddendIsRight) {
4522 unsigned BitWidth = Offset.getBitWidth();
4523 unsigned AddendBitWidth = Addend.getBitWidth();
4524 // There might be negative interim results.
4525 if (Addend.isUnsigned()) {
4526 Addend = Addend.zext(++AddendBitWidth);
4527 Addend.setIsSigned(true);
4528 }
4529 // Adjust the bit width of the APSInts.
4530 if (AddendBitWidth > BitWidth) {
4531 Offset = Offset.sext(AddendBitWidth);
4532 BitWidth = AddendBitWidth;
4533 } else if (BitWidth > AddendBitWidth) {
4534 Addend = Addend.sext(BitWidth);
4535 }
4536
4537 bool Ov = false;
4538 llvm::APSInt ResOffset = Offset;
4539 if (BinOpKind == BO_Add)
4540 ResOffset = Offset.sadd_ov(Addend, Ov);
4541 else {
4542 assert(AddendIsRight && BinOpKind == BO_Sub &&
4543 "operator must be add or sub with addend on the right");
4544 ResOffset = Offset.ssub_ov(Addend, Ov);
4545 }
4546
4547 // We add an offset to a pointer here so we should support an offset as big as
4548 // possible.
4549 if (Ov) {
4550 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004551 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004552 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4553 return;
4554 }
4555
4556 Offset = ResOffset;
4557}
4558
4559namespace {
4560// This is a wrapper class around StringLiteral to support offsetted string
4561// literals as format strings. It takes the offset into account when returning
4562// the string and its length or the source locations to display notes correctly.
4563class FormatStringLiteral {
4564 const StringLiteral *FExpr;
4565 int64_t Offset;
4566
4567 public:
4568 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4569 : FExpr(fexpr), Offset(Offset) {}
4570
4571 StringRef getString() const {
4572 return FExpr->getString().drop_front(Offset);
4573 }
4574
4575 unsigned getByteLength() const {
4576 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4577 }
4578 unsigned getLength() const { return FExpr->getLength() - Offset; }
4579 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4580
4581 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4582
4583 QualType getType() const { return FExpr->getType(); }
4584
4585 bool isAscii() const { return FExpr->isAscii(); }
4586 bool isWide() const { return FExpr->isWide(); }
4587 bool isUTF8() const { return FExpr->isUTF8(); }
4588 bool isUTF16() const { return FExpr->isUTF16(); }
4589 bool isUTF32() const { return FExpr->isUTF32(); }
4590 bool isPascal() const { return FExpr->isPascal(); }
4591
4592 SourceLocation getLocationOfByte(
4593 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4594 const TargetInfo &Target, unsigned *StartToken = nullptr,
4595 unsigned *StartTokenByteOffset = nullptr) const {
4596 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4597 StartToken, StartTokenByteOffset);
4598 }
4599
4600 SourceLocation getLocStart() const LLVM_READONLY {
4601 return FExpr->getLocStart().getLocWithOffset(Offset);
4602 }
4603 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4604};
4605} // end anonymous namespace
4606
4607static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004608 const Expr *OrigFormatExpr,
4609 ArrayRef<const Expr *> Args,
4610 bool HasVAListArg, unsigned format_idx,
4611 unsigned firstDataArg,
4612 Sema::FormatStringType Type,
4613 bool inFunctionCall,
4614 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004615 llvm::SmallBitVector &CheckedVarArgs,
4616 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004617
Richard Smith55ce3522012-06-25 20:30:08 +00004618// Determine if an expression is a string literal or constant string.
4619// If this function returns false on the arguments to a function expecting a
4620// format string, we will usually need to emit a warning.
4621// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004622static StringLiteralCheckType
4623checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4624 bool HasVAListArg, unsigned format_idx,
4625 unsigned firstDataArg, Sema::FormatStringType Type,
4626 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004627 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004628 UncoveredArgHandler &UncoveredArg,
4629 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004630 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004631 assert(Offset.isSigned() && "invalid offset");
4632
Douglas Gregorc25f7662009-05-19 22:10:17 +00004633 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004634 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004635
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004636 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004637
Richard Smithd7293d72013-08-05 18:49:43 +00004638 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004639 // Technically -Wformat-nonliteral does not warn about this case.
4640 // The behavior of printf and friends in this case is implementation
4641 // dependent. Ideally if the format string cannot be null then
4642 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004643 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004644
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004645 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004646 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004647 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004648 // The expression is a literal if both sub-expressions were, and it was
4649 // completely checked only if both sub-expressions were checked.
4650 const AbstractConditionalOperator *C =
4651 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004652
4653 // Determine whether it is necessary to check both sub-expressions, for
4654 // example, because the condition expression is a constant that can be
4655 // evaluated at compile time.
4656 bool CheckLeft = true, CheckRight = true;
4657
4658 bool Cond;
4659 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4660 if (Cond)
4661 CheckRight = false;
4662 else
4663 CheckLeft = false;
4664 }
4665
Stephen Hines648c3692016-09-16 01:07:04 +00004666 // We need to maintain the offsets for the right and the left hand side
4667 // separately to check if every possible indexed expression is a valid
4668 // string literal. They might have different offsets for different string
4669 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004670 StringLiteralCheckType Left;
4671 if (!CheckLeft)
4672 Left = SLCT_UncheckedLiteral;
4673 else {
4674 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4675 HasVAListArg, format_idx, firstDataArg,
4676 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004677 CheckedVarArgs, UncoveredArg, Offset);
4678 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004679 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004680 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004681 }
4682
Richard Smith55ce3522012-06-25 20:30:08 +00004683 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004684 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004685 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004686 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004687 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004688
4689 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004690 }
4691
4692 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004693 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4694 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004695 }
4696
John McCallc07a0c72011-02-17 10:25:35 +00004697 case Stmt::OpaqueValueExprClass:
4698 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4699 E = src;
4700 goto tryAgain;
4701 }
Richard Smith55ce3522012-06-25 20:30:08 +00004702 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004703
Ted Kremeneka8890832011-02-24 23:03:04 +00004704 case Stmt::PredefinedExprClass:
4705 // While __func__, etc., are technically not string literals, they
4706 // cannot contain format specifiers and thus are not a security
4707 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004708 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004709
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004710 case Stmt::DeclRefExprClass: {
4711 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004712
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004713 // As an exception, do not flag errors for variables binding to
4714 // const string literals.
4715 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4716 bool isConstant = false;
4717 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004718
Richard Smithd7293d72013-08-05 18:49:43 +00004719 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4720 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004721 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004722 isConstant = T.isConstant(S.Context) &&
4723 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004724 } else if (T->isObjCObjectPointerType()) {
4725 // In ObjC, there is usually no "const ObjectPointer" type,
4726 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004727 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004728 }
Mike Stump11289f42009-09-09 15:08:12 +00004729
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004730 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004731 if (const Expr *Init = VD->getAnyInitializer()) {
4732 // Look through initializers like const char c[] = { "foo" }
4733 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4734 if (InitList->isStringLiteralInit())
4735 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4736 }
Richard Smithd7293d72013-08-05 18:49:43 +00004737 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004738 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004739 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004740 /*InFunctionCall*/ false, CheckedVarArgs,
4741 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004742 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004743 }
Mike Stump11289f42009-09-09 15:08:12 +00004744
Anders Carlssonb012ca92009-06-28 19:55:58 +00004745 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4746 // special check to see if the format string is a function parameter
4747 // of the function calling the printf function. If the function
4748 // has an attribute indicating it is a printf-like function, then we
4749 // should suppress warnings concerning non-literals being used in a call
4750 // to a vprintf function. For example:
4751 //
4752 // void
4753 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4754 // va_list ap;
4755 // va_start(ap, fmt);
4756 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4757 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004758 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004759 if (HasVAListArg) {
4760 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4761 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4762 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004763 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004764 // adjust for implicit parameter
4765 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4766 if (MD->isInstance())
4767 ++PVIndex;
4768 // We also check if the formats are compatible.
4769 // We can't pass a 'scanf' string to a 'printf' function.
4770 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004771 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004772 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004773 }
4774 }
4775 }
4776 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004777 }
Mike Stump11289f42009-09-09 15:08:12 +00004778
Richard Smith55ce3522012-06-25 20:30:08 +00004779 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004780 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004781
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004782 case Stmt::CallExprClass:
4783 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004784 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004785 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4786 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4787 unsigned ArgIndex = FA->getFormatIdx();
4788 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4789 if (MD->isInstance())
4790 --ArgIndex;
4791 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004792
Richard Smithd7293d72013-08-05 18:49:43 +00004793 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004794 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004795 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004796 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004797 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4798 unsigned BuiltinID = FD->getBuiltinID();
4799 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4800 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4801 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004802 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004803 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004804 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004805 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004806 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004807 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004808 }
4809 }
Mike Stump11289f42009-09-09 15:08:12 +00004810
Richard Smith55ce3522012-06-25 20:30:08 +00004811 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004812 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004813 case Stmt::ObjCMessageExprClass: {
4814 const auto *ME = cast<ObjCMessageExpr>(E);
4815 if (const auto *ND = ME->getMethodDecl()) {
4816 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4817 unsigned ArgIndex = FA->getFormatIdx();
4818 const Expr *Arg = ME->getArg(ArgIndex - 1);
4819 return checkFormatStringExpr(
4820 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4821 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4822 }
4823 }
4824
4825 return SLCT_NotALiteral;
4826 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004827 case Stmt::ObjCStringLiteralClass:
4828 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004829 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004830
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004831 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004832 StrE = ObjCFExpr->getString();
4833 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004834 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004835
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004836 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004837 if (Offset.isNegative() || Offset > StrE->getLength()) {
4838 // TODO: It would be better to have an explicit warning for out of
4839 // bounds literals.
4840 return SLCT_NotALiteral;
4841 }
4842 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4843 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004844 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004845 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004846 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004847 }
Mike Stump11289f42009-09-09 15:08:12 +00004848
Richard Smith55ce3522012-06-25 20:30:08 +00004849 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004850 }
Stephen Hines648c3692016-09-16 01:07:04 +00004851 case Stmt::BinaryOperatorClass: {
4852 llvm::APSInt LResult;
4853 llvm::APSInt RResult;
4854
4855 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4856
4857 // A string literal + an int offset is still a string literal.
4858 if (BinOp->isAdditiveOp()) {
4859 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4860 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4861
4862 if (LIsInt != RIsInt) {
4863 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4864
4865 if (LIsInt) {
4866 if (BinOpKind == BO_Add) {
4867 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4868 E = BinOp->getRHS();
4869 goto tryAgain;
4870 }
4871 } else {
4872 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4873 E = BinOp->getLHS();
4874 goto tryAgain;
4875 }
4876 }
Stephen Hines648c3692016-09-16 01:07:04 +00004877 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004878
4879 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004880 }
4881 case Stmt::UnaryOperatorClass: {
4882 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4883 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4884 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4885 llvm::APSInt IndexResult;
4886 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4887 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4888 E = ASE->getBase();
4889 goto tryAgain;
4890 }
4891 }
4892
4893 return SLCT_NotALiteral;
4894 }
Mike Stump11289f42009-09-09 15:08:12 +00004895
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004896 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004897 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004898 }
4899}
4900
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004901Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004902 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004903 .Case("scanf", FST_Scanf)
4904 .Cases("printf", "printf0", FST_Printf)
4905 .Cases("NSString", "CFString", FST_NSString)
4906 .Case("strftime", FST_Strftime)
4907 .Case("strfmon", FST_Strfmon)
4908 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4909 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4910 .Case("os_trace", FST_OSLog)
4911 .Case("os_log", FST_OSLog)
4912 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004913}
4914
Jordan Rose3e0ec582012-07-19 18:10:23 +00004915/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004916/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004917/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004918bool Sema::CheckFormatArguments(const FormatAttr *Format,
4919 ArrayRef<const Expr *> Args,
4920 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004921 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004922 SourceLocation Loc, SourceRange Range,
4923 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004924 FormatStringInfo FSI;
4925 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004926 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004927 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004928 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004929 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004930}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004931
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004932bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004933 bool HasVAListArg, unsigned format_idx,
4934 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004935 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004936 SourceLocation Loc, SourceRange Range,
4937 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004938 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004939 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004940 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004941 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004942 }
Mike Stump11289f42009-09-09 15:08:12 +00004943
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004944 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004945
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004946 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004947 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004948 // Dynamically generated format strings are difficult to
4949 // automatically vet at compile time. Requiring that format strings
4950 // are string literals: (1) permits the checking of format strings by
4951 // the compiler and thereby (2) can practically remove the source of
4952 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004953
Mike Stump11289f42009-09-09 15:08:12 +00004954 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004955 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004956 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004957 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004958 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004959 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004960 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4961 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004962 /*IsFunctionCall*/ true, CheckedVarArgs,
4963 UncoveredArg,
4964 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004965
4966 // Generate a diagnostic where an uncovered argument is detected.
4967 if (UncoveredArg.hasUncoveredArg()) {
4968 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4969 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4970 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4971 }
4972
Richard Smith55ce3522012-06-25 20:30:08 +00004973 if (CT != SLCT_NotALiteral)
4974 // Literal format string found, check done!
4975 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004976
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004977 // Strftime is particular as it always uses a single 'time' argument,
4978 // so it is safe to pass a non-literal string.
4979 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004980 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004981
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004982 // Do not emit diag when the string param is a macro expansion and the
4983 // format is either NSString or CFString. This is a hack to prevent
4984 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4985 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004986 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4987 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004988 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004989
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004990 // If there are no arguments specified, warn with -Wformat-security, otherwise
4991 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004992 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004993 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4994 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004995 switch (Type) {
4996 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004997 break;
4998 case FST_Kprintf:
4999 case FST_FreeBSDKPrintf:
5000 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005001 Diag(FormatLoc, diag::note_format_security_fixit)
5002 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005003 break;
5004 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005005 Diag(FormatLoc, diag::note_format_security_fixit)
5006 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005007 break;
5008 }
5009 } else {
5010 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005011 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005012 }
Richard Smith55ce3522012-06-25 20:30:08 +00005013 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005014}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005015
Ted Kremenekab278de2010-01-28 23:39:18 +00005016namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005017class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5018protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005019 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005020 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005021 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005022 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005023 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005024 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005025 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005026 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005027 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005028 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005029 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005030 bool usesPositionalArgs;
5031 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005032 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005033 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005034 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005035 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005036
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005037public:
Stephen Hines648c3692016-09-16 01:07:04 +00005038 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005039 const Expr *origFormatExpr,
5040 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005041 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005042 ArrayRef<const Expr *> Args, unsigned formatIdx,
5043 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005044 llvm::SmallBitVector &CheckedVarArgs,
5045 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005046 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5047 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5048 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5049 usesPositionalArgs(false), atFirstArg(true),
5050 inFunctionCall(inFunctionCall), CallType(callType),
5051 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005052 CoveredArgs.resize(numDataArgs);
5053 CoveredArgs.reset();
5054 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005055
Ted Kremenek019d2242010-01-29 01:50:07 +00005056 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005057
Ted Kremenek02087932010-07-16 02:11:22 +00005058 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005059 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005060
Jordan Rose92303592012-09-08 04:00:03 +00005061 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005062 const analyze_format_string::FormatSpecifier &FS,
5063 const analyze_format_string::ConversionSpecifier &CS,
5064 const char *startSpecifier, unsigned specifierLen,
5065 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005066
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005067 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005068 const analyze_format_string::FormatSpecifier &FS,
5069 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005070
5071 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005072 const analyze_format_string::ConversionSpecifier &CS,
5073 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005074
Craig Toppere14c0f82014-03-12 04:55:44 +00005075 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005076
Craig Toppere14c0f82014-03-12 04:55:44 +00005077 void HandleInvalidPosition(const char *startSpecifier,
5078 unsigned specifierLen,
5079 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005080
Craig Toppere14c0f82014-03-12 04:55:44 +00005081 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005082
Craig Toppere14c0f82014-03-12 04:55:44 +00005083 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005084
Richard Trieu03cf7b72011-10-28 00:41:25 +00005085 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005086 static void
5087 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5088 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5089 bool IsStringLocation, Range StringRange,
5090 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005091
Ted Kremenek02087932010-07-16 02:11:22 +00005092protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005093 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5094 const char *startSpec,
5095 unsigned specifierLen,
5096 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005097
5098 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5099 const char *startSpec,
5100 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005101
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005102 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005103 CharSourceRange getSpecifierRange(const char *startSpecifier,
5104 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005105 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005106
Ted Kremenek5739de72010-01-29 01:06:55 +00005107 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005108
5109 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5110 const analyze_format_string::ConversionSpecifier &CS,
5111 const char *startSpecifier, unsigned specifierLen,
5112 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005113
5114 template <typename Range>
5115 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5116 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005117 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005118};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005119} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005120
Ted Kremenek02087932010-07-16 02:11:22 +00005121SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005122 return OrigFormatExpr->getSourceRange();
5123}
5124
Ted Kremenek02087932010-07-16 02:11:22 +00005125CharSourceRange CheckFormatHandler::
5126getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005127 SourceLocation Start = getLocationOfByte(startSpecifier);
5128 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5129
5130 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005131 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005132
5133 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005134}
5135
Ted Kremenek02087932010-07-16 02:11:22 +00005136SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005137 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5138 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005139}
5140
Ted Kremenek02087932010-07-16 02:11:22 +00005141void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5142 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005143 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5144 getLocationOfByte(startSpecifier),
5145 /*IsStringLocation*/true,
5146 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005147}
5148
Jordan Rose92303592012-09-08 04:00:03 +00005149void CheckFormatHandler::HandleInvalidLengthModifier(
5150 const analyze_format_string::FormatSpecifier &FS,
5151 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005152 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005153 using namespace analyze_format_string;
5154
5155 const LengthModifier &LM = FS.getLengthModifier();
5156 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5157
5158 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005159 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005160 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005161 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005162 getLocationOfByte(LM.getStart()),
5163 /*IsStringLocation*/true,
5164 getSpecifierRange(startSpecifier, specifierLen));
5165
5166 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5167 << FixedLM->toString()
5168 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5169
5170 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005171 FixItHint Hint;
5172 if (DiagID == diag::warn_format_nonsensical_length)
5173 Hint = FixItHint::CreateRemoval(LMRange);
5174
5175 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005176 getLocationOfByte(LM.getStart()),
5177 /*IsStringLocation*/true,
5178 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005179 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005180 }
5181}
5182
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005183void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005184 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005185 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005186 using namespace analyze_format_string;
5187
5188 const LengthModifier &LM = FS.getLengthModifier();
5189 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5190
5191 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005192 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005193 if (FixedLM) {
5194 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5195 << LM.toString() << 0,
5196 getLocationOfByte(LM.getStart()),
5197 /*IsStringLocation*/true,
5198 getSpecifierRange(startSpecifier, specifierLen));
5199
5200 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5201 << FixedLM->toString()
5202 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5203
5204 } else {
5205 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5206 << LM.toString() << 0,
5207 getLocationOfByte(LM.getStart()),
5208 /*IsStringLocation*/true,
5209 getSpecifierRange(startSpecifier, specifierLen));
5210 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005211}
5212
5213void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5214 const analyze_format_string::ConversionSpecifier &CS,
5215 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005216 using namespace analyze_format_string;
5217
5218 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005219 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005220 if (FixedCS) {
5221 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5222 << CS.toString() << /*conversion specifier*/1,
5223 getLocationOfByte(CS.getStart()),
5224 /*IsStringLocation*/true,
5225 getSpecifierRange(startSpecifier, specifierLen));
5226
5227 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5228 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5229 << FixedCS->toString()
5230 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5231 } else {
5232 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5233 << CS.toString() << /*conversion specifier*/1,
5234 getLocationOfByte(CS.getStart()),
5235 /*IsStringLocation*/true,
5236 getSpecifierRange(startSpecifier, specifierLen));
5237 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005238}
5239
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005240void CheckFormatHandler::HandlePosition(const char *startPos,
5241 unsigned posLen) {
5242 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5243 getLocationOfByte(startPos),
5244 /*IsStringLocation*/true,
5245 getSpecifierRange(startPos, posLen));
5246}
5247
Ted Kremenekd1668192010-02-27 01:41:03 +00005248void
Ted Kremenek02087932010-07-16 02:11:22 +00005249CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5250 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5252 << (unsigned) p,
5253 getLocationOfByte(startPos), /*IsStringLocation*/true,
5254 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005255}
5256
Ted Kremenek02087932010-07-16 02:11:22 +00005257void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005258 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005259 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5260 getLocationOfByte(startPos),
5261 /*IsStringLocation*/true,
5262 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005263}
5264
Ted Kremenek02087932010-07-16 02:11:22 +00005265void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005266 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005267 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005268 EmitFormatDiagnostic(
5269 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5270 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5271 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005272 }
Ted Kremenek02087932010-07-16 02:11:22 +00005273}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005274
Jordan Rose58bbe422012-07-19 18:10:08 +00005275// Note that this may return NULL if there was an error parsing or building
5276// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005277const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005278 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005279}
5280
5281void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005282 // Does the number of data arguments exceed the number of
5283 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005284 if (!HasVAListArg) {
5285 // Find any arguments that weren't covered.
5286 CoveredArgs.flip();
5287 signed notCoveredArg = CoveredArgs.find_first();
5288 if (notCoveredArg >= 0) {
5289 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005290 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5291 } else {
5292 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005293 }
5294 }
5295}
5296
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005297void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5298 const Expr *ArgExpr) {
5299 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5300 "Invalid state");
5301
5302 if (!ArgExpr)
5303 return;
5304
5305 SourceLocation Loc = ArgExpr->getLocStart();
5306
5307 if (S.getSourceManager().isInSystemMacro(Loc))
5308 return;
5309
5310 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5311 for (auto E : DiagnosticExprs)
5312 PDiag << E->getSourceRange();
5313
5314 CheckFormatHandler::EmitFormatDiagnostic(
5315 S, IsFunctionCall, DiagnosticExprs[0],
5316 PDiag, Loc, /*IsStringLocation*/false,
5317 DiagnosticExprs[0]->getSourceRange());
5318}
5319
Ted Kremenekce815422010-07-19 21:25:57 +00005320bool
5321CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5322 SourceLocation Loc,
5323 const char *startSpec,
5324 unsigned specifierLen,
5325 const char *csStart,
5326 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005327 bool keepGoing = true;
5328 if (argIndex < NumDataArgs) {
5329 // Consider the argument coverered, even though the specifier doesn't
5330 // make sense.
5331 CoveredArgs.set(argIndex);
5332 }
5333 else {
5334 // If argIndex exceeds the number of data arguments we
5335 // don't issue a warning because that is just a cascade of warnings (and
5336 // they may have intended '%%' anyway). We don't want to continue processing
5337 // the format string after this point, however, as we will like just get
5338 // gibberish when trying to match arguments.
5339 keepGoing = false;
5340 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005341
5342 StringRef Specifier(csStart, csLen);
5343
5344 // If the specifier in non-printable, it could be the first byte of a UTF-8
5345 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5346 // hex value.
5347 std::string CodePointStr;
5348 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005349 llvm::UTF32 CodePoint;
5350 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5351 const llvm::UTF8 *E =
5352 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5353 llvm::ConversionResult Result =
5354 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005355
Justin Lebar90910552016-09-30 00:38:45 +00005356 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005357 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005358 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005359 }
5360
5361 llvm::raw_string_ostream OS(CodePointStr);
5362 if (CodePoint < 256)
5363 OS << "\\x" << llvm::format("%02x", CodePoint);
5364 else if (CodePoint <= 0xFFFF)
5365 OS << "\\u" << llvm::format("%04x", CodePoint);
5366 else
5367 OS << "\\U" << llvm::format("%08x", CodePoint);
5368 OS.flush();
5369 Specifier = CodePointStr;
5370 }
5371
5372 EmitFormatDiagnostic(
5373 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5374 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5375
Ted Kremenekce815422010-07-19 21:25:57 +00005376 return keepGoing;
5377}
5378
Richard Trieu03cf7b72011-10-28 00:41:25 +00005379void
5380CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5381 const char *startSpec,
5382 unsigned specifierLen) {
5383 EmitFormatDiagnostic(
5384 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5385 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5386}
5387
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005388bool
5389CheckFormatHandler::CheckNumArgs(
5390 const analyze_format_string::FormatSpecifier &FS,
5391 const analyze_format_string::ConversionSpecifier &CS,
5392 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5393
5394 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005395 PartialDiagnostic PDiag = FS.usesPositionalArg()
5396 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5397 << (argIndex+1) << NumDataArgs)
5398 : S.PDiag(diag::warn_printf_insufficient_data_args);
5399 EmitFormatDiagnostic(
5400 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5401 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005402
5403 // Since more arguments than conversion tokens are given, by extension
5404 // all arguments are covered, so mark this as so.
5405 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005406 return false;
5407 }
5408 return true;
5409}
5410
Richard Trieu03cf7b72011-10-28 00:41:25 +00005411template<typename Range>
5412void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5413 SourceLocation Loc,
5414 bool IsStringLocation,
5415 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005416 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005417 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005418 Loc, IsStringLocation, StringRange, FixIt);
5419}
5420
5421/// \brief If the format string is not within the funcion call, emit a note
5422/// so that the function call and string are in diagnostic messages.
5423///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005424/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005425/// call and only one diagnostic message will be produced. Otherwise, an
5426/// extra note will be emitted pointing to location of the format string.
5427///
5428/// \param ArgumentExpr the expression that is passed as the format string
5429/// argument in the function call. Used for getting locations when two
5430/// diagnostics are emitted.
5431///
5432/// \param PDiag the callee should already have provided any strings for the
5433/// diagnostic message. This function only adds locations and fixits
5434/// to diagnostics.
5435///
5436/// \param Loc primary location for diagnostic. If two diagnostics are
5437/// required, one will be at Loc and a new SourceLocation will be created for
5438/// the other one.
5439///
5440/// \param IsStringLocation if true, Loc points to the format string should be
5441/// used for the note. Otherwise, Loc points to the argument list and will
5442/// be used with PDiag.
5443///
5444/// \param StringRange some or all of the string to highlight. This is
5445/// templated so it can accept either a CharSourceRange or a SourceRange.
5446///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005447/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005448template <typename Range>
5449void CheckFormatHandler::EmitFormatDiagnostic(
5450 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5451 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5452 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005453 if (InFunctionCall) {
5454 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5455 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005456 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005457 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005458 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5459 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005460
5461 const Sema::SemaDiagnosticBuilder &Note =
5462 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5463 diag::note_format_string_defined);
5464
5465 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005466 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005467 }
5468}
5469
Ted Kremenek02087932010-07-16 02:11:22 +00005470//===--- CHECK: Printf format string checking ------------------------------===//
5471
5472namespace {
5473class CheckPrintfHandler : public CheckFormatHandler {
5474public:
Stephen Hines648c3692016-09-16 01:07:04 +00005475 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005476 const Expr *origFormatExpr,
5477 const Sema::FormatStringType type, unsigned firstDataArg,
5478 unsigned numDataArgs, bool isObjC, const char *beg,
5479 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005480 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005481 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005482 llvm::SmallBitVector &CheckedVarArgs,
5483 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005484 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5485 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5486 inFunctionCall, CallType, CheckedVarArgs,
5487 UncoveredArg) {}
5488
5489 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5490
5491 /// Returns true if '%@' specifiers are allowed in the format string.
5492 bool allowsObjCArg() const {
5493 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5494 FSType == Sema::FST_OSTrace;
5495 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005496
Ted Kremenek02087932010-07-16 02:11:22 +00005497 bool HandleInvalidPrintfConversionSpecifier(
5498 const analyze_printf::PrintfSpecifier &FS,
5499 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005500 unsigned specifierLen) override;
5501
Ted Kremenek02087932010-07-16 02:11:22 +00005502 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5503 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005504 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005505 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5506 const char *StartSpecifier,
5507 unsigned SpecifierLen,
5508 const Expr *E);
5509
Ted Kremenek02087932010-07-16 02:11:22 +00005510 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5511 const char *startSpecifier, unsigned specifierLen);
5512 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5513 const analyze_printf::OptionalAmount &Amt,
5514 unsigned type,
5515 const char *startSpecifier, unsigned specifierLen);
5516 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5517 const analyze_printf::OptionalFlag &flag,
5518 const char *startSpecifier, unsigned specifierLen);
5519 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5520 const analyze_printf::OptionalFlag &ignoredFlag,
5521 const analyze_printf::OptionalFlag &flag,
5522 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005523 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005524 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005525
5526 void HandleEmptyObjCModifierFlag(const char *startFlag,
5527 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005528
Ted Kremenek2b417712015-07-02 05:39:16 +00005529 void HandleInvalidObjCModifierFlag(const char *startFlag,
5530 unsigned flagLen) override;
5531
5532 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5533 const char *flagsEnd,
5534 const char *conversionPosition)
5535 override;
5536};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005537} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005538
5539bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5540 const analyze_printf::PrintfSpecifier &FS,
5541 const char *startSpecifier,
5542 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005543 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005544 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005545
Ted Kremenekce815422010-07-19 21:25:57 +00005546 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5547 getLocationOfByte(CS.getStart()),
5548 startSpecifier, specifierLen,
5549 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005550}
5551
Ted Kremenek02087932010-07-16 02:11:22 +00005552bool CheckPrintfHandler::HandleAmount(
5553 const analyze_format_string::OptionalAmount &Amt,
5554 unsigned k, const char *startSpecifier,
5555 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005556 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005557 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005558 unsigned argIndex = Amt.getArgIndex();
5559 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005560 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5561 << k,
5562 getLocationOfByte(Amt.getStart()),
5563 /*IsStringLocation*/true,
5564 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005565 // Don't do any more checking. We will just emit
5566 // spurious errors.
5567 return false;
5568 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005569
Ted Kremenek5739de72010-01-29 01:06:55 +00005570 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005571 // Although not in conformance with C99, we also allow the argument to be
5572 // an 'unsigned int' as that is a reasonably safe case. GCC also
5573 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005574 CoveredArgs.set(argIndex);
5575 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005576 if (!Arg)
5577 return false;
5578
Ted Kremenek5739de72010-01-29 01:06:55 +00005579 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005580
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005581 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5582 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005583
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005584 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005585 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005586 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005587 << T << Arg->getSourceRange(),
5588 getLocationOfByte(Amt.getStart()),
5589 /*IsStringLocation*/true,
5590 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005591 // Don't do any more checking. We will just emit
5592 // spurious errors.
5593 return false;
5594 }
5595 }
5596 }
5597 return true;
5598}
Ted Kremenek5739de72010-01-29 01:06:55 +00005599
Tom Careb49ec692010-06-17 19:00:27 +00005600void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005601 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005602 const analyze_printf::OptionalAmount &Amt,
5603 unsigned type,
5604 const char *startSpecifier,
5605 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005606 const analyze_printf::PrintfConversionSpecifier &CS =
5607 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005608
Richard Trieu03cf7b72011-10-28 00:41:25 +00005609 FixItHint fixit =
5610 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5611 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5612 Amt.getConstantLength()))
5613 : FixItHint();
5614
5615 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5616 << type << CS.toString(),
5617 getLocationOfByte(Amt.getStart()),
5618 /*IsStringLocation*/true,
5619 getSpecifierRange(startSpecifier, specifierLen),
5620 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005621}
5622
Ted Kremenek02087932010-07-16 02:11:22 +00005623void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005624 const analyze_printf::OptionalFlag &flag,
5625 const char *startSpecifier,
5626 unsigned specifierLen) {
5627 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005628 const analyze_printf::PrintfConversionSpecifier &CS =
5629 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005630 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5631 << flag.toString() << CS.toString(),
5632 getLocationOfByte(flag.getPosition()),
5633 /*IsStringLocation*/true,
5634 getSpecifierRange(startSpecifier, specifierLen),
5635 FixItHint::CreateRemoval(
5636 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005637}
5638
5639void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005640 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005641 const analyze_printf::OptionalFlag &ignoredFlag,
5642 const analyze_printf::OptionalFlag &flag,
5643 const char *startSpecifier,
5644 unsigned specifierLen) {
5645 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005646 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5647 << ignoredFlag.toString() << flag.toString(),
5648 getLocationOfByte(ignoredFlag.getPosition()),
5649 /*IsStringLocation*/true,
5650 getSpecifierRange(startSpecifier, specifierLen),
5651 FixItHint::CreateRemoval(
5652 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005653}
5654
Ted Kremenek2b417712015-07-02 05:39:16 +00005655// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5656// bool IsStringLocation, Range StringRange,
5657// ArrayRef<FixItHint> Fixit = None);
5658
5659void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5660 unsigned flagLen) {
5661 // Warn about an empty flag.
5662 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5663 getLocationOfByte(startFlag),
5664 /*IsStringLocation*/true,
5665 getSpecifierRange(startFlag, flagLen));
5666}
5667
5668void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5669 unsigned flagLen) {
5670 // Warn about an invalid flag.
5671 auto Range = getSpecifierRange(startFlag, flagLen);
5672 StringRef flag(startFlag, flagLen);
5673 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5674 getLocationOfByte(startFlag),
5675 /*IsStringLocation*/true,
5676 Range, FixItHint::CreateRemoval(Range));
5677}
5678
5679void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5680 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5681 // Warn about using '[...]' without a '@' conversion.
5682 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5683 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5684 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5685 getLocationOfByte(conversionPosition),
5686 /*IsStringLocation*/true,
5687 Range, FixItHint::CreateRemoval(Range));
5688}
5689
Richard Smith55ce3522012-06-25 20:30:08 +00005690// Determines if the specified is a C++ class or struct containing
5691// a member with the specified name and kind (e.g. a CXXMethodDecl named
5692// "c_str()").
5693template<typename MemberKind>
5694static llvm::SmallPtrSet<MemberKind*, 1>
5695CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5696 const RecordType *RT = Ty->getAs<RecordType>();
5697 llvm::SmallPtrSet<MemberKind*, 1> Results;
5698
5699 if (!RT)
5700 return Results;
5701 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005702 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005703 return Results;
5704
Alp Tokerb6cc5922014-05-03 03:45:55 +00005705 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005706 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005707 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005708
5709 // We just need to include all members of the right kind turned up by the
5710 // filter, at this point.
5711 if (S.LookupQualifiedName(R, RT->getDecl()))
5712 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5713 NamedDecl *decl = (*I)->getUnderlyingDecl();
5714 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5715 Results.insert(FK);
5716 }
5717 return Results;
5718}
5719
Richard Smith2868a732014-02-28 01:36:39 +00005720/// Check if we could call '.c_str()' on an object.
5721///
5722/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5723/// allow the call, or if it would be ambiguous).
5724bool Sema::hasCStrMethod(const Expr *E) {
5725 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5726 MethodSet Results =
5727 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5728 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5729 MI != ME; ++MI)
5730 if ((*MI)->getMinRequiredArguments() == 0)
5731 return true;
5732 return false;
5733}
5734
Richard Smith55ce3522012-06-25 20:30:08 +00005735// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005736// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005737// Returns true when a c_str() conversion method is found.
5738bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005739 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005740 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5741
5742 MethodSet Results =
5743 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5744
5745 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5746 MI != ME; ++MI) {
5747 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005748 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005749 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005750 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005751 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005752 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5753 << "c_str()"
5754 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5755 return true;
5756 }
5757 }
5758
5759 return false;
5760}
5761
Ted Kremenekab278de2010-01-28 23:39:18 +00005762bool
Ted Kremenek02087932010-07-16 02:11:22 +00005763CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005764 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005765 const char *startSpecifier,
5766 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005767 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005768 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005769 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005770
Ted Kremenek6cd69422010-07-19 22:01:06 +00005771 if (FS.consumesDataArgument()) {
5772 if (atFirstArg) {
5773 atFirstArg = false;
5774 usesPositionalArgs = FS.usesPositionalArg();
5775 }
5776 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005777 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5778 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005779 return false;
5780 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005781 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005782
Ted Kremenekd1668192010-02-27 01:41:03 +00005783 // First check if the field width, precision, and conversion specifier
5784 // have matching data arguments.
5785 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5786 startSpecifier, specifierLen)) {
5787 return false;
5788 }
5789
5790 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5791 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005792 return false;
5793 }
5794
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005795 if (!CS.consumesDataArgument()) {
5796 // FIXME: Technically specifying a precision or field width here
5797 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005798 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005799 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005800
Ted Kremenek4a49d982010-02-26 19:18:41 +00005801 // Consume the argument.
5802 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005803 if (argIndex < NumDataArgs) {
5804 // The check to see if the argIndex is valid will come later.
5805 // We set the bit here because we may exit early from this
5806 // function if we encounter some other error.
5807 CoveredArgs.set(argIndex);
5808 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005809
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005810 // FreeBSD kernel extensions.
5811 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5812 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5813 // We need at least two arguments.
5814 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5815 return false;
5816
5817 // Claim the second argument.
5818 CoveredArgs.set(argIndex + 1);
5819
5820 // Type check the first argument (int for %b, pointer for %D)
5821 const Expr *Ex = getDataArg(argIndex);
5822 const analyze_printf::ArgType &AT =
5823 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5824 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5825 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5826 EmitFormatDiagnostic(
5827 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5828 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5829 << false << Ex->getSourceRange(),
5830 Ex->getLocStart(), /*IsStringLocation*/false,
5831 getSpecifierRange(startSpecifier, specifierLen));
5832
5833 // Type check the second argument (char * for both %b and %D)
5834 Ex = getDataArg(argIndex + 1);
5835 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5836 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5837 EmitFormatDiagnostic(
5838 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5839 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5840 << false << Ex->getSourceRange(),
5841 Ex->getLocStart(), /*IsStringLocation*/false,
5842 getSpecifierRange(startSpecifier, specifierLen));
5843
5844 return true;
5845 }
5846
Ted Kremenek4a49d982010-02-26 19:18:41 +00005847 // Check for using an Objective-C specific conversion specifier
5848 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005849 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005850 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5851 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005852 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005853
Mehdi Amini06d367c2016-10-24 20:39:34 +00005854 // %P can only be used with os_log.
5855 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5856 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5857 specifierLen);
5858 }
5859
5860 // %n is not allowed with os_log.
5861 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5862 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5863 getLocationOfByte(CS.getStart()),
5864 /*IsStringLocation*/ false,
5865 getSpecifierRange(startSpecifier, specifierLen));
5866
5867 return true;
5868 }
5869
5870 // Only scalars are allowed for os_trace.
5871 if (FSType == Sema::FST_OSTrace &&
5872 (CS.getKind() == ConversionSpecifier::PArg ||
5873 CS.getKind() == ConversionSpecifier::sArg ||
5874 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5875 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5876 specifierLen);
5877 }
5878
5879 // Check for use of public/private annotation outside of os_log().
5880 if (FSType != Sema::FST_OSLog) {
5881 if (FS.isPublic().isSet()) {
5882 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5883 << "public",
5884 getLocationOfByte(FS.isPublic().getPosition()),
5885 /*IsStringLocation*/ false,
5886 getSpecifierRange(startSpecifier, specifierLen));
5887 }
5888 if (FS.isPrivate().isSet()) {
5889 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5890 << "private",
5891 getLocationOfByte(FS.isPrivate().getPosition()),
5892 /*IsStringLocation*/ false,
5893 getSpecifierRange(startSpecifier, specifierLen));
5894 }
5895 }
5896
Tom Careb49ec692010-06-17 19:00:27 +00005897 // Check for invalid use of field width
5898 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005899 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005900 startSpecifier, specifierLen);
5901 }
5902
5903 // Check for invalid use of precision
5904 if (!FS.hasValidPrecision()) {
5905 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5906 startSpecifier, specifierLen);
5907 }
5908
Mehdi Amini06d367c2016-10-24 20:39:34 +00005909 // Precision is mandatory for %P specifier.
5910 if (CS.getKind() == ConversionSpecifier::PArg &&
5911 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5913 getLocationOfByte(startSpecifier),
5914 /*IsStringLocation*/ false,
5915 getSpecifierRange(startSpecifier, specifierLen));
5916 }
5917
Tom Careb49ec692010-06-17 19:00:27 +00005918 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005919 if (!FS.hasValidThousandsGroupingPrefix())
5920 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005921 if (!FS.hasValidLeadingZeros())
5922 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5923 if (!FS.hasValidPlusPrefix())
5924 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005925 if (!FS.hasValidSpacePrefix())
5926 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005927 if (!FS.hasValidAlternativeForm())
5928 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5929 if (!FS.hasValidLeftJustified())
5930 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5931
5932 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005933 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5934 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5935 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005936 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5937 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5938 startSpecifier, specifierLen);
5939
5940 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005941 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005942 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5943 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005944 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005945 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005946 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005947 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5948 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005949
Jordan Rose92303592012-09-08 04:00:03 +00005950 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5951 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5952
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005953 // The remaining checks depend on the data arguments.
5954 if (HasVAListArg)
5955 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005956
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005957 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005958 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005959
Jordan Rose58bbe422012-07-19 18:10:08 +00005960 const Expr *Arg = getDataArg(argIndex);
5961 if (!Arg)
5962 return true;
5963
5964 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005965}
5966
Jordan Roseaee34382012-09-05 22:56:26 +00005967static bool requiresParensToAddCast(const Expr *E) {
5968 // FIXME: We should have a general way to reason about operator
5969 // precedence and whether parens are actually needed here.
5970 // Take care of a few common cases where they aren't.
5971 const Expr *Inside = E->IgnoreImpCasts();
5972 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5973 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5974
5975 switch (Inside->getStmtClass()) {
5976 case Stmt::ArraySubscriptExprClass:
5977 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005978 case Stmt::CharacterLiteralClass:
5979 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005980 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005981 case Stmt::FloatingLiteralClass:
5982 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005983 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005984 case Stmt::ObjCArrayLiteralClass:
5985 case Stmt::ObjCBoolLiteralExprClass:
5986 case Stmt::ObjCBoxedExprClass:
5987 case Stmt::ObjCDictionaryLiteralClass:
5988 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005989 case Stmt::ObjCIvarRefExprClass:
5990 case Stmt::ObjCMessageExprClass:
5991 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005992 case Stmt::ObjCStringLiteralClass:
5993 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005994 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005995 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005996 case Stmt::UnaryOperatorClass:
5997 return false;
5998 default:
5999 return true;
6000 }
6001}
6002
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006003static std::pair<QualType, StringRef>
6004shouldNotPrintDirectly(const ASTContext &Context,
6005 QualType IntendedTy,
6006 const Expr *E) {
6007 // Use a 'while' to peel off layers of typedefs.
6008 QualType TyTy = IntendedTy;
6009 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6010 StringRef Name = UserTy->getDecl()->getName();
6011 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006012 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006013 .Case("NSInteger", Context.LongTy)
6014 .Case("NSUInteger", Context.UnsignedLongTy)
6015 .Case("SInt32", Context.IntTy)
6016 .Case("UInt32", Context.UnsignedIntTy)
6017 .Default(QualType());
6018
6019 if (!CastTy.isNull())
6020 return std::make_pair(CastTy, Name);
6021
6022 TyTy = UserTy->desugar();
6023 }
6024
6025 // Strip parens if necessary.
6026 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6027 return shouldNotPrintDirectly(Context,
6028 PE->getSubExpr()->getType(),
6029 PE->getSubExpr());
6030
6031 // If this is a conditional expression, then its result type is constructed
6032 // via usual arithmetic conversions and thus there might be no necessary
6033 // typedef sugar there. Recurse to operands to check for NSInteger &
6034 // Co. usage condition.
6035 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6036 QualType TrueTy, FalseTy;
6037 StringRef TrueName, FalseName;
6038
6039 std::tie(TrueTy, TrueName) =
6040 shouldNotPrintDirectly(Context,
6041 CO->getTrueExpr()->getType(),
6042 CO->getTrueExpr());
6043 std::tie(FalseTy, FalseName) =
6044 shouldNotPrintDirectly(Context,
6045 CO->getFalseExpr()->getType(),
6046 CO->getFalseExpr());
6047
6048 if (TrueTy == FalseTy)
6049 return std::make_pair(TrueTy, TrueName);
6050 else if (TrueTy.isNull())
6051 return std::make_pair(FalseTy, FalseName);
6052 else if (FalseTy.isNull())
6053 return std::make_pair(TrueTy, TrueName);
6054 }
6055
6056 return std::make_pair(QualType(), StringRef());
6057}
6058
Richard Smith55ce3522012-06-25 20:30:08 +00006059bool
6060CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6061 const char *StartSpecifier,
6062 unsigned SpecifierLen,
6063 const Expr *E) {
6064 using namespace analyze_format_string;
6065 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006066 // Now type check the data expression that matches the
6067 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006068 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006069 if (!AT.isValid())
6070 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006071
Jordan Rose598ec092012-12-05 18:44:40 +00006072 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006073 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6074 ExprTy = TET->getUnderlyingExpr()->getType();
6075 }
6076
Seth Cantrellb4802962015-03-04 03:12:10 +00006077 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6078
6079 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006080 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006081 }
Jordan Rose98709982012-06-04 22:48:57 +00006082
Jordan Rose22b74712012-09-05 22:56:19 +00006083 // Look through argument promotions for our error message's reported type.
6084 // This includes the integral and floating promotions, but excludes array
6085 // and function pointer decay; seeing that an argument intended to be a
6086 // string has type 'char [6]' is probably more confusing than 'char *'.
6087 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6088 if (ICE->getCastKind() == CK_IntegralCast ||
6089 ICE->getCastKind() == CK_FloatingCast) {
6090 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006091 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006092
6093 // Check if we didn't match because of an implicit cast from a 'char'
6094 // or 'short' to an 'int'. This is done because printf is a varargs
6095 // function.
6096 if (ICE->getType() == S.Context.IntTy ||
6097 ICE->getType() == S.Context.UnsignedIntTy) {
6098 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006099 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006100 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006101 }
Jordan Rose98709982012-06-04 22:48:57 +00006102 }
Jordan Rose598ec092012-12-05 18:44:40 +00006103 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6104 // Special case for 'a', which has type 'int' in C.
6105 // Note, however, that we do /not/ want to treat multibyte constants like
6106 // 'MooV' as characters! This form is deprecated but still exists.
6107 if (ExprTy == S.Context.IntTy)
6108 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6109 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006110 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006111
Jordan Rosebc53ed12014-05-31 04:12:14 +00006112 // Look through enums to their underlying type.
6113 bool IsEnum = false;
6114 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6115 ExprTy = EnumTy->getDecl()->getIntegerType();
6116 IsEnum = true;
6117 }
6118
Jordan Rose0e5badd2012-12-05 18:44:49 +00006119 // %C in an Objective-C context prints a unichar, not a wchar_t.
6120 // If the argument is an integer of some kind, believe the %C and suggest
6121 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006122 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006123 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006124 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6125 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6126 !ExprTy->isCharType()) {
6127 // 'unichar' is defined as a typedef of unsigned short, but we should
6128 // prefer using the typedef if it is visible.
6129 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006130
6131 // While we are here, check if the value is an IntegerLiteral that happens
6132 // to be within the valid range.
6133 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6134 const llvm::APInt &V = IL->getValue();
6135 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6136 return true;
6137 }
6138
Jordan Rose0e5badd2012-12-05 18:44:49 +00006139 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6140 Sema::LookupOrdinaryName);
6141 if (S.LookupName(Result, S.getCurScope())) {
6142 NamedDecl *ND = Result.getFoundDecl();
6143 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6144 if (TD->getUnderlyingType() == IntendedTy)
6145 IntendedTy = S.Context.getTypedefType(TD);
6146 }
6147 }
6148 }
6149
6150 // Special-case some of Darwin's platform-independence types by suggesting
6151 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006152 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006153 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006154 QualType CastTy;
6155 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6156 if (!CastTy.isNull()) {
6157 IntendedTy = CastTy;
6158 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006159 }
6160 }
6161
Jordan Rose22b74712012-09-05 22:56:19 +00006162 // We may be able to offer a FixItHint if it is a supported type.
6163 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006164 bool success =
6165 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006166
Jordan Rose22b74712012-09-05 22:56:19 +00006167 if (success) {
6168 // Get the fix string from the fixed format specifier
6169 SmallString<16> buf;
6170 llvm::raw_svector_ostream os(buf);
6171 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006172
Jordan Roseaee34382012-09-05 22:56:26 +00006173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6174
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006175 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006176 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6177 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6178 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6179 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006180 // In this case, the specifier is wrong and should be changed to match
6181 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006182 EmitFormatDiagnostic(S.PDiag(diag)
6183 << AT.getRepresentativeTypeName(S.Context)
6184 << IntendedTy << IsEnum << E->getSourceRange(),
6185 E->getLocStart(),
6186 /*IsStringLocation*/ false, SpecRange,
6187 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006188 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006189 // The canonical type for formatting this value is different from the
6190 // actual type of the expression. (This occurs, for example, with Darwin's
6191 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6192 // should be printed as 'long' for 64-bit compatibility.)
6193 // Rather than emitting a normal format/argument mismatch, we want to
6194 // add a cast to the recommended type (and correct the format string
6195 // if necessary).
6196 SmallString<16> CastBuf;
6197 llvm::raw_svector_ostream CastFix(CastBuf);
6198 CastFix << "(";
6199 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6200 CastFix << ")";
6201
6202 SmallVector<FixItHint,4> Hints;
6203 if (!AT.matchesType(S.Context, IntendedTy))
6204 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6205
6206 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6207 // If there's already a cast present, just replace it.
6208 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6209 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6210
6211 } else if (!requiresParensToAddCast(E)) {
6212 // If the expression has high enough precedence,
6213 // just write the C-style cast.
6214 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6215 CastFix.str()));
6216 } else {
6217 // Otherwise, add parens around the expression as well as the cast.
6218 CastFix << "(";
6219 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6220 CastFix.str()));
6221
Alp Tokerb6cc5922014-05-03 03:45:55 +00006222 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006223 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6224 }
6225
Jordan Rose0e5badd2012-12-05 18:44:49 +00006226 if (ShouldNotPrintDirectly) {
6227 // The expression has a type that should not be printed directly.
6228 // We extract the name from the typedef because we don't want to show
6229 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006230 StringRef Name;
6231 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6232 Name = TypedefTy->getDecl()->getName();
6233 else
6234 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006236 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006237 << E->getSourceRange(),
6238 E->getLocStart(), /*IsStringLocation=*/false,
6239 SpecRange, Hints);
6240 } else {
6241 // In this case, the expression could be printed using a different
6242 // specifier, but we've decided that the specifier is probably correct
6243 // and we should cast instead. Just use the normal warning message.
6244 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006245 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6246 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006247 << E->getSourceRange(),
6248 E->getLocStart(), /*IsStringLocation*/false,
6249 SpecRange, Hints);
6250 }
Jordan Roseaee34382012-09-05 22:56:26 +00006251 }
Jordan Rose22b74712012-09-05 22:56:19 +00006252 } else {
6253 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6254 SpecifierLen);
6255 // Since the warning for passing non-POD types to variadic functions
6256 // was deferred until now, we emit a warning for non-POD
6257 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006258 switch (S.isValidVarArgType(ExprTy)) {
6259 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006260 case Sema::VAK_ValidInCXX11: {
6261 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6262 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6263 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6264 }
Richard Smithd7293d72013-08-05 18:49:43 +00006265
Seth Cantrellb4802962015-03-04 03:12:10 +00006266 EmitFormatDiagnostic(
6267 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6268 << IsEnum << CSR << E->getSourceRange(),
6269 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6270 break;
6271 }
Richard Smithd7293d72013-08-05 18:49:43 +00006272 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006273 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006274 EmitFormatDiagnostic(
6275 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006276 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006277 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006278 << CallType
6279 << AT.getRepresentativeTypeName(S.Context)
6280 << CSR
6281 << E->getSourceRange(),
6282 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006283 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006284 break;
6285
6286 case Sema::VAK_Invalid:
6287 if (ExprTy->isObjCObjectType())
6288 EmitFormatDiagnostic(
6289 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6290 << S.getLangOpts().CPlusPlus11
6291 << ExprTy
6292 << CallType
6293 << AT.getRepresentativeTypeName(S.Context)
6294 << CSR
6295 << E->getSourceRange(),
6296 E->getLocStart(), /*IsStringLocation*/false, CSR);
6297 else
6298 // FIXME: If this is an initializer list, suggest removing the braces
6299 // or inserting a cast to the target type.
6300 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6301 << isa<InitListExpr>(E) << ExprTy << CallType
6302 << AT.getRepresentativeTypeName(S.Context)
6303 << E->getSourceRange();
6304 break;
6305 }
6306
6307 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6308 "format string specifier index out of range");
6309 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006310 }
6311
Ted Kremenekab278de2010-01-28 23:39:18 +00006312 return true;
6313}
6314
Ted Kremenek02087932010-07-16 02:11:22 +00006315//===--- CHECK: Scanf format string checking ------------------------------===//
6316
6317namespace {
6318class CheckScanfHandler : public CheckFormatHandler {
6319public:
Stephen Hines648c3692016-09-16 01:07:04 +00006320 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006321 const Expr *origFormatExpr, Sema::FormatStringType type,
6322 unsigned firstDataArg, unsigned numDataArgs,
6323 const char *beg, bool hasVAListArg,
6324 ArrayRef<const Expr *> Args, unsigned formatIdx,
6325 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006326 llvm::SmallBitVector &CheckedVarArgs,
6327 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006328 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6329 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6330 inFunctionCall, CallType, CheckedVarArgs,
6331 UncoveredArg) {}
6332
Ted Kremenek02087932010-07-16 02:11:22 +00006333 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6334 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006335 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006336
6337 bool HandleInvalidScanfConversionSpecifier(
6338 const analyze_scanf::ScanfSpecifier &FS,
6339 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006340 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006341
Craig Toppere14c0f82014-03-12 04:55:44 +00006342 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006343};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006344} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006345
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006346void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6347 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006348 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6349 getLocationOfByte(end), /*IsStringLocation*/true,
6350 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006351}
6352
Ted Kremenekce815422010-07-19 21:25:57 +00006353bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6354 const analyze_scanf::ScanfSpecifier &FS,
6355 const char *startSpecifier,
6356 unsigned specifierLen) {
6357
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006358 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006359 FS.getConversionSpecifier();
6360
6361 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6362 getLocationOfByte(CS.getStart()),
6363 startSpecifier, specifierLen,
6364 CS.getStart(), CS.getLength());
6365}
6366
Ted Kremenek02087932010-07-16 02:11:22 +00006367bool CheckScanfHandler::HandleScanfSpecifier(
6368 const analyze_scanf::ScanfSpecifier &FS,
6369 const char *startSpecifier,
6370 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006371 using namespace analyze_scanf;
6372 using namespace analyze_format_string;
6373
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006374 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006375
Ted Kremenek6cd69422010-07-19 22:01:06 +00006376 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6377 // be used to decide if we are using positional arguments consistently.
6378 if (FS.consumesDataArgument()) {
6379 if (atFirstArg) {
6380 atFirstArg = false;
6381 usesPositionalArgs = FS.usesPositionalArg();
6382 }
6383 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006384 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6385 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006386 return false;
6387 }
Ted Kremenek02087932010-07-16 02:11:22 +00006388 }
6389
6390 // Check if the field with is non-zero.
6391 const OptionalAmount &Amt = FS.getFieldWidth();
6392 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6393 if (Amt.getConstantAmount() == 0) {
6394 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6395 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006396 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6397 getLocationOfByte(Amt.getStart()),
6398 /*IsStringLocation*/true, R,
6399 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006400 }
6401 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006402
Ted Kremenek02087932010-07-16 02:11:22 +00006403 if (!FS.consumesDataArgument()) {
6404 // FIXME: Technically specifying a precision or field width here
6405 // makes no sense. Worth issuing a warning at some point.
6406 return true;
6407 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006408
Ted Kremenek02087932010-07-16 02:11:22 +00006409 // Consume the argument.
6410 unsigned argIndex = FS.getArgIndex();
6411 if (argIndex < NumDataArgs) {
6412 // The check to see if the argIndex is valid will come later.
6413 // We set the bit here because we may exit early from this
6414 // function if we encounter some other error.
6415 CoveredArgs.set(argIndex);
6416 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006417
Ted Kremenek4407ea42010-07-20 20:04:47 +00006418 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006419 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006420 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6421 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006422 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006423 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006424 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6426 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006427
Jordan Rose92303592012-09-08 04:00:03 +00006428 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6429 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6430
Ted Kremenek02087932010-07-16 02:11:22 +00006431 // The remaining checks depend on the data arguments.
6432 if (HasVAListArg)
6433 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006434
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006435 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006436 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006437
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006438 // Check that the argument type matches the format specifier.
6439 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006440 if (!Ex)
6441 return true;
6442
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006443 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006444
6445 if (!AT.isValid()) {
6446 return true;
6447 }
6448
Seth Cantrellb4802962015-03-04 03:12:10 +00006449 analyze_format_string::ArgType::MatchKind match =
6450 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006451 if (match == analyze_format_string::ArgType::Match) {
6452 return true;
6453 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006454
Seth Cantrell79340072015-03-04 05:58:08 +00006455 ScanfSpecifier fixedFS = FS;
6456 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6457 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006458
Seth Cantrell79340072015-03-04 05:58:08 +00006459 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6460 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6461 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6462 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006463
Seth Cantrell79340072015-03-04 05:58:08 +00006464 if (success) {
6465 // Get the fix string from the fixed format specifier.
6466 SmallString<128> buf;
6467 llvm::raw_svector_ostream os(buf);
6468 fixedFS.toString(os);
6469
6470 EmitFormatDiagnostic(
6471 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6472 << Ex->getType() << false << Ex->getSourceRange(),
6473 Ex->getLocStart(),
6474 /*IsStringLocation*/ false,
6475 getSpecifierRange(startSpecifier, specifierLen),
6476 FixItHint::CreateReplacement(
6477 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6478 } else {
6479 EmitFormatDiagnostic(S.PDiag(diag)
6480 << AT.getRepresentativeTypeName(S.Context)
6481 << Ex->getType() << false << Ex->getSourceRange(),
6482 Ex->getLocStart(),
6483 /*IsStringLocation*/ false,
6484 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006485 }
6486
Ted Kremenek02087932010-07-16 02:11:22 +00006487 return true;
6488}
6489
Stephen Hines648c3692016-09-16 01:07:04 +00006490static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006491 const Expr *OrigFormatExpr,
6492 ArrayRef<const Expr *> Args,
6493 bool HasVAListArg, unsigned format_idx,
6494 unsigned firstDataArg,
6495 Sema::FormatStringType Type,
6496 bool inFunctionCall,
6497 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006498 llvm::SmallBitVector &CheckedVarArgs,
6499 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006500 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006501 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006502 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006503 S, inFunctionCall, Args[format_idx],
6504 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006505 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006506 return;
6507 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006508
Ted Kremenekab278de2010-01-28 23:39:18 +00006509 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006510 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006511 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006512 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006513 const ConstantArrayType *T =
6514 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006515 assert(T && "String literal not of constant array type!");
6516 size_t TypeSize = T->getSize().getZExtValue();
6517 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006518 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006519
6520 // Emit a warning if the string literal is truncated and does not contain an
6521 // embedded null character.
6522 if (TypeSize <= StrRef.size() &&
6523 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6524 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006525 S, inFunctionCall, Args[format_idx],
6526 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006527 FExpr->getLocStart(),
6528 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6529 return;
6530 }
6531
Ted Kremenekab278de2010-01-28 23:39:18 +00006532 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006533 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006534 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006535 S, inFunctionCall, Args[format_idx],
6536 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006537 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006538 return;
6539 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006540
6541 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006542 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6543 Type == Sema::FST_OSTrace) {
6544 CheckPrintfHandler H(
6545 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6546 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6547 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6548 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006549
Hans Wennborg23926bd2011-12-15 10:25:47 +00006550 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006551 S.getLangOpts(),
6552 S.Context.getTargetInfo(),
6553 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006554 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006555 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006556 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6557 numDataArgs, Str, HasVAListArg, Args, format_idx,
6558 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006559
Hans Wennborg23926bd2011-12-15 10:25:47 +00006560 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006561 S.getLangOpts(),
6562 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006563 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006564 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006565}
6566
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006567bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6568 // Str - The format string. NOTE: this is NOT null-terminated!
6569 StringRef StrRef = FExpr->getString();
6570 const char *Str = StrRef.data();
6571 // Account for cases where the string literal is truncated in a declaration.
6572 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6573 assert(T && "String literal not of constant array type!");
6574 size_t TypeSize = T->getSize().getZExtValue();
6575 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6576 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6577 getLangOpts(),
6578 Context.getTargetInfo());
6579}
6580
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006581//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6582
6583// Returns the related absolute value function that is larger, of 0 if one
6584// does not exist.
6585static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6586 switch (AbsFunction) {
6587 default:
6588 return 0;
6589
6590 case Builtin::BI__builtin_abs:
6591 return Builtin::BI__builtin_labs;
6592 case Builtin::BI__builtin_labs:
6593 return Builtin::BI__builtin_llabs;
6594 case Builtin::BI__builtin_llabs:
6595 return 0;
6596
6597 case Builtin::BI__builtin_fabsf:
6598 return Builtin::BI__builtin_fabs;
6599 case Builtin::BI__builtin_fabs:
6600 return Builtin::BI__builtin_fabsl;
6601 case Builtin::BI__builtin_fabsl:
6602 return 0;
6603
6604 case Builtin::BI__builtin_cabsf:
6605 return Builtin::BI__builtin_cabs;
6606 case Builtin::BI__builtin_cabs:
6607 return Builtin::BI__builtin_cabsl;
6608 case Builtin::BI__builtin_cabsl:
6609 return 0;
6610
6611 case Builtin::BIabs:
6612 return Builtin::BIlabs;
6613 case Builtin::BIlabs:
6614 return Builtin::BIllabs;
6615 case Builtin::BIllabs:
6616 return 0;
6617
6618 case Builtin::BIfabsf:
6619 return Builtin::BIfabs;
6620 case Builtin::BIfabs:
6621 return Builtin::BIfabsl;
6622 case Builtin::BIfabsl:
6623 return 0;
6624
6625 case Builtin::BIcabsf:
6626 return Builtin::BIcabs;
6627 case Builtin::BIcabs:
6628 return Builtin::BIcabsl;
6629 case Builtin::BIcabsl:
6630 return 0;
6631 }
6632}
6633
6634// Returns the argument type of the absolute value function.
6635static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6636 unsigned AbsType) {
6637 if (AbsType == 0)
6638 return QualType();
6639
6640 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6641 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6642 if (Error != ASTContext::GE_None)
6643 return QualType();
6644
6645 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6646 if (!FT)
6647 return QualType();
6648
6649 if (FT->getNumParams() != 1)
6650 return QualType();
6651
6652 return FT->getParamType(0);
6653}
6654
6655// Returns the best absolute value function, or zero, based on type and
6656// current absolute value function.
6657static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6658 unsigned AbsFunctionKind) {
6659 unsigned BestKind = 0;
6660 uint64_t ArgSize = Context.getTypeSize(ArgType);
6661 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6662 Kind = getLargerAbsoluteValueFunction(Kind)) {
6663 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6664 if (Context.getTypeSize(ParamType) >= ArgSize) {
6665 if (BestKind == 0)
6666 BestKind = Kind;
6667 else if (Context.hasSameType(ParamType, ArgType)) {
6668 BestKind = Kind;
6669 break;
6670 }
6671 }
6672 }
6673 return BestKind;
6674}
6675
6676enum AbsoluteValueKind {
6677 AVK_Integer,
6678 AVK_Floating,
6679 AVK_Complex
6680};
6681
6682static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6683 if (T->isIntegralOrEnumerationType())
6684 return AVK_Integer;
6685 if (T->isRealFloatingType())
6686 return AVK_Floating;
6687 if (T->isAnyComplexType())
6688 return AVK_Complex;
6689
6690 llvm_unreachable("Type not integer, floating, or complex");
6691}
6692
6693// Changes the absolute value function to a different type. Preserves whether
6694// the function is a builtin.
6695static unsigned changeAbsFunction(unsigned AbsKind,
6696 AbsoluteValueKind ValueKind) {
6697 switch (ValueKind) {
6698 case AVK_Integer:
6699 switch (AbsKind) {
6700 default:
6701 return 0;
6702 case Builtin::BI__builtin_fabsf:
6703 case Builtin::BI__builtin_fabs:
6704 case Builtin::BI__builtin_fabsl:
6705 case Builtin::BI__builtin_cabsf:
6706 case Builtin::BI__builtin_cabs:
6707 case Builtin::BI__builtin_cabsl:
6708 return Builtin::BI__builtin_abs;
6709 case Builtin::BIfabsf:
6710 case Builtin::BIfabs:
6711 case Builtin::BIfabsl:
6712 case Builtin::BIcabsf:
6713 case Builtin::BIcabs:
6714 case Builtin::BIcabsl:
6715 return Builtin::BIabs;
6716 }
6717 case AVK_Floating:
6718 switch (AbsKind) {
6719 default:
6720 return 0;
6721 case Builtin::BI__builtin_abs:
6722 case Builtin::BI__builtin_labs:
6723 case Builtin::BI__builtin_llabs:
6724 case Builtin::BI__builtin_cabsf:
6725 case Builtin::BI__builtin_cabs:
6726 case Builtin::BI__builtin_cabsl:
6727 return Builtin::BI__builtin_fabsf;
6728 case Builtin::BIabs:
6729 case Builtin::BIlabs:
6730 case Builtin::BIllabs:
6731 case Builtin::BIcabsf:
6732 case Builtin::BIcabs:
6733 case Builtin::BIcabsl:
6734 return Builtin::BIfabsf;
6735 }
6736 case AVK_Complex:
6737 switch (AbsKind) {
6738 default:
6739 return 0;
6740 case Builtin::BI__builtin_abs:
6741 case Builtin::BI__builtin_labs:
6742 case Builtin::BI__builtin_llabs:
6743 case Builtin::BI__builtin_fabsf:
6744 case Builtin::BI__builtin_fabs:
6745 case Builtin::BI__builtin_fabsl:
6746 return Builtin::BI__builtin_cabsf;
6747 case Builtin::BIabs:
6748 case Builtin::BIlabs:
6749 case Builtin::BIllabs:
6750 case Builtin::BIfabsf:
6751 case Builtin::BIfabs:
6752 case Builtin::BIfabsl:
6753 return Builtin::BIcabsf;
6754 }
6755 }
6756 llvm_unreachable("Unable to convert function");
6757}
6758
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006759static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006760 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6761 if (!FnInfo)
6762 return 0;
6763
6764 switch (FDecl->getBuiltinID()) {
6765 default:
6766 return 0;
6767 case Builtin::BI__builtin_abs:
6768 case Builtin::BI__builtin_fabs:
6769 case Builtin::BI__builtin_fabsf:
6770 case Builtin::BI__builtin_fabsl:
6771 case Builtin::BI__builtin_labs:
6772 case Builtin::BI__builtin_llabs:
6773 case Builtin::BI__builtin_cabs:
6774 case Builtin::BI__builtin_cabsf:
6775 case Builtin::BI__builtin_cabsl:
6776 case Builtin::BIabs:
6777 case Builtin::BIlabs:
6778 case Builtin::BIllabs:
6779 case Builtin::BIfabs:
6780 case Builtin::BIfabsf:
6781 case Builtin::BIfabsl:
6782 case Builtin::BIcabs:
6783 case Builtin::BIcabsf:
6784 case Builtin::BIcabsl:
6785 return FDecl->getBuiltinID();
6786 }
6787 llvm_unreachable("Unknown Builtin type");
6788}
6789
6790// If the replacement is valid, emit a note with replacement function.
6791// Additionally, suggest including the proper header if not already included.
6792static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006793 unsigned AbsKind, QualType ArgType) {
6794 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006795 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006796 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006797 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6798 FunctionName = "std::abs";
6799 if (ArgType->isIntegralOrEnumerationType()) {
6800 HeaderName = "cstdlib";
6801 } else if (ArgType->isRealFloatingType()) {
6802 HeaderName = "cmath";
6803 } else {
6804 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006805 }
Richard Trieubeffb832014-04-15 23:47:53 +00006806
6807 // Lookup all std::abs
6808 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006809 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006810 R.suppressDiagnostics();
6811 S.LookupQualifiedName(R, Std);
6812
6813 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006814 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006815 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6816 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6817 } else {
6818 FDecl = dyn_cast<FunctionDecl>(I);
6819 }
6820 if (!FDecl)
6821 continue;
6822
6823 // Found std::abs(), check that they are the right ones.
6824 if (FDecl->getNumParams() != 1)
6825 continue;
6826
6827 // Check that the parameter type can handle the argument.
6828 QualType ParamType = FDecl->getParamDecl(0)->getType();
6829 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6830 S.Context.getTypeSize(ArgType) <=
6831 S.Context.getTypeSize(ParamType)) {
6832 // Found a function, don't need the header hint.
6833 EmitHeaderHint = false;
6834 break;
6835 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006836 }
Richard Trieubeffb832014-04-15 23:47:53 +00006837 }
6838 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006839 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006840 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6841
6842 if (HeaderName) {
6843 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6844 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6845 R.suppressDiagnostics();
6846 S.LookupName(R, S.getCurScope());
6847
6848 if (R.isSingleResult()) {
6849 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6850 if (FD && FD->getBuiltinID() == AbsKind) {
6851 EmitHeaderHint = false;
6852 } else {
6853 return;
6854 }
6855 } else if (!R.empty()) {
6856 return;
6857 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006858 }
6859 }
6860
6861 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006862 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006863
Richard Trieubeffb832014-04-15 23:47:53 +00006864 if (!HeaderName)
6865 return;
6866
6867 if (!EmitHeaderHint)
6868 return;
6869
Alp Toker5d96e0a2014-07-11 20:53:51 +00006870 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6871 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006872}
6873
Richard Trieua7f30b12016-12-06 01:42:28 +00006874template <std::size_t StrLen>
6875static bool IsStdFunction(const FunctionDecl *FDecl,
6876 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006877 if (!FDecl)
6878 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006879 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006880 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006881 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006882 return false;
6883
6884 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006885}
6886
6887// Warn when using the wrong abs() function.
6888void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006889 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006890 if (Call->getNumArgs() != 1)
6891 return;
6892
6893 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006894 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006895 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006896 return;
6897
6898 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6899 QualType ParamType = Call->getArg(0)->getType();
6900
Alp Toker5d96e0a2014-07-11 20:53:51 +00006901 // Unsigned types cannot be negative. Suggest removing the absolute value
6902 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006903 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006904 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006905 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006906 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6907 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006908 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006909 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6910 return;
6911 }
6912
David Majnemer7f77eb92015-11-15 03:04:34 +00006913 // Taking the absolute value of a pointer is very suspicious, they probably
6914 // wanted to index into an array, dereference a pointer, call a function, etc.
6915 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6916 unsigned DiagType = 0;
6917 if (ArgType->isFunctionType())
6918 DiagType = 1;
6919 else if (ArgType->isArrayType())
6920 DiagType = 2;
6921
6922 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6923 return;
6924 }
6925
Richard Trieubeffb832014-04-15 23:47:53 +00006926 // std::abs has overloads which prevent most of the absolute value problems
6927 // from occurring.
6928 if (IsStdAbs)
6929 return;
6930
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006931 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6932 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6933
6934 // The argument and parameter are the same kind. Check if they are the right
6935 // size.
6936 if (ArgValueKind == ParamValueKind) {
6937 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6938 return;
6939
6940 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6941 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6942 << FDecl << ArgType << ParamType;
6943
6944 if (NewAbsKind == 0)
6945 return;
6946
6947 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006948 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006949 return;
6950 }
6951
6952 // ArgValueKind != ParamValueKind
6953 // The wrong type of absolute value function was used. Attempt to find the
6954 // proper one.
6955 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6956 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6957 if (NewAbsKind == 0)
6958 return;
6959
6960 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6961 << FDecl << ParamValueKind << ArgValueKind;
6962
6963 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006964 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006965}
6966
Richard Trieu67c00712016-12-05 23:41:46 +00006967//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006968void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6969 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006970 if (!Call || !FDecl) return;
6971
6972 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006973 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006974 if (Call->getExprLoc().isMacroID()) return;
6975
6976 // Only care about the one template argument, two function parameter std::max
6977 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006978 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006979 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6980 if (!ArgList) return;
6981 if (ArgList->size() != 1) return;
6982
6983 // Check that template type argument is unsigned integer.
6984 const auto& TA = ArgList->get(0);
6985 if (TA.getKind() != TemplateArgument::Type) return;
6986 QualType ArgType = TA.getAsType();
6987 if (!ArgType->isUnsignedIntegerType()) return;
6988
6989 // See if either argument is a literal zero.
6990 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6991 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6992 if (!MTE) return false;
6993 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6994 if (!Num) return false;
6995 if (Num->getValue() != 0) return false;
6996 return true;
6997 };
6998
6999 const Expr *FirstArg = Call->getArg(0);
7000 const Expr *SecondArg = Call->getArg(1);
7001 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7002 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7003
7004 // Only warn when exactly one argument is zero.
7005 if (IsFirstArgZero == IsSecondArgZero) return;
7006
7007 SourceRange FirstRange = FirstArg->getSourceRange();
7008 SourceRange SecondRange = SecondArg->getSourceRange();
7009
7010 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7011
7012 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7013 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7014
7015 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7016 SourceRange RemovalRange;
7017 if (IsFirstArgZero) {
7018 RemovalRange = SourceRange(FirstRange.getBegin(),
7019 SecondRange.getBegin().getLocWithOffset(-1));
7020 } else {
7021 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7022 SecondRange.getEnd());
7023 }
7024
7025 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7026 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7027 << FixItHint::CreateRemoval(RemovalRange);
7028}
7029
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007030//===--- CHECK: Standard memory functions ---------------------------------===//
7031
Nico Weber0e6daef2013-12-26 23:38:39 +00007032/// \brief Takes the expression passed to the size_t parameter of functions
7033/// such as memcmp, strncat, etc and warns if it's a comparison.
7034///
7035/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7036static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7037 IdentifierInfo *FnName,
7038 SourceLocation FnLoc,
7039 SourceLocation RParenLoc) {
7040 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7041 if (!Size)
7042 return false;
7043
7044 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7045 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7046 return false;
7047
Nico Weber0e6daef2013-12-26 23:38:39 +00007048 SourceRange SizeRange = Size->getSourceRange();
7049 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7050 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007051 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007052 << FnName << FixItHint::CreateInsertion(
7053 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007054 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007055 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007056 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007057 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7058 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007059
7060 return true;
7061}
7062
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007063/// \brief Determine whether the given type is or contains a dynamic class type
7064/// (e.g., whether it has a vtable).
7065static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7066 bool &IsContained) {
7067 // Look through array types while ignoring qualifiers.
7068 const Type *Ty = T->getBaseElementTypeUnsafe();
7069 IsContained = false;
7070
7071 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7072 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007073 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007074 return nullptr;
7075
7076 if (RD->isDynamicClass())
7077 return RD;
7078
7079 // Check all the fields. If any bases were dynamic, the class is dynamic.
7080 // It's impossible for a class to transitively contain itself by value, so
7081 // infinite recursion is impossible.
7082 for (auto *FD : RD->fields()) {
7083 bool SubContained;
7084 if (const CXXRecordDecl *ContainedRD =
7085 getContainedDynamicClass(FD->getType(), SubContained)) {
7086 IsContained = true;
7087 return ContainedRD;
7088 }
7089 }
7090
7091 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007092}
7093
Chandler Carruth889ed862011-06-21 23:04:20 +00007094/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007095/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007096static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007097 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007098 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7099 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7100 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007101
Craig Topperc3ec1492014-05-26 06:22:03 +00007102 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007103}
7104
Chandler Carruth889ed862011-06-21 23:04:20 +00007105/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007106static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007107 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7108 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7109 if (SizeOf->getKind() == clang::UETT_SizeOf)
7110 return SizeOf->getTypeOfArgument();
7111
7112 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007113}
7114
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007115/// \brief Check for dangerous or invalid arguments to memset().
7116///
Chandler Carruthac687262011-06-03 06:23:57 +00007117/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007118/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7119/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007120///
7121/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007122void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007123 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007124 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007125 assert(BId != 0);
7126
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007127 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007128 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007129 unsigned ExpectedNumArgs =
7130 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007131 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007132 return;
7133
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007134 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007135 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007136 unsigned LenArg =
7137 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007138 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007139
Nico Weber0e6daef2013-12-26 23:38:39 +00007140 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7141 Call->getLocStart(), Call->getRParenLoc()))
7142 return;
7143
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007144 // We have special checking when the length is a sizeof expression.
7145 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7146 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7147 llvm::FoldingSetNodeID SizeOfArgID;
7148
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007149 // Although widely used, 'bzero' is not a standard function. Be more strict
7150 // with the argument types before allowing diagnostics and only allow the
7151 // form bzero(ptr, sizeof(...)).
7152 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7153 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7154 return;
7155
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007156 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7157 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007158 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007159
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007160 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007161 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007162 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007163 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007164
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007165 // Never warn about void type pointers. This can be used to suppress
7166 // false positives.
7167 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007168 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007169
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007170 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7171 // actually comparing the expressions for equality. Because computing the
7172 // expression IDs can be expensive, we only do this if the diagnostic is
7173 // enabled.
7174 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007175 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7176 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007177 // We only compute IDs for expressions if the warning is enabled, and
7178 // cache the sizeof arg's ID.
7179 if (SizeOfArgID == llvm::FoldingSetNodeID())
7180 SizeOfArg->Profile(SizeOfArgID, Context, true);
7181 llvm::FoldingSetNodeID DestID;
7182 Dest->Profile(DestID, Context, true);
7183 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007184 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7185 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007186 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007187 StringRef ReadableName = FnName->getName();
7188
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007189 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007190 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007191 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007192 if (!PointeeTy->isIncompleteType() &&
7193 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007194 ActionIdx = 2; // If the pointee's size is sizeof(char),
7195 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007196
7197 // If the function is defined as a builtin macro, do not show macro
7198 // expansion.
7199 SourceLocation SL = SizeOfArg->getExprLoc();
7200 SourceRange DSR = Dest->getSourceRange();
7201 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007202 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007203
7204 if (SM.isMacroArgExpansion(SL)) {
7205 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7206 SL = SM.getSpellingLoc(SL);
7207 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7208 SM.getSpellingLoc(DSR.getEnd()));
7209 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7210 SM.getSpellingLoc(SSR.getEnd()));
7211 }
7212
Anna Zaksd08d9152012-05-30 23:14:52 +00007213 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007214 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007215 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007216 << PointeeTy
7217 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007218 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007219 << SSR);
7220 DiagRuntimeBehavior(SL, SizeOfArg,
7221 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7222 << ActionIdx
7223 << SSR);
7224
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007225 break;
7226 }
7227 }
7228
7229 // Also check for cases where the sizeof argument is the exact same
7230 // type as the memory argument, and where it points to a user-defined
7231 // record type.
7232 if (SizeOfArgTy != QualType()) {
7233 if (PointeeTy->isRecordType() &&
7234 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7235 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7236 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7237 << FnName << SizeOfArgTy << ArgIdx
7238 << PointeeTy << Dest->getSourceRange()
7239 << LenExpr->getSourceRange());
7240 break;
7241 }
Nico Weberc5e73862011-06-14 16:14:58 +00007242 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007243 } else if (DestTy->isArrayType()) {
7244 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007245 }
Nico Weberc5e73862011-06-14 16:14:58 +00007246
Nico Weberc44b35e2015-03-21 17:37:46 +00007247 if (PointeeTy == QualType())
7248 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007249
Nico Weberc44b35e2015-03-21 17:37:46 +00007250 // Always complain about dynamic classes.
7251 bool IsContained;
7252 if (const CXXRecordDecl *ContainedRD =
7253 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007254
Nico Weberc44b35e2015-03-21 17:37:46 +00007255 unsigned OperationType = 0;
7256 // "overwritten" if we're warning about the destination for any call
7257 // but memcmp; otherwise a verb appropriate to the call.
7258 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7259 if (BId == Builtin::BImemcpy)
7260 OperationType = 1;
7261 else if(BId == Builtin::BImemmove)
7262 OperationType = 2;
7263 else if (BId == Builtin::BImemcmp)
7264 OperationType = 3;
7265 }
7266
John McCall31168b02011-06-15 23:02:42 +00007267 DiagRuntimeBehavior(
7268 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007269 PDiag(diag::warn_dyn_class_memaccess)
7270 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7271 << FnName << IsContained << ContainedRD << OperationType
7272 << Call->getCallee()->getSourceRange());
7273 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7274 BId != Builtin::BImemset)
7275 DiagRuntimeBehavior(
7276 Dest->getExprLoc(), Dest,
7277 PDiag(diag::warn_arc_object_memaccess)
7278 << ArgIdx << FnName << PointeeTy
7279 << Call->getCallee()->getSourceRange());
7280 else
7281 continue;
7282
7283 DiagRuntimeBehavior(
7284 Dest->getExprLoc(), Dest,
7285 PDiag(diag::note_bad_memaccess_silence)
7286 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7287 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007288 }
7289}
7290
Ted Kremenek6865f772011-08-18 20:55:45 +00007291// A little helper routine: ignore addition and subtraction of integer literals.
7292// This intentionally does not ignore all integer constant expressions because
7293// we don't want to remove sizeof().
7294static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7295 Ex = Ex->IgnoreParenCasts();
7296
7297 for (;;) {
7298 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7299 if (!BO || !BO->isAdditiveOp())
7300 break;
7301
7302 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7303 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7304
7305 if (isa<IntegerLiteral>(RHS))
7306 Ex = LHS;
7307 else if (isa<IntegerLiteral>(LHS))
7308 Ex = RHS;
7309 else
7310 break;
7311 }
7312
7313 return Ex;
7314}
7315
Anna Zaks13b08572012-08-08 21:42:23 +00007316static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7317 ASTContext &Context) {
7318 // Only handle constant-sized or VLAs, but not flexible members.
7319 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7320 // Only issue the FIXIT for arrays of size > 1.
7321 if (CAT->getSize().getSExtValue() <= 1)
7322 return false;
7323 } else if (!Ty->isVariableArrayType()) {
7324 return false;
7325 }
7326 return true;
7327}
7328
Ted Kremenek6865f772011-08-18 20:55:45 +00007329// Warn if the user has made the 'size' argument to strlcpy or strlcat
7330// be the size of the source, instead of the destination.
7331void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7332 IdentifierInfo *FnName) {
7333
7334 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007335 unsigned NumArgs = Call->getNumArgs();
7336 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007337 return;
7338
7339 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7340 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007341 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007342
7343 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7344 Call->getLocStart(), Call->getRParenLoc()))
7345 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007346
7347 // Look for 'strlcpy(dst, x, sizeof(x))'
7348 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7349 CompareWithSrc = Ex;
7350 else {
7351 // Look for 'strlcpy(dst, x, strlen(x))'
7352 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007353 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7354 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007355 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7356 }
7357 }
7358
7359 if (!CompareWithSrc)
7360 return;
7361
7362 // Determine if the argument to sizeof/strlen is equal to the source
7363 // argument. In principle there's all kinds of things you could do
7364 // here, for instance creating an == expression and evaluating it with
7365 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7366 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7367 if (!SrcArgDRE)
7368 return;
7369
7370 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7371 if (!CompareWithSrcDRE ||
7372 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7373 return;
7374
7375 const Expr *OriginalSizeArg = Call->getArg(2);
7376 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7377 << OriginalSizeArg->getSourceRange() << FnName;
7378
7379 // Output a FIXIT hint if the destination is an array (rather than a
7380 // pointer to an array). This could be enhanced to handle some
7381 // pointers if we know the actual size, like if DstArg is 'array+2'
7382 // we could say 'sizeof(array)-2'.
7383 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007384 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007385 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007386
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007387 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007388 llvm::raw_svector_ostream OS(sizeString);
7389 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007390 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007391 OS << ")";
7392
7393 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7394 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7395 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007396}
7397
Anna Zaks314cd092012-02-01 19:08:57 +00007398/// Check if two expressions refer to the same declaration.
7399static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7400 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7401 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7402 return D1->getDecl() == D2->getDecl();
7403 return false;
7404}
7405
7406static const Expr *getStrlenExprArg(const Expr *E) {
7407 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7408 const FunctionDecl *FD = CE->getDirectCallee();
7409 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007410 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007411 return CE->getArg(0)->IgnoreParenCasts();
7412 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007413 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007414}
7415
7416// Warn on anti-patterns as the 'size' argument to strncat.
7417// The correct size argument should look like following:
7418// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7419void Sema::CheckStrncatArguments(const CallExpr *CE,
7420 IdentifierInfo *FnName) {
7421 // Don't crash if the user has the wrong number of arguments.
7422 if (CE->getNumArgs() < 3)
7423 return;
7424 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7425 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7426 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7427
Nico Weber0e6daef2013-12-26 23:38:39 +00007428 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7429 CE->getRParenLoc()))
7430 return;
7431
Anna Zaks314cd092012-02-01 19:08:57 +00007432 // Identify common expressions, which are wrongly used as the size argument
7433 // to strncat and may lead to buffer overflows.
7434 unsigned PatternType = 0;
7435 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7436 // - sizeof(dst)
7437 if (referToTheSameDecl(SizeOfArg, DstArg))
7438 PatternType = 1;
7439 // - sizeof(src)
7440 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7441 PatternType = 2;
7442 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7443 if (BE->getOpcode() == BO_Sub) {
7444 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7445 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7446 // - sizeof(dst) - strlen(dst)
7447 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7448 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7449 PatternType = 1;
7450 // - sizeof(src) - (anything)
7451 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7452 PatternType = 2;
7453 }
7454 }
7455
7456 if (PatternType == 0)
7457 return;
7458
Anna Zaks5069aa32012-02-03 01:27:37 +00007459 // Generate the diagnostic.
7460 SourceLocation SL = LenArg->getLocStart();
7461 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007462 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007463
7464 // If the function is defined as a builtin macro, do not show macro expansion.
7465 if (SM.isMacroArgExpansion(SL)) {
7466 SL = SM.getSpellingLoc(SL);
7467 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7468 SM.getSpellingLoc(SR.getEnd()));
7469 }
7470
Anna Zaks13b08572012-08-08 21:42:23 +00007471 // Check if the destination is an array (rather than a pointer to an array).
7472 QualType DstTy = DstArg->getType();
7473 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7474 Context);
7475 if (!isKnownSizeArray) {
7476 if (PatternType == 1)
7477 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7478 else
7479 Diag(SL, diag::warn_strncat_src_size) << SR;
7480 return;
7481 }
7482
Anna Zaks314cd092012-02-01 19:08:57 +00007483 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007484 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007485 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007486 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007487
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007488 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007489 llvm::raw_svector_ostream OS(sizeString);
7490 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007491 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007492 OS << ") - ";
7493 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007494 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007495 OS << ") - 1";
7496
Anna Zaks5069aa32012-02-03 01:27:37 +00007497 Diag(SL, diag::note_strncat_wrong_size)
7498 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007499}
7500
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007501//===--- CHECK: Return Address of Stack Variable --------------------------===//
7502
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007503static const Expr *EvalVal(const Expr *E,
7504 SmallVectorImpl<const DeclRefExpr *> &refVars,
7505 const Decl *ParentDecl);
7506static const Expr *EvalAddr(const Expr *E,
7507 SmallVectorImpl<const DeclRefExpr *> &refVars,
7508 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007509
7510/// CheckReturnStackAddr - Check if a return statement returns the address
7511/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007512static void
7513CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7514 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007515
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007516 const Expr *stackE = nullptr;
7517 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007518
7519 // Perform checking for returned stack addresses, local blocks,
7520 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007521 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007522 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007523 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007524 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007525 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007526 }
7527
Craig Topperc3ec1492014-05-26 06:22:03 +00007528 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007529 return; // Nothing suspicious was found.
7530
Simon Pilgrim750bde62017-03-31 11:00:53 +00007531 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007532 // of a parameter reference doesn't need a warning.
7533 for (auto *DRE : refVars)
7534 if (isa<ParmVarDecl>(DRE->getDecl()))
7535 return;
7536
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007537 SourceLocation diagLoc;
7538 SourceRange diagRange;
7539 if (refVars.empty()) {
7540 diagLoc = stackE->getLocStart();
7541 diagRange = stackE->getSourceRange();
7542 } else {
7543 // We followed through a reference variable. 'stackE' contains the
7544 // problematic expression but we will warn at the return statement pointing
7545 // at the reference variable. We will later display the "trail" of
7546 // reference variables using notes.
7547 diagLoc = refVars[0]->getLocStart();
7548 diagRange = refVars[0]->getSourceRange();
7549 }
7550
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007551 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7552 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007553 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007554 << DR->getDecl()->getDeclName() << diagRange;
7555 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007556 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007557 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007558 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007559 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007560 // If there is an LValue->RValue conversion, then the value of the
7561 // reference type is used, not the reference.
7562 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7563 if (ICE->getCastKind() == CK_LValueToRValue) {
7564 return;
7565 }
7566 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007567 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7568 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007569 }
7570
7571 // Display the "trail" of reference variables that we followed until we
7572 // found the problematic expression using notes.
7573 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007574 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007575 // If this var binds to another reference var, show the range of the next
7576 // var, otherwise the var binds to the problematic expression, in which case
7577 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007578 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7579 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007580 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7581 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007582 }
7583}
7584
7585/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7586/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007587/// to a location on the stack, a local block, an address of a label, or a
7588/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007589/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007590/// encounter a subexpression that (1) clearly does not lead to one of the
7591/// above problematic expressions (2) is something we cannot determine leads to
7592/// a problematic expression based on such local checking.
7593///
7594/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7595/// the expression that they point to. Such variables are added to the
7596/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007597///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007598/// EvalAddr processes expressions that are pointers that are used as
7599/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007600/// At the base case of the recursion is a check for the above problematic
7601/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007602///
7603/// This implementation handles:
7604///
7605/// * pointer-to-pointer casts
7606/// * implicit conversions from array references to pointers
7607/// * taking the address of fields
7608/// * arbitrary interplay between "&" and "*" operators
7609/// * pointer arithmetic from an address of a stack variable
7610/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007611static const Expr *EvalAddr(const Expr *E,
7612 SmallVectorImpl<const DeclRefExpr *> &refVars,
7613 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007614 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007615 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007616
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007617 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007618 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007619 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007620 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007621 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007622
Peter Collingbourne91147592011-04-15 00:35:48 +00007623 E = E->IgnoreParens();
7624
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007625 // Our "symbolic interpreter" is just a dispatch off the currently
7626 // viewed AST node. We then recursively traverse the AST by calling
7627 // EvalAddr and EvalVal appropriately.
7628 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007629 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007630 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007631
Richard Smith40f08eb2014-01-30 22:05:38 +00007632 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007633 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007634 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007635
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007636 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007637 // If this is a reference variable, follow through to the expression that
7638 // it points to.
7639 if (V->hasLocalStorage() &&
7640 V->getType()->isReferenceType() && V->hasInit()) {
7641 // Add the reference variable to the "trail".
7642 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007643 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007644 }
7645
Craig Topperc3ec1492014-05-26 06:22:03 +00007646 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007647 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007648
Chris Lattner934edb22007-12-28 05:31:15 +00007649 case Stmt::UnaryOperatorClass: {
7650 // The only unary operator that make sense to handle here
7651 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007652 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007653
John McCalle3027922010-08-25 11:45:40 +00007654 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007655 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007656 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007657 }
Mike Stump11289f42009-09-09 15:08:12 +00007658
Chris Lattner934edb22007-12-28 05:31:15 +00007659 case Stmt::BinaryOperatorClass: {
7660 // Handle pointer arithmetic. All other binary operators are not valid
7661 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007662 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007663 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007664
John McCalle3027922010-08-25 11:45:40 +00007665 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007666 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007667
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007668 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007669
7670 // Determine which argument is the real pointer base. It could be
7671 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007672 if (!Base->getType()->isPointerType())
7673 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007674
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007675 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007676 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007677 }
Steve Naroff2752a172008-09-10 19:17:48 +00007678
Chris Lattner934edb22007-12-28 05:31:15 +00007679 // For conditional operators we need to see if either the LHS or RHS are
7680 // valid DeclRefExpr*s. If one of them is valid, we return it.
7681 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007682 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007683
Chris Lattner934edb22007-12-28 05:31:15 +00007684 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007685 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007686 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007687 // In C++, we can have a throw-expression, which has 'void' type.
7688 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007689 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007690 return LHS;
7691 }
Chris Lattner934edb22007-12-28 05:31:15 +00007692
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007693 // In C++, we can have a throw-expression, which has 'void' type.
7694 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007695 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007696
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007697 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007698 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007699
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007700 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007701 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007702 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007703 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007704
7705 case Stmt::AddrLabelExprClass:
7706 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007707
John McCall28fc7092011-11-10 05:35:25 +00007708 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007709 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7710 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007711
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007712 // For casts, we need to handle conversions from arrays to
7713 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007714 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007715 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007716 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007717 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007718 case Stmt::CXXStaticCastExprClass:
7719 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007720 case Stmt::CXXConstCastExprClass:
7721 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007722 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007723 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007724 case CK_LValueToRValue:
7725 case CK_NoOp:
7726 case CK_BaseToDerived:
7727 case CK_DerivedToBase:
7728 case CK_UncheckedDerivedToBase:
7729 case CK_Dynamic:
7730 case CK_CPointerToObjCPointerCast:
7731 case CK_BlockPointerToObjCPointerCast:
7732 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007733 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007734
7735 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007736 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007737
Richard Trieudadefde2014-07-02 04:39:38 +00007738 case CK_BitCast:
7739 if (SubExpr->getType()->isAnyPointerType() ||
7740 SubExpr->getType()->isBlockPointerType() ||
7741 SubExpr->getType()->isObjCQualifiedIdType())
7742 return EvalAddr(SubExpr, refVars, ParentDecl);
7743 else
7744 return nullptr;
7745
Eli Friedman8195ad72012-02-23 23:04:32 +00007746 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007747 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007748 }
Chris Lattner934edb22007-12-28 05:31:15 +00007749 }
Mike Stump11289f42009-09-09 15:08:12 +00007750
Douglas Gregorfe314812011-06-21 17:03:29 +00007751 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007752 if (const Expr *Result =
7753 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7754 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007755 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007756 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007757
Chris Lattner934edb22007-12-28 05:31:15 +00007758 // Everything else: we simply don't reason about them.
7759 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007760 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007761 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007762}
Mike Stump11289f42009-09-09 15:08:12 +00007763
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007764/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7765/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007766static const Expr *EvalVal(const Expr *E,
7767 SmallVectorImpl<const DeclRefExpr *> &refVars,
7768 const Decl *ParentDecl) {
7769 do {
7770 // We should only be called for evaluating non-pointer expressions, or
7771 // expressions with a pointer type that are not used as references but
7772 // instead
7773 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007774
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007775 // Our "symbolic interpreter" is just a dispatch off the currently
7776 // viewed AST node. We then recursively traverse the AST by calling
7777 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007778
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007779 E = E->IgnoreParens();
7780 switch (E->getStmtClass()) {
7781 case Stmt::ImplicitCastExprClass: {
7782 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7783 if (IE->getValueKind() == VK_LValue) {
7784 E = IE->getSubExpr();
7785 continue;
7786 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007787 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007788 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007789
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007790 case Stmt::ExprWithCleanupsClass:
7791 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7792 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007793
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007794 case Stmt::DeclRefExprClass: {
7795 // When we hit a DeclRefExpr we are looking at code that refers to a
7796 // variable's name. If it's not a reference variable we check if it has
7797 // local storage within the function, and if so, return the expression.
7798 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7799
7800 // If we leave the immediate function, the lifetime isn't about to end.
7801 if (DR->refersToEnclosingVariableOrCapture())
7802 return nullptr;
7803
7804 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7805 // Check if it refers to itself, e.g. "int& i = i;".
7806 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007807 return DR;
7808
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007809 if (V->hasLocalStorage()) {
7810 if (!V->getType()->isReferenceType())
7811 return DR;
7812
7813 // Reference variable, follow through to the expression that
7814 // it points to.
7815 if (V->hasInit()) {
7816 // Add the reference variable to the "trail".
7817 refVars.push_back(DR);
7818 return EvalVal(V->getInit(), refVars, V);
7819 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007820 }
7821 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007822
7823 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007824 }
Mike Stump11289f42009-09-09 15:08:12 +00007825
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007826 case Stmt::UnaryOperatorClass: {
7827 // The only unary operator that make sense to handle here
7828 // is Deref. All others don't resolve to a "name." This includes
7829 // handling all sorts of rvalues passed to a unary operator.
7830 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007831
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007832 if (U->getOpcode() == UO_Deref)
7833 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007834
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007835 return nullptr;
7836 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007837
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007838 case Stmt::ArraySubscriptExprClass: {
7839 // Array subscripts are potential references to data on the stack. We
7840 // retrieve the DeclRefExpr* for the array variable if it indeed
7841 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007842 const auto *ASE = cast<ArraySubscriptExpr>(E);
7843 if (ASE->isTypeDependent())
7844 return nullptr;
7845 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007846 }
Mike Stump11289f42009-09-09 15:08:12 +00007847
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007848 case Stmt::OMPArraySectionExprClass: {
7849 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7850 ParentDecl);
7851 }
Mike Stump11289f42009-09-09 15:08:12 +00007852
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007853 case Stmt::ConditionalOperatorClass: {
7854 // For conditional operators we need to see if either the LHS or RHS are
7855 // non-NULL Expr's. If one is non-NULL, we return it.
7856 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007857
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007858 // Handle the GNU extension for missing LHS.
7859 if (const Expr *LHSExpr = C->getLHS()) {
7860 // In C++, we can have a throw-expression, which has 'void' type.
7861 if (!LHSExpr->getType()->isVoidType())
7862 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7863 return LHS;
7864 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007865
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007866 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007867 if (C->getRHS()->getType()->isVoidType())
7868 return nullptr;
7869
7870 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007871 }
7872
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007873 // Accesses to members are potential references to data on the stack.
7874 case Stmt::MemberExprClass: {
7875 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007876
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007877 // Check for indirect access. We only want direct field accesses.
7878 if (M->isArrow())
7879 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007880
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007881 // Check whether the member type is itself a reference, in which case
7882 // we're not going to refer to the member, but to what the member refers
7883 // to.
7884 if (M->getMemberDecl()->getType()->isReferenceType())
7885 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007886
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007887 return EvalVal(M->getBase(), refVars, ParentDecl);
7888 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007889
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007890 case Stmt::MaterializeTemporaryExprClass:
7891 if (const Expr *Result =
7892 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7893 refVars, ParentDecl))
7894 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007895 return E;
7896
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007897 default:
7898 // Check that we don't return or take the address of a reference to a
7899 // temporary. This is only useful in C++.
7900 if (!E->isTypeDependent() && E->isRValue())
7901 return E;
7902
7903 // Everything else: we simply don't reason about them.
7904 return nullptr;
7905 }
7906 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007907}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007908
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007909void
7910Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7911 SourceLocation ReturnLoc,
7912 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007913 const AttrVec *Attrs,
7914 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007915 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7916
7917 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007918 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7919 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007920 CheckNonNullExpr(*this, RetValExp))
7921 Diag(ReturnLoc, diag::warn_null_ret)
7922 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007923
7924 // C++11 [basic.stc.dynamic.allocation]p4:
7925 // If an allocation function declared with a non-throwing
7926 // exception-specification fails to allocate storage, it shall return
7927 // a null pointer. Any other allocation function that fails to allocate
7928 // storage shall indicate failure only by throwing an exception [...]
7929 if (FD) {
7930 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7931 if (Op == OO_New || Op == OO_Array_New) {
7932 const FunctionProtoType *Proto
7933 = FD->getType()->castAs<FunctionProtoType>();
7934 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7935 CheckNonNullExpr(*this, RetValExp))
7936 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7937 << FD << getLangOpts().CPlusPlus11;
7938 }
7939 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007940}
7941
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007942//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7943
7944/// Check for comparisons of floating point operands using != and ==.
7945/// Issue a warning if these are no self-comparisons, as they are not likely
7946/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007947void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007948 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7949 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007950
7951 // Special case: check for x == x (which is OK).
7952 // Do not emit warnings for such cases.
7953 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7954 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7955 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007956 return;
Mike Stump11289f42009-09-09 15:08:12 +00007957
Ted Kremenekeda40e22007-11-29 00:59:04 +00007958 // Special case: check for comparisons against literals that can be exactly
7959 // represented by APFloat. In such cases, do not emit a warning. This
7960 // is a heuristic: often comparison against such literals are used to
7961 // detect if a value in a variable has not changed. This clearly can
7962 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007963 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7964 if (FLL->isExact())
7965 return;
7966 } else
7967 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7968 if (FLR->isExact())
7969 return;
Mike Stump11289f42009-09-09 15:08:12 +00007970
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007971 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007972 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007973 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007974 return;
Mike Stump11289f42009-09-09 15:08:12 +00007975
David Blaikie1f4ff152012-07-16 20:47:22 +00007976 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007977 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007978 return;
Mike Stump11289f42009-09-09 15:08:12 +00007979
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007980 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007981 Diag(Loc, diag::warn_floatingpoint_eq)
7982 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007983}
John McCallca01b222010-01-04 23:21:16 +00007984
John McCall70aa5392010-01-06 05:24:50 +00007985//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7986//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007987
John McCall70aa5392010-01-06 05:24:50 +00007988namespace {
John McCallca01b222010-01-04 23:21:16 +00007989
John McCall70aa5392010-01-06 05:24:50 +00007990/// Structure recording the 'active' range of an integer-valued
7991/// expression.
7992struct IntRange {
7993 /// The number of bits active in the int.
7994 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007995
John McCall70aa5392010-01-06 05:24:50 +00007996 /// True if the int is known not to have negative values.
7997 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007998
John McCall70aa5392010-01-06 05:24:50 +00007999 IntRange(unsigned Width, bool NonNegative)
8000 : Width(Width), NonNegative(NonNegative)
8001 {}
John McCallca01b222010-01-04 23:21:16 +00008002
John McCall817d4af2010-11-10 23:38:19 +00008003 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008004 static IntRange forBoolType() {
8005 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008006 }
8007
John McCall817d4af2010-11-10 23:38:19 +00008008 /// Returns the range of an opaque value of the given integral type.
8009 static IntRange forValueOfType(ASTContext &C, QualType T) {
8010 return forValueOfCanonicalType(C,
8011 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008012 }
8013
John McCall817d4af2010-11-10 23:38:19 +00008014 /// Returns the range of an opaque value of a canonical integral type.
8015 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008016 assert(T->isCanonicalUnqualified());
8017
8018 if (const VectorType *VT = dyn_cast<VectorType>(T))
8019 T = VT->getElementType().getTypePtr();
8020 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8021 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008022 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8023 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008024
David Majnemer6a426652013-06-07 22:07:20 +00008025 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008026 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008027 EnumDecl *Enum = ET->getDecl();
8028 if (!Enum->isCompleteDefinition())
8029 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008030
David Majnemer6a426652013-06-07 22:07:20 +00008031 unsigned NumPositive = Enum->getNumPositiveBits();
8032 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008033
David Majnemer6a426652013-06-07 22:07:20 +00008034 if (NumNegative == 0)
8035 return IntRange(NumPositive, true/*NonNegative*/);
8036 else
8037 return IntRange(std::max(NumPositive + 1, NumNegative),
8038 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008039 }
John McCall70aa5392010-01-06 05:24:50 +00008040
8041 const BuiltinType *BT = cast<BuiltinType>(T);
8042 assert(BT->isInteger());
8043
8044 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8045 }
8046
John McCall817d4af2010-11-10 23:38:19 +00008047 /// Returns the "target" range of a canonical integral type, i.e.
8048 /// the range of values expressible in the type.
8049 ///
8050 /// This matches forValueOfCanonicalType except that enums have the
8051 /// full range of their type, not the range of their enumerators.
8052 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8053 assert(T->isCanonicalUnqualified());
8054
8055 if (const VectorType *VT = dyn_cast<VectorType>(T))
8056 T = VT->getElementType().getTypePtr();
8057 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8058 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008059 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8060 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008061 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008062 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008063
8064 const BuiltinType *BT = cast<BuiltinType>(T);
8065 assert(BT->isInteger());
8066
8067 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8068 }
8069
8070 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008071 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008072 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008073 L.NonNegative && R.NonNegative);
8074 }
8075
John McCall817d4af2010-11-10 23:38:19 +00008076 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008077 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008078 return IntRange(std::min(L.Width, R.Width),
8079 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008080 }
8081};
8082
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008083IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008084 if (value.isSigned() && value.isNegative())
8085 return IntRange(value.getMinSignedBits(), false);
8086
8087 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008088 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008089
8090 // isNonNegative() just checks the sign bit without considering
8091 // signedness.
8092 return IntRange(value.getActiveBits(), true);
8093}
8094
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008095IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8096 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008097 if (result.isInt())
8098 return GetValueRange(C, result.getInt(), MaxWidth);
8099
8100 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008101 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8102 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8103 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8104 R = IntRange::join(R, El);
8105 }
John McCall70aa5392010-01-06 05:24:50 +00008106 return R;
8107 }
8108
8109 if (result.isComplexInt()) {
8110 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8111 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8112 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008113 }
8114
8115 // This can happen with lossless casts to intptr_t of "based" lvalues.
8116 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008117 // FIXME: The only reason we need to pass the type in here is to get
8118 // the sign right on this one case. It would be nice if APValue
8119 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008120 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008121 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008122}
John McCall70aa5392010-01-06 05:24:50 +00008123
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008124QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008125 QualType Ty = E->getType();
8126 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8127 Ty = AtomicRHS->getValueType();
8128 return Ty;
8129}
8130
John McCall70aa5392010-01-06 05:24:50 +00008131/// Pseudo-evaluate the given integer expression, estimating the
8132/// range of values it might take.
8133///
8134/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008135IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008136 E = E->IgnoreParens();
8137
8138 // Try a full evaluation first.
8139 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008140 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008141 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008142
8143 // I think we only want to look through implicit casts here; if the
8144 // user has an explicit widening cast, we should treat the value as
8145 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008146 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008147 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008148 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8149
Eli Friedmane6d33952013-07-08 20:20:06 +00008150 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008151
George Burgess IVdf1ed002016-01-13 01:52:39 +00008152 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8153 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008154
John McCall70aa5392010-01-06 05:24:50 +00008155 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008156 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008157 return OutputTypeRange;
8158
8159 IntRange SubRange
8160 = GetExprRange(C, CE->getSubExpr(),
8161 std::min(MaxWidth, OutputTypeRange.Width));
8162
8163 // Bail out if the subexpr's range is as wide as the cast type.
8164 if (SubRange.Width >= OutputTypeRange.Width)
8165 return OutputTypeRange;
8166
8167 // Otherwise, we take the smaller width, and we're non-negative if
8168 // either the output type or the subexpr is.
8169 return IntRange(SubRange.Width,
8170 SubRange.NonNegative || OutputTypeRange.NonNegative);
8171 }
8172
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008173 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008174 // If we can fold the condition, just take that operand.
8175 bool CondResult;
8176 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8177 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8178 : CO->getFalseExpr(),
8179 MaxWidth);
8180
8181 // Otherwise, conservatively merge.
8182 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8183 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8184 return IntRange::join(L, R);
8185 }
8186
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008187 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008188 switch (BO->getOpcode()) {
8189
8190 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008191 case BO_LAnd:
8192 case BO_LOr:
8193 case BO_LT:
8194 case BO_GT:
8195 case BO_LE:
8196 case BO_GE:
8197 case BO_EQ:
8198 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008199 return IntRange::forBoolType();
8200
John McCallc3688382011-07-13 06:35:24 +00008201 // The type of the assignments is the type of the LHS, so the RHS
8202 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008203 case BO_MulAssign:
8204 case BO_DivAssign:
8205 case BO_RemAssign:
8206 case BO_AddAssign:
8207 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008208 case BO_XorAssign:
8209 case BO_OrAssign:
8210 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008211 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008212
John McCallc3688382011-07-13 06:35:24 +00008213 // Simple assignments just pass through the RHS, which will have
8214 // been coerced to the LHS type.
8215 case BO_Assign:
8216 // TODO: bitfields?
8217 return GetExprRange(C, BO->getRHS(), MaxWidth);
8218
John McCall70aa5392010-01-06 05:24:50 +00008219 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008220 case BO_PtrMemD:
8221 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008222 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008223
John McCall2ce81ad2010-01-06 22:07:33 +00008224 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008225 case BO_And:
8226 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008227 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8228 GetExprRange(C, BO->getRHS(), MaxWidth));
8229
John McCall70aa5392010-01-06 05:24:50 +00008230 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008231 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008232 // ...except that we want to treat '1 << (blah)' as logically
8233 // positive. It's an important idiom.
8234 if (IntegerLiteral *I
8235 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8236 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008237 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008238 return IntRange(R.Width, /*NonNegative*/ true);
8239 }
8240 }
8241 // fallthrough
8242
John McCalle3027922010-08-25 11:45:40 +00008243 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008244 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008245
John McCall2ce81ad2010-01-06 22:07:33 +00008246 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008247 case BO_Shr:
8248 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008249 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8250
8251 // If the shift amount is a positive constant, drop the width by
8252 // that much.
8253 llvm::APSInt shift;
8254 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8255 shift.isNonNegative()) {
8256 unsigned zext = shift.getZExtValue();
8257 if (zext >= L.Width)
8258 L.Width = (L.NonNegative ? 0 : 1);
8259 else
8260 L.Width -= zext;
8261 }
8262
8263 return L;
8264 }
8265
8266 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008267 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008268 return GetExprRange(C, BO->getRHS(), MaxWidth);
8269
John McCall2ce81ad2010-01-06 22:07:33 +00008270 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008271 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008272 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008273 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008274 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008275
John McCall51431812011-07-14 22:39:48 +00008276 // The width of a division result is mostly determined by the size
8277 // of the LHS.
8278 case BO_Div: {
8279 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008280 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008281 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8282
8283 // If the divisor is constant, use that.
8284 llvm::APSInt divisor;
8285 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8286 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8287 if (log2 >= L.Width)
8288 L.Width = (L.NonNegative ? 0 : 1);
8289 else
8290 L.Width = std::min(L.Width - log2, MaxWidth);
8291 return L;
8292 }
8293
8294 // Otherwise, just use the LHS's width.
8295 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8296 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8297 }
8298
8299 // The result of a remainder can't be larger than the result of
8300 // either side.
8301 case BO_Rem: {
8302 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008303 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008304 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8305 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8306
8307 IntRange meet = IntRange::meet(L, R);
8308 meet.Width = std::min(meet.Width, MaxWidth);
8309 return meet;
8310 }
8311
8312 // The default behavior is okay for these.
8313 case BO_Mul:
8314 case BO_Add:
8315 case BO_Xor:
8316 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008317 break;
8318 }
8319
John McCall51431812011-07-14 22:39:48 +00008320 // The default case is to treat the operation as if it were closed
8321 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008322 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8323 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8324 return IntRange::join(L, R);
8325 }
8326
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008327 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008328 switch (UO->getOpcode()) {
8329 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008330 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008331 return IntRange::forBoolType();
8332
8333 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008334 case UO_Deref:
8335 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008336 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008337
8338 default:
8339 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8340 }
8341 }
8342
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008343 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008344 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8345
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008346 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008347 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008348 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008349
Eli Friedmane6d33952013-07-08 20:20:06 +00008350 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008351}
John McCall263a48b2010-01-04 23:31:57 +00008352
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008353IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008354 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008355}
8356
John McCall263a48b2010-01-04 23:31:57 +00008357/// Checks whether the given value, which currently has the given
8358/// source semantics, has the same value when coerced through the
8359/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008360bool IsSameFloatAfterCast(const llvm::APFloat &value,
8361 const llvm::fltSemantics &Src,
8362 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008363 llvm::APFloat truncated = value;
8364
8365 bool ignored;
8366 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8367 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8368
8369 return truncated.bitwiseIsEqual(value);
8370}
8371
8372/// Checks whether the given value, which currently has the given
8373/// source semantics, has the same value when coerced through the
8374/// target semantics.
8375///
8376/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008377bool IsSameFloatAfterCast(const APValue &value,
8378 const llvm::fltSemantics &Src,
8379 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008380 if (value.isFloat())
8381 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8382
8383 if (value.isVector()) {
8384 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8385 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8386 return false;
8387 return true;
8388 }
8389
8390 assert(value.isComplexFloat());
8391 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8392 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8393}
8394
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008395void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008396
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008397bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008398 // Suppress cases where we are comparing against an enum constant.
8399 if (const DeclRefExpr *DR =
8400 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8401 if (isa<EnumConstantDecl>(DR->getDecl()))
8402 return false;
8403
8404 // Suppress cases where the '0' value is expanded from a macro.
8405 if (E->getLocStart().isMacroID())
8406 return false;
8407
John McCallcc7e5bf2010-05-06 08:58:33 +00008408 llvm::APSInt Value;
8409 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8410}
8411
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008412bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008413 // Strip off implicit integral promotions.
8414 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008415 if (ICE->getCastKind() != CK_IntegralCast &&
8416 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008417 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008418 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008419 }
8420
8421 return E->getType()->isEnumeralType();
8422}
8423
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008424void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008425 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008426 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008427 return;
8428
John McCalle3027922010-08-25 11:45:40 +00008429 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008430 if (E->isValueDependent())
8431 return;
8432
John McCalle3027922010-08-25 11:45:40 +00008433 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008434 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008435 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008436 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008437 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008438 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008439 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008440 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008441 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008442 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008443 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008444 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008445 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008446 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008447 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008448 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8449 }
8450}
8451
Benjamin Kramer7320b992016-06-15 14:20:56 +00008452void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8453 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008454 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008455 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008456 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008457 return;
8458
Richard Trieu0f097742014-04-04 04:13:47 +00008459 // TODO: Investigate using GetExprRange() to get tighter bounds
8460 // on the bit ranges.
8461 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008462 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008463 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008464 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8465 unsigned OtherWidth = OtherRange.Width;
8466
8467 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8468
Richard Trieu560910c2012-11-14 22:50:24 +00008469 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008470 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008471 return;
8472
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008473 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008474 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008475
Richard Trieu0f097742014-04-04 04:13:47 +00008476 // Used for diagnostic printout.
8477 enum {
8478 LiteralConstant = 0,
8479 CXXBoolLiteralTrue,
8480 CXXBoolLiteralFalse
8481 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008482
Richard Trieu0f097742014-04-04 04:13:47 +00008483 if (!OtherIsBooleanType) {
8484 QualType ConstantT = Constant->getType();
8485 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008486
Richard Trieu0f097742014-04-04 04:13:47 +00008487 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8488 return;
8489 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8490 "comparison with non-integer type");
8491
8492 bool ConstantSigned = ConstantT->isSignedIntegerType();
8493 bool CommonSigned = CommonT->isSignedIntegerType();
8494
8495 bool EqualityOnly = false;
8496
8497 if (CommonSigned) {
8498 // The common type is signed, therefore no signed to unsigned conversion.
8499 if (!OtherRange.NonNegative) {
8500 // Check that the constant is representable in type OtherT.
8501 if (ConstantSigned) {
8502 if (OtherWidth >= Value.getMinSignedBits())
8503 return;
8504 } else { // !ConstantSigned
8505 if (OtherWidth >= Value.getActiveBits() + 1)
8506 return;
8507 }
8508 } else { // !OtherSigned
8509 // Check that the constant is representable in type OtherT.
8510 // Negative values are out of range.
8511 if (ConstantSigned) {
8512 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8513 return;
8514 } else { // !ConstantSigned
8515 if (OtherWidth >= Value.getActiveBits())
8516 return;
8517 }
Richard Trieu560910c2012-11-14 22:50:24 +00008518 }
Richard Trieu0f097742014-04-04 04:13:47 +00008519 } else { // !CommonSigned
8520 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008521 if (OtherWidth >= Value.getActiveBits())
8522 return;
Craig Toppercf360162014-06-18 05:13:11 +00008523 } else { // OtherSigned
8524 assert(!ConstantSigned &&
8525 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008526 // Check to see if the constant is representable in OtherT.
8527 if (OtherWidth > Value.getActiveBits())
8528 return;
8529 // Check to see if the constant is equivalent to a negative value
8530 // cast to CommonT.
8531 if (S.Context.getIntWidth(ConstantT) ==
8532 S.Context.getIntWidth(CommonT) &&
8533 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8534 return;
8535 // The constant value rests between values that OtherT can represent
8536 // after conversion. Relational comparison still works, but equality
8537 // comparisons will be tautological.
8538 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008539 }
8540 }
Richard Trieu0f097742014-04-04 04:13:47 +00008541
8542 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8543
8544 if (op == BO_EQ || op == BO_NE) {
8545 IsTrue = op == BO_NE;
8546 } else if (EqualityOnly) {
8547 return;
8548 } else if (RhsConstant) {
8549 if (op == BO_GT || op == BO_GE)
8550 IsTrue = !PositiveConstant;
8551 else // op == BO_LT || op == BO_LE
8552 IsTrue = PositiveConstant;
8553 } else {
8554 if (op == BO_LT || op == BO_LE)
8555 IsTrue = !PositiveConstant;
8556 else // op == BO_GT || op == BO_GE
8557 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008558 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008559 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008560 // Other isKnownToHaveBooleanValue
8561 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8562 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8563 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8564
8565 static const struct LinkedConditions {
8566 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8567 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8568 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8569 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8570 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8571 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8572
8573 } TruthTable = {
8574 // Constant on LHS. | Constant on RHS. |
8575 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8576 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8577 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8578 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8579 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8580 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8581 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8582 };
8583
8584 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8585
8586 enum ConstantValue ConstVal = Zero;
8587 if (Value.isUnsigned() || Value.isNonNegative()) {
8588 if (Value == 0) {
8589 LiteralOrBoolConstant =
8590 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8591 ConstVal = Zero;
8592 } else if (Value == 1) {
8593 LiteralOrBoolConstant =
8594 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8595 ConstVal = One;
8596 } else {
8597 LiteralOrBoolConstant = LiteralConstant;
8598 ConstVal = GT_One;
8599 }
8600 } else {
8601 ConstVal = LT_Zero;
8602 }
8603
8604 CompareBoolWithConstantResult CmpRes;
8605
8606 switch (op) {
8607 case BO_LT:
8608 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8609 break;
8610 case BO_GT:
8611 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8612 break;
8613 case BO_LE:
8614 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8615 break;
8616 case BO_GE:
8617 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8618 break;
8619 case BO_EQ:
8620 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8621 break;
8622 case BO_NE:
8623 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8624 break;
8625 default:
8626 CmpRes = Unkwn;
8627 break;
8628 }
8629
8630 if (CmpRes == AFals) {
8631 IsTrue = false;
8632 } else if (CmpRes == ATrue) {
8633 IsTrue = true;
8634 } else {
8635 return;
8636 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008637 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008638
8639 // If this is a comparison to an enum constant, include that
8640 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008641 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008642 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8643 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8644
8645 SmallString<64> PrettySourceValue;
8646 llvm::raw_svector_ostream OS(PrettySourceValue);
8647 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008648 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008649 else
8650 OS << Value;
8651
Richard Trieu0f097742014-04-04 04:13:47 +00008652 S.DiagRuntimeBehavior(
8653 E->getOperatorLoc(), E,
8654 S.PDiag(diag::warn_out_of_range_compare)
8655 << OS.str() << LiteralOrBoolConstant
8656 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8657 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008658}
8659
John McCallcc7e5bf2010-05-06 08:58:33 +00008660/// Analyze the operands of the given comparison. Implements the
8661/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008662void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8664 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008665}
John McCall263a48b2010-01-04 23:31:57 +00008666
John McCallca01b222010-01-04 23:21:16 +00008667/// \brief Implements -Wsign-compare.
8668///
Richard Trieu82402a02011-09-15 21:56:47 +00008669/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008670void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008671 // The type the comparison is being performed in.
8672 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008673
8674 // Only analyze comparison operators where both sides have been converted to
8675 // the same type.
8676 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8677 return AnalyzeImpConvsInComparison(S, E);
8678
8679 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008680 if (E->isValueDependent())
8681 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008682
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008683 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8684 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008685
8686 bool IsComparisonConstant = false;
8687
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008688 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008689 // of 'true' or 'false'.
8690 if (T->isIntegralType(S.Context)) {
8691 llvm::APSInt RHSValue;
8692 bool IsRHSIntegralLiteral =
8693 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8694 llvm::APSInt LHSValue;
8695 bool IsLHSIntegralLiteral =
8696 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8697 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8698 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8699 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8700 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8701 else
8702 IsComparisonConstant =
8703 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008704 } else if (!T->hasUnsignedIntegerRepresentation())
8705 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008706
John McCallcc7e5bf2010-05-06 08:58:33 +00008707 // We don't do anything special if this isn't an unsigned integral
8708 // comparison: we're only interested in integral comparisons, and
8709 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008710 //
8711 // We also don't care about value-dependent expressions or expressions
8712 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008713 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008714 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008715
John McCallcc7e5bf2010-05-06 08:58:33 +00008716 // Check to see if one of the (unmodified) operands is of different
8717 // signedness.
8718 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008719 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8720 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008721 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008722 signedOperand = LHS;
8723 unsignedOperand = RHS;
8724 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8725 signedOperand = RHS;
8726 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008727 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008728 CheckTrivialUnsignedComparison(S, E);
8729 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008730 }
8731
John McCallcc7e5bf2010-05-06 08:58:33 +00008732 // Otherwise, calculate the effective range of the signed operand.
8733 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008734
John McCallcc7e5bf2010-05-06 08:58:33 +00008735 // Go ahead and analyze implicit conversions in the operands. Note
8736 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008737 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8738 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008739
John McCallcc7e5bf2010-05-06 08:58:33 +00008740 // If the signed range is non-negative, -Wsign-compare won't fire,
8741 // but we should still check for comparisons which are always true
8742 // or false.
8743 if (signedRange.NonNegative)
8744 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008745
8746 // For (in)equality comparisons, if the unsigned operand is a
8747 // constant which cannot collide with a overflowed signed operand,
8748 // then reinterpreting the signed operand as unsigned will not
8749 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008750 if (E->isEqualityOp()) {
8751 unsigned comparisonWidth = S.Context.getIntWidth(T);
8752 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008753
John McCallcc7e5bf2010-05-06 08:58:33 +00008754 // We should never be unable to prove that the unsigned operand is
8755 // non-negative.
8756 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8757
8758 if (unsignedRange.Width < comparisonWidth)
8759 return;
8760 }
8761
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008762 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8763 S.PDiag(diag::warn_mixed_sign_comparison)
8764 << LHS->getType() << RHS->getType()
8765 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008766}
8767
John McCall1f425642010-11-11 03:21:53 +00008768/// Analyzes an attempt to assign the given value to a bitfield.
8769///
8770/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008771bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8772 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008773 assert(Bitfield->isBitField());
8774 if (Bitfield->isInvalidDecl())
8775 return false;
8776
John McCalldeebbcf2010-11-11 05:33:51 +00008777 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008778 QualType BitfieldType = Bitfield->getType();
8779 if (BitfieldType->isBooleanType())
8780 return false;
8781
8782 if (BitfieldType->isEnumeralType()) {
8783 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8784 // If the underlying enum type was not explicitly specified as an unsigned
8785 // type and the enum contain only positive values, MSVC++ will cause an
8786 // inconsistency by storing this as a signed type.
8787 if (S.getLangOpts().CPlusPlus11 &&
8788 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8789 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8790 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8791 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8792 << BitfieldEnumDecl->getNameAsString();
8793 }
8794 }
8795
John McCalldeebbcf2010-11-11 05:33:51 +00008796 if (Bitfield->getType()->isBooleanType())
8797 return false;
8798
Douglas Gregor789adec2011-02-04 13:09:01 +00008799 // Ignore value- or type-dependent expressions.
8800 if (Bitfield->getBitWidth()->isValueDependent() ||
8801 Bitfield->getBitWidth()->isTypeDependent() ||
8802 Init->isValueDependent() ||
8803 Init->isTypeDependent())
8804 return false;
8805
John McCall1f425642010-11-11 03:21:53 +00008806 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008807 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008808
Richard Smith5fab0c92011-12-28 19:48:30 +00008809 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008810 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8811 Expr::SE_AllowSideEffects)) {
8812 // The RHS is not constant. If the RHS has an enum type, make sure the
8813 // bitfield is wide enough to hold all the values of the enum without
8814 // truncation.
8815 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8816 EnumDecl *ED = EnumTy->getDecl();
8817 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8818
8819 // Enum types are implicitly signed on Windows, so check if there are any
8820 // negative enumerators to see if the enum was intended to be signed or
8821 // not.
8822 bool SignedEnum = ED->getNumNegativeBits() > 0;
8823
8824 // Check for surprising sign changes when assigning enum values to a
8825 // bitfield of different signedness. If the bitfield is signed and we
8826 // have exactly the right number of bits to store this unsigned enum,
8827 // suggest changing the enum to an unsigned type. This typically happens
8828 // on Windows where unfixed enums always use an underlying type of 'int'.
8829 unsigned DiagID = 0;
8830 if (SignedEnum && !SignedBitfield) {
8831 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8832 } else if (SignedBitfield && !SignedEnum &&
8833 ED->getNumPositiveBits() == FieldWidth) {
8834 DiagID = diag::warn_signed_bitfield_enum_conversion;
8835 }
8836
8837 if (DiagID) {
8838 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8839 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8840 SourceRange TypeRange =
8841 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8842 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8843 << SignedEnum << TypeRange;
8844 }
8845
8846 // Compute the required bitwidth. If the enum has negative values, we need
8847 // one more bit than the normal number of positive bits to represent the
8848 // sign bit.
8849 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8850 ED->getNumNegativeBits())
8851 : ED->getNumPositiveBits();
8852
8853 // Check the bitwidth.
8854 if (BitsNeeded > FieldWidth) {
8855 Expr *WidthExpr = Bitfield->getBitWidth();
8856 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8857 << Bitfield << ED;
8858 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8859 << BitsNeeded << ED << WidthExpr->getSourceRange();
8860 }
8861 }
8862
John McCall1f425642010-11-11 03:21:53 +00008863 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008864 }
John McCall1f425642010-11-11 03:21:53 +00008865
John McCall1f425642010-11-11 03:21:53 +00008866 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008867
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008868 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008869 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008870 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8871 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008872
John McCall1f425642010-11-11 03:21:53 +00008873 if (OriginalWidth <= FieldWidth)
8874 return false;
8875
Eli Friedmanc267a322012-01-26 23:11:39 +00008876 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008877 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008878 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008879
Eli Friedmanc267a322012-01-26 23:11:39 +00008880 // Check whether the stored value is equal to the original value.
8881 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008882 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008883 return false;
8884
Eli Friedmanc267a322012-01-26 23:11:39 +00008885 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008886 // therefore don't strictly fit into a signed bitfield of width 1.
8887 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008888 return false;
8889
John McCall1f425642010-11-11 03:21:53 +00008890 std::string PrettyValue = Value.toString(10);
8891 std::string PrettyTrunc = TruncatedValue.toString(10);
8892
8893 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8894 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8895 << Init->getSourceRange();
8896
8897 return true;
8898}
8899
John McCalld2a53122010-11-09 23:24:47 +00008900/// Analyze the given simple or compound assignment for warning-worthy
8901/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008902void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008903 // Just recurse on the LHS.
8904 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8905
8906 // We want to recurse on the RHS as normal unless we're assigning to
8907 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008908 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008909 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008910 E->getOperatorLoc())) {
8911 // Recurse, ignoring any implicit conversions on the RHS.
8912 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8913 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008914 }
8915 }
8916
8917 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8918}
8919
John McCall263a48b2010-01-04 23:31:57 +00008920/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008921void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8922 SourceLocation CContext, unsigned diag,
8923 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008924 if (pruneControlFlow) {
8925 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8926 S.PDiag(diag)
8927 << SourceType << T << E->getSourceRange()
8928 << SourceRange(CContext));
8929 return;
8930 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008931 S.Diag(E->getExprLoc(), diag)
8932 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8933}
8934
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008935/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008936void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8937 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008938 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008939}
8940
Richard Trieube234c32016-04-21 21:04:55 +00008941
8942/// Diagnose an implicit cast from a floating point value to an integer value.
8943void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8944
8945 SourceLocation CContext) {
8946 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008947 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008948
8949 Expr *InnerE = E->IgnoreParenImpCasts();
8950 // We also want to warn on, e.g., "int i = -1.234"
8951 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8952 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8953 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8954
8955 const bool IsLiteral =
8956 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8957
8958 llvm::APFloat Value(0.0);
8959 bool IsConstant =
8960 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8961 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008962 return DiagnoseImpCast(S, E, T, CContext,
8963 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008964 }
8965
Chandler Carruth016ef402011-04-10 08:36:24 +00008966 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008967
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008968 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8969 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008970 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8971 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008972 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008973 if (IsLiteral) return;
8974 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8975 PruneWarnings);
8976 }
8977
8978 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008979 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008980 // Warn on floating point literal to integer.
8981 DiagID = diag::warn_impcast_literal_float_to_integer;
8982 } else if (IntegerValue == 0) {
8983 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8984 return DiagnoseImpCast(S, E, T, CContext,
8985 diag::warn_impcast_float_integer, PruneWarnings);
8986 }
8987 // Warn on non-zero to zero conversion.
8988 DiagID = diag::warn_impcast_float_to_integer_zero;
8989 } else {
8990 if (IntegerValue.isUnsigned()) {
8991 if (!IntegerValue.isMaxValue()) {
8992 return DiagnoseImpCast(S, E, T, CContext,
8993 diag::warn_impcast_float_integer, PruneWarnings);
8994 }
8995 } else { // IntegerValue.isSigned()
8996 if (!IntegerValue.isMaxSignedValue() &&
8997 !IntegerValue.isMinSignedValue()) {
8998 return DiagnoseImpCast(S, E, T, CContext,
8999 diag::warn_impcast_float_integer, PruneWarnings);
9000 }
9001 }
9002 // Warn on evaluatable floating point expression to integer conversion.
9003 DiagID = diag::warn_impcast_float_to_integer;
9004 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009005
Eli Friedman07185912013-08-29 23:44:43 +00009006 // FIXME: Force the precision of the source value down so we don't print
9007 // digits which are usually useless (we don't really care here if we
9008 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9009 // would automatically print the shortest representation, but it's a bit
9010 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009011 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009012 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9013 precision = (precision * 59 + 195) / 196;
9014 Value.toString(PrettySourceValue, precision);
9015
David Blaikie9b88cc02012-05-15 17:18:27 +00009016 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009017 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009018 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009019 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009020 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009021
Richard Trieube234c32016-04-21 21:04:55 +00009022 if (PruneWarnings) {
9023 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9024 S.PDiag(DiagID)
9025 << E->getType() << T.getUnqualifiedType()
9026 << PrettySourceValue << PrettyTargetValue
9027 << E->getSourceRange() << SourceRange(CContext));
9028 } else {
9029 S.Diag(E->getExprLoc(), DiagID)
9030 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9031 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9032 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009033}
9034
John McCall18a2c2c2010-11-09 22:22:12 +00009035std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9036 if (!Range.Width) return "0";
9037
9038 llvm::APSInt ValueInRange = Value;
9039 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009040 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009041 return ValueInRange.toString(10);
9042}
9043
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009044bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009045 if (!isa<ImplicitCastExpr>(Ex))
9046 return false;
9047
9048 Expr *InnerE = Ex->IgnoreParenImpCasts();
9049 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9050 const Type *Source =
9051 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9052 if (Target->isDependentType())
9053 return false;
9054
9055 const BuiltinType *FloatCandidateBT =
9056 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9057 const Type *BoolCandidateType = ToBool ? Target : Source;
9058
9059 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9060 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9061}
9062
9063void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9064 SourceLocation CC) {
9065 unsigned NumArgs = TheCall->getNumArgs();
9066 for (unsigned i = 0; i < NumArgs; ++i) {
9067 Expr *CurrA = TheCall->getArg(i);
9068 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9069 continue;
9070
9071 bool IsSwapped = ((i > 0) &&
9072 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9073 IsSwapped |= ((i < (NumArgs - 1)) &&
9074 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9075 if (IsSwapped) {
9076 // Warn on this floating-point to bool conversion.
9077 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9078 CurrA->getType(), CC,
9079 diag::warn_impcast_floating_point_to_bool);
9080 }
9081 }
9082}
9083
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009084void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009085 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9086 E->getExprLoc()))
9087 return;
9088
Richard Trieu09d6b802016-01-08 23:35:06 +00009089 // Don't warn on functions which have return type nullptr_t.
9090 if (isa<CallExpr>(E))
9091 return;
9092
Richard Trieu5b993502014-10-15 03:42:06 +00009093 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9094 const Expr::NullPointerConstantKind NullKind =
9095 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9096 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9097 return;
9098
9099 // Return if target type is a safe conversion.
9100 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9101 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9102 return;
9103
9104 SourceLocation Loc = E->getSourceRange().getBegin();
9105
Richard Trieu0a5e1662016-02-13 00:58:53 +00009106 // Venture through the macro stacks to get to the source of macro arguments.
9107 // The new location is a better location than the complete location that was
9108 // passed in.
9109 while (S.SourceMgr.isMacroArgExpansion(Loc))
9110 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9111
9112 while (S.SourceMgr.isMacroArgExpansion(CC))
9113 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9114
Richard Trieu5b993502014-10-15 03:42:06 +00009115 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009116 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9117 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9118 Loc, S.SourceMgr, S.getLangOpts());
9119 if (MacroName == "NULL")
9120 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009121 }
9122
9123 // Only warn if the null and context location are in the same macro expansion.
9124 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9125 return;
9126
9127 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9128 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9129 << FixItHint::CreateReplacement(Loc,
9130 S.getFixItZeroLiteralForType(T, Loc));
9131}
9132
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009133void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9134 ObjCArrayLiteral *ArrayLiteral);
9135void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9136 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009137
9138/// Check a single element within a collection literal against the
9139/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009140void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9141 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009142 // Skip a bitcast to 'id' or qualified 'id'.
9143 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9144 if (ICE->getCastKind() == CK_BitCast &&
9145 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9146 Element = ICE->getSubExpr();
9147 }
9148
9149 QualType ElementType = Element->getType();
9150 ExprResult ElementResult(Element);
9151 if (ElementType->getAs<ObjCObjectPointerType>() &&
9152 S.CheckSingleAssignmentConstraints(TargetElementType,
9153 ElementResult,
9154 false, false)
9155 != Sema::Compatible) {
9156 S.Diag(Element->getLocStart(),
9157 diag::warn_objc_collection_literal_element)
9158 << ElementType << ElementKind << TargetElementType
9159 << Element->getSourceRange();
9160 }
9161
9162 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9163 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9164 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9165 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9166}
9167
9168/// Check an Objective-C array literal being converted to the given
9169/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009170void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9171 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009172 if (!S.NSArrayDecl)
9173 return;
9174
9175 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9176 if (!TargetObjCPtr)
9177 return;
9178
9179 if (TargetObjCPtr->isUnspecialized() ||
9180 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9181 != S.NSArrayDecl->getCanonicalDecl())
9182 return;
9183
9184 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9185 if (TypeArgs.size() != 1)
9186 return;
9187
9188 QualType TargetElementType = TypeArgs[0];
9189 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9190 checkObjCCollectionLiteralElement(S, TargetElementType,
9191 ArrayLiteral->getElement(I),
9192 0);
9193 }
9194}
9195
9196/// Check an Objective-C dictionary literal being converted to the given
9197/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009198void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9199 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009200 if (!S.NSDictionaryDecl)
9201 return;
9202
9203 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9204 if (!TargetObjCPtr)
9205 return;
9206
9207 if (TargetObjCPtr->isUnspecialized() ||
9208 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9209 != S.NSDictionaryDecl->getCanonicalDecl())
9210 return;
9211
9212 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9213 if (TypeArgs.size() != 2)
9214 return;
9215
9216 QualType TargetKeyType = TypeArgs[0];
9217 QualType TargetObjectType = TypeArgs[1];
9218 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9219 auto Element = DictionaryLiteral->getKeyValueElement(I);
9220 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9221 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9222 }
9223}
9224
Richard Trieufc404c72016-02-05 23:02:38 +00009225// Helper function to filter out cases for constant width constant conversion.
9226// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009227bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9228 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009229 // If initializing from a constant, and the constant starts with '0',
9230 // then it is a binary, octal, or hexadecimal. Allow these constants
9231 // to fill all the bits, even if there is a sign change.
9232 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9233 const char FirstLiteralCharacter =
9234 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9235 if (FirstLiteralCharacter == '0')
9236 return false;
9237 }
9238
9239 // If the CC location points to a '{', and the type is char, then assume
9240 // assume it is an array initialization.
9241 if (CC.isValid() && T->isCharType()) {
9242 const char FirstContextCharacter =
9243 S.getSourceManager().getCharacterData(CC)[0];
9244 if (FirstContextCharacter == '{')
9245 return false;
9246 }
9247
9248 return true;
9249}
9250
John McCallcc7e5bf2010-05-06 08:58:33 +00009251void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009252 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009253 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009254
John McCallcc7e5bf2010-05-06 08:58:33 +00009255 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9256 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9257 if (Source == Target) return;
9258 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009259
Chandler Carruthc22845a2011-07-26 05:40:03 +00009260 // If the conversion context location is invalid don't complain. We also
9261 // don't want to emit a warning if the issue occurs from the expansion of
9262 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9263 // delay this check as long as possible. Once we detect we are in that
9264 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009265 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009266 return;
9267
Richard Trieu021baa32011-09-23 20:10:00 +00009268 // Diagnose implicit casts to bool.
9269 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9270 if (isa<StringLiteral>(E))
9271 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009272 // and expressions, for instance, assert(0 && "error here"), are
9273 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009274 return DiagnoseImpCast(S, E, T, CC,
9275 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009276 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9277 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9278 // This covers the literal expressions that evaluate to Objective-C
9279 // objects.
9280 return DiagnoseImpCast(S, E, T, CC,
9281 diag::warn_impcast_objective_c_literal_to_bool);
9282 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009283 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9284 // Warn on pointer to bool conversion that is always true.
9285 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9286 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009287 }
Richard Trieu021baa32011-09-23 20:10:00 +00009288 }
John McCall263a48b2010-01-04 23:31:57 +00009289
Douglas Gregor5054cb02015-07-07 03:58:22 +00009290 // Check implicit casts from Objective-C collection literals to specialized
9291 // collection types, e.g., NSArray<NSString *> *.
9292 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9293 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9294 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9295 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9296
John McCall263a48b2010-01-04 23:31:57 +00009297 // Strip vector types.
9298 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009299 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009300 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009301 return;
John McCallacf0ee52010-10-08 02:01:28 +00009302 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009303 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009304
9305 // If the vector cast is cast between two vectors of the same size, it is
9306 // a bitcast, not a conversion.
9307 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9308 return;
John McCall263a48b2010-01-04 23:31:57 +00009309
9310 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9311 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9312 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009313 if (auto VecTy = dyn_cast<VectorType>(Target))
9314 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009315
9316 // Strip complex types.
9317 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009318 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009319 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009320 return;
9321
John McCallacf0ee52010-10-08 02:01:28 +00009322 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009323 }
John McCall263a48b2010-01-04 23:31:57 +00009324
9325 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9326 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9327 }
9328
9329 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9330 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9331
9332 // If the source is floating point...
9333 if (SourceBT && SourceBT->isFloatingPoint()) {
9334 // ...and the target is floating point...
9335 if (TargetBT && TargetBT->isFloatingPoint()) {
9336 // ...then warn if we're dropping FP rank.
9337
9338 // Builtin FP kinds are ordered by increasing FP rank.
9339 if (SourceBT->getKind() > TargetBT->getKind()) {
9340 // Don't warn about float constants that are precisely
9341 // representable in the target type.
9342 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009343 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009344 // Value might be a float, a float vector, or a float complex.
9345 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009346 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9347 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009348 return;
9349 }
9350
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009351 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009352 return;
9353
John McCallacf0ee52010-10-08 02:01:28 +00009354 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009355 }
9356 // ... or possibly if we're increasing rank, too
9357 else if (TargetBT->getKind() > SourceBT->getKind()) {
9358 if (S.SourceMgr.isInSystemMacro(CC))
9359 return;
9360
9361 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009362 }
9363 return;
9364 }
9365
Richard Trieube234c32016-04-21 21:04:55 +00009366 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009367 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009368 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009369 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009370
Richard Trieube234c32016-04-21 21:04:55 +00009371 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009372 }
John McCall263a48b2010-01-04 23:31:57 +00009373
Richard Smith54894fd2015-12-30 01:06:52 +00009374 // Detect the case where a call result is converted from floating-point to
9375 // to bool, and the final argument to the call is converted from bool, to
9376 // discover this typo:
9377 //
9378 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9379 //
9380 // FIXME: This is an incredibly special case; is there some more general
9381 // way to detect this class of misplaced-parentheses bug?
9382 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009383 // Check last argument of function call to see if it is an
9384 // implicit cast from a type matching the type the result
9385 // is being cast to.
9386 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009387 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009388 Expr *LastA = CEx->getArg(NumArgs - 1);
9389 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009390 if (isa<ImplicitCastExpr>(LastA) &&
9391 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009392 // Warn on this floating-point to bool conversion
9393 DiagnoseImpCast(S, E, T, CC,
9394 diag::warn_impcast_floating_point_to_bool);
9395 }
9396 }
9397 }
John McCall263a48b2010-01-04 23:31:57 +00009398 return;
9399 }
9400
Richard Trieu5b993502014-10-15 03:42:06 +00009401 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009402
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009403 S.DiscardMisalignedMemberAddress(Target, E);
9404
David Blaikie9366d2b2012-06-19 21:19:06 +00009405 if (!Source->isIntegerType() || !Target->isIntegerType())
9406 return;
9407
David Blaikie7555b6a2012-05-15 16:56:36 +00009408 // TODO: remove this early return once the false positives for constant->bool
9409 // in templates, macros, etc, are reduced or removed.
9410 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9411 return;
9412
John McCallcc7e5bf2010-05-06 08:58:33 +00009413 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009414 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009415
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009416 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009417 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009418 // TODO: this should happen for bitfield stores, too.
9419 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009420 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009421 if (S.SourceMgr.isInSystemMacro(CC))
9422 return;
9423
John McCall18a2c2c2010-11-09 22:22:12 +00009424 std::string PrettySourceValue = Value.toString(10);
9425 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009426
Ted Kremenek33ba9952011-10-22 02:37:33 +00009427 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9428 S.PDiag(diag::warn_impcast_integer_precision_constant)
9429 << PrettySourceValue << PrettyTargetValue
9430 << E->getType() << T << E->getSourceRange()
9431 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009432 return;
9433 }
9434
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009435 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9436 if (S.SourceMgr.isInSystemMacro(CC))
9437 return;
9438
David Blaikie9455da02012-04-12 22:40:54 +00009439 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009440 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9441 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009442 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009443 }
9444
Richard Trieudcb55572016-01-29 23:51:16 +00009445 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9446 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9447 // Warn when doing a signed to signed conversion, warn if the positive
9448 // source value is exactly the width of the target type, which will
9449 // cause a negative value to be stored.
9450
9451 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009452 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9453 !S.SourceMgr.isInSystemMacro(CC)) {
9454 if (isSameWidthConstantConversion(S, E, T, CC)) {
9455 std::string PrettySourceValue = Value.toString(10);
9456 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009457
Richard Trieufc404c72016-02-05 23:02:38 +00009458 S.DiagRuntimeBehavior(
9459 E->getExprLoc(), E,
9460 S.PDiag(diag::warn_impcast_integer_precision_constant)
9461 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9462 << E->getSourceRange() << clang::SourceRange(CC));
9463 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009464 }
9465 }
Richard Trieufc404c72016-02-05 23:02:38 +00009466
Richard Trieudcb55572016-01-29 23:51:16 +00009467 // Fall through for non-constants to give a sign conversion warning.
9468 }
9469
John McCallcc7e5bf2010-05-06 08:58:33 +00009470 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9471 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9472 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009473 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009474 return;
9475
John McCallcc7e5bf2010-05-06 08:58:33 +00009476 unsigned DiagID = diag::warn_impcast_integer_sign;
9477
9478 // Traditionally, gcc has warned about this under -Wsign-compare.
9479 // We also want to warn about it in -Wconversion.
9480 // So if -Wconversion is off, use a completely identical diagnostic
9481 // in the sign-compare group.
9482 // The conditional-checking code will
9483 if (ICContext) {
9484 DiagID = diag::warn_impcast_integer_sign_conditional;
9485 *ICContext = true;
9486 }
9487
John McCallacf0ee52010-10-08 02:01:28 +00009488 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009489 }
9490
Douglas Gregora78f1932011-02-22 02:45:07 +00009491 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009492 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9493 // type, to give us better diagnostics.
9494 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009495 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009496 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9497 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9498 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9499 SourceType = S.Context.getTypeDeclType(Enum);
9500 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9501 }
9502 }
9503
Douglas Gregora78f1932011-02-22 02:45:07 +00009504 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9505 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009506 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9507 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009508 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009509 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009510 return;
9511
Douglas Gregor364f7db2011-03-12 00:14:31 +00009512 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009513 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009514 }
John McCall263a48b2010-01-04 23:31:57 +00009515}
9516
David Blaikie18e9ac72012-05-15 21:57:38 +00009517void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9518 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009519
9520void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009521 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009522 E = E->IgnoreParenImpCasts();
9523
9524 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009525 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009526
John McCallacf0ee52010-10-08 02:01:28 +00009527 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009528 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009529 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009530}
9531
David Blaikie18e9ac72012-05-15 21:57:38 +00009532void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9533 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009534 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009535
9536 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009537 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9538 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009539
9540 // If -Wconversion would have warned about either of the candidates
9541 // for a signedness conversion to the context type...
9542 if (!Suspicious) return;
9543
9544 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009545 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009546 return;
9547
John McCallcc7e5bf2010-05-06 08:58:33 +00009548 // ...then check whether it would have warned about either of the
9549 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009550 if (E->getType() == T) return;
9551
9552 Suspicious = false;
9553 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9554 E->getType(), CC, &Suspicious);
9555 if (!Suspicious)
9556 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009557 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009558}
9559
Richard Trieu65724892014-11-15 06:37:39 +00009560/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9561/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009562void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009563 if (S.getLangOpts().Bool)
9564 return;
9565 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9566}
9567
John McCallcc7e5bf2010-05-06 08:58:33 +00009568/// AnalyzeImplicitConversions - Find and report any interesting
9569/// implicit conversions in the given expression. There are a couple
9570/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009571void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009572 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009573 Expr *E = OrigE->IgnoreParenImpCasts();
9574
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009575 if (E->isTypeDependent() || E->isValueDependent())
9576 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009577
John McCallcc7e5bf2010-05-06 08:58:33 +00009578 // For conditional operators, we analyze the arguments as if they
9579 // were being fed directly into the output.
9580 if (isa<ConditionalOperator>(E)) {
9581 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009582 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009583 return;
9584 }
9585
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009586 // Check implicit argument conversions for function calls.
9587 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9588 CheckImplicitArgumentConversions(S, Call, CC);
9589
John McCallcc7e5bf2010-05-06 08:58:33 +00009590 // Go ahead and check any implicit conversions we might have skipped.
9591 // The non-canonical typecheck is just an optimization;
9592 // CheckImplicitConversion will filter out dead implicit conversions.
9593 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009594 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009595
9596 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009597
9598 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9599 // The bound subexpressions in a PseudoObjectExpr are not reachable
9600 // as transitive children.
9601 // FIXME: Use a more uniform representation for this.
9602 for (auto *SE : POE->semantics())
9603 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9604 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009605 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009606
John McCallcc7e5bf2010-05-06 08:58:33 +00009607 // Skip past explicit casts.
9608 if (isa<ExplicitCastExpr>(E)) {
9609 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009610 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009611 }
9612
John McCalld2a53122010-11-09 23:24:47 +00009613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9614 // Do a somewhat different check with comparison operators.
9615 if (BO->isComparisonOp())
9616 return AnalyzeComparison(S, BO);
9617
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009618 // And with simple assignments.
9619 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009620 return AnalyzeAssignment(S, BO);
9621 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009622
9623 // These break the otherwise-useful invariant below. Fortunately,
9624 // we don't really need to recurse into them, because any internal
9625 // expressions should have been analyzed already when they were
9626 // built into statements.
9627 if (isa<StmtExpr>(E)) return;
9628
9629 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009630 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009631
9632 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009633 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009634 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009635 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009636 for (Stmt *SubStmt : E->children()) {
9637 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009638 if (!ChildExpr)
9639 continue;
9640
Richard Trieu955231d2014-01-25 01:10:35 +00009641 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009642 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009643 // Ignore checking string literals that are in logical and operators.
9644 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009645 continue;
9646 AnalyzeImplicitConversions(S, ChildExpr, CC);
9647 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009648
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009649 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009650 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9651 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009652 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009653
9654 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9655 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009656 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009657 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009658
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009659 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9660 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009661 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009662}
9663
9664} // end anonymous namespace
9665
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009666/// Diagnose integer type and any valid implicit convertion to it.
9667static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9668 // Taking into account implicit conversions,
9669 // allow any integer.
9670 if (!E->getType()->isIntegerType()) {
9671 S.Diag(E->getLocStart(),
9672 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9673 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009674 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009675 // Potentially emit standard warnings for implicit conversions if enabled
9676 // using -Wconversion.
9677 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9678 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009679}
9680
Richard Trieuc1888e02014-06-28 23:25:37 +00009681// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9682// Returns true when emitting a warning about taking the address of a reference.
9683static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009684 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009685 E = E->IgnoreParenImpCasts();
9686
9687 const FunctionDecl *FD = nullptr;
9688
9689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9690 if (!DRE->getDecl()->getType()->isReferenceType())
9691 return false;
9692 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9693 if (!M->getMemberDecl()->getType()->isReferenceType())
9694 return false;
9695 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009696 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009697 return false;
9698 FD = Call->getDirectCallee();
9699 } else {
9700 return false;
9701 }
9702
9703 SemaRef.Diag(E->getExprLoc(), PD);
9704
9705 // If possible, point to location of function.
9706 if (FD) {
9707 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9708 }
9709
9710 return true;
9711}
9712
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009713// Returns true if the SourceLocation is expanded from any macro body.
9714// Returns false if the SourceLocation is invalid, is from not in a macro
9715// expansion, or is from expanded from a top-level macro argument.
9716static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9717 if (Loc.isInvalid())
9718 return false;
9719
9720 while (Loc.isMacroID()) {
9721 if (SM.isMacroBodyExpansion(Loc))
9722 return true;
9723 Loc = SM.getImmediateMacroCallerLoc(Loc);
9724 }
9725
9726 return false;
9727}
9728
Richard Trieu3bb8b562014-02-26 02:36:06 +00009729/// \brief Diagnose pointers that are always non-null.
9730/// \param E the expression containing the pointer
9731/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9732/// compared to a null pointer
9733/// \param IsEqual True when the comparison is equal to a null pointer
9734/// \param Range Extra SourceRange to highlight in the diagnostic
9735void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9736 Expr::NullPointerConstantKind NullKind,
9737 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009738 if (!E)
9739 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009740
9741 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009742 if (E->getExprLoc().isMacroID()) {
9743 const SourceManager &SM = getSourceManager();
9744 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9745 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009746 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009747 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009748 E = E->IgnoreImpCasts();
9749
9750 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9751
Richard Trieuf7432752014-06-06 21:39:26 +00009752 if (isa<CXXThisExpr>(E)) {
9753 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9754 : diag::warn_this_bool_conversion;
9755 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9756 return;
9757 }
9758
Richard Trieu3bb8b562014-02-26 02:36:06 +00009759 bool IsAddressOf = false;
9760
9761 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9762 if (UO->getOpcode() != UO_AddrOf)
9763 return;
9764 IsAddressOf = true;
9765 E = UO->getSubExpr();
9766 }
9767
Richard Trieuc1888e02014-06-28 23:25:37 +00009768 if (IsAddressOf) {
9769 unsigned DiagID = IsCompare
9770 ? diag::warn_address_of_reference_null_compare
9771 : diag::warn_address_of_reference_bool_conversion;
9772 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9773 << IsEqual;
9774 if (CheckForReference(*this, E, PD)) {
9775 return;
9776 }
9777 }
9778
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009779 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9780 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009781 std::string Str;
9782 llvm::raw_string_ostream S(Str);
9783 E->printPretty(S, nullptr, getPrintingPolicy());
9784 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9785 : diag::warn_cast_nonnull_to_bool;
9786 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9787 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009788 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009789 };
9790
9791 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9792 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9793 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009794 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9795 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009796 return;
9797 }
9798 }
9799 }
9800
Richard Trieu3bb8b562014-02-26 02:36:06 +00009801 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009802 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009803 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9804 D = R->getDecl();
9805 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9806 D = M->getMemberDecl();
9807 }
9808
9809 // Weak Decls can be null.
9810 if (!D || D->isWeak())
9811 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009812
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009813 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009814 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9815 if (getCurFunction() &&
9816 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009817 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9818 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009819 return;
9820 }
9821
9822 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009823 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009824 assert(ParamIter != FD->param_end());
9825 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9826
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009827 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9828 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009829 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009830 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009831 }
George Burgess IV850269a2015-12-08 22:02:00 +00009832
9833 for (unsigned ArgNo : NonNull->args()) {
9834 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009835 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009836 return;
9837 }
George Burgess IV850269a2015-12-08 22:02:00 +00009838 }
9839 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009840 }
9841 }
George Burgess IV850269a2015-12-08 22:02:00 +00009842 }
9843
Richard Trieu3bb8b562014-02-26 02:36:06 +00009844 QualType T = D->getType();
9845 const bool IsArray = T->isArrayType();
9846 const bool IsFunction = T->isFunctionType();
9847
Richard Trieuc1888e02014-06-28 23:25:37 +00009848 // Address of function is used to silence the function warning.
9849 if (IsAddressOf && IsFunction) {
9850 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009851 }
9852
9853 // Found nothing.
9854 if (!IsAddressOf && !IsFunction && !IsArray)
9855 return;
9856
9857 // Pretty print the expression for the diagnostic.
9858 std::string Str;
9859 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009860 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009861
9862 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9863 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009864 enum {
9865 AddressOf,
9866 FunctionPointer,
9867 ArrayPointer
9868 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009869 if (IsAddressOf)
9870 DiagType = AddressOf;
9871 else if (IsFunction)
9872 DiagType = FunctionPointer;
9873 else if (IsArray)
9874 DiagType = ArrayPointer;
9875 else
9876 llvm_unreachable("Could not determine diagnostic.");
9877 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9878 << Range << IsEqual;
9879
9880 if (!IsFunction)
9881 return;
9882
9883 // Suggest '&' to silence the function warning.
9884 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9885 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9886
9887 // Check to see if '()' fixit should be emitted.
9888 QualType ReturnType;
9889 UnresolvedSet<4> NonTemplateOverloads;
9890 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9891 if (ReturnType.isNull())
9892 return;
9893
9894 if (IsCompare) {
9895 // There are two cases here. If there is null constant, the only suggest
9896 // for a pointer return type. If the null is 0, then suggest if the return
9897 // type is a pointer or an integer type.
9898 if (!ReturnType->isPointerType()) {
9899 if (NullKind == Expr::NPCK_ZeroExpression ||
9900 NullKind == Expr::NPCK_ZeroLiteral) {
9901 if (!ReturnType->isIntegerType())
9902 return;
9903 } else {
9904 return;
9905 }
9906 }
9907 } else { // !IsCompare
9908 // For function to bool, only suggest if the function pointer has bool
9909 // return type.
9910 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9911 return;
9912 }
9913 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009914 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009915}
9916
John McCallcc7e5bf2010-05-06 08:58:33 +00009917/// Diagnoses "dangerous" implicit conversions within the given
9918/// expression (which is a full expression). Implements -Wconversion
9919/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009920///
9921/// \param CC the "context" location of the implicit conversion, i.e.
9922/// the most location of the syntactic entity requiring the implicit
9923/// conversion
9924void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009925 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009926 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009927 return;
9928
9929 // Don't diagnose for value- or type-dependent expressions.
9930 if (E->isTypeDependent() || E->isValueDependent())
9931 return;
9932
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009933 // Check for array bounds violations in cases where the check isn't triggered
9934 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9935 // ArraySubscriptExpr is on the RHS of a variable initialization.
9936 CheckArrayAccess(E);
9937
John McCallacf0ee52010-10-08 02:01:28 +00009938 // This is not the right CC for (e.g.) a variable initialization.
9939 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009940}
9941
Richard Trieu65724892014-11-15 06:37:39 +00009942/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9943/// Input argument E is a logical expression.
9944void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9945 ::CheckBoolLikeConversion(*this, E, CC);
9946}
9947
Richard Smith9f7df0c2017-06-26 23:19:32 +00009948/// Diagnose when expression is an integer constant expression and its evaluation
9949/// results in integer overflow
9950void Sema::CheckForIntOverflow (Expr *E) {
9951 // Use a work list to deal with nested struct initializers.
9952 SmallVector<Expr *, 2> Exprs(1, E);
9953
9954 do {
9955 Expr *E = Exprs.pop_back_val();
9956
9957 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9958 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9959 continue;
9960 }
9961
9962 if (auto InitList = dyn_cast<InitListExpr>(E))
9963 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9964
9965 if (isa<ObjCBoxedExpr>(E))
9966 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9967 } while (!Exprs.empty());
9968}
9969
Richard Smithc406cb72013-01-17 01:17:56 +00009970namespace {
9971/// \brief Visitor for expressions which looks for unsequenced operations on the
9972/// same object.
9973class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009974 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9975
Richard Smithc406cb72013-01-17 01:17:56 +00009976 /// \brief A tree of sequenced regions within an expression. Two regions are
9977 /// unsequenced if one is an ancestor or a descendent of the other. When we
9978 /// finish processing an expression with sequencing, such as a comma
9979 /// expression, we fold its tree nodes into its parent, since they are
9980 /// unsequenced with respect to nodes we will visit later.
9981 class SequenceTree {
9982 struct Value {
9983 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9984 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009985 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009986 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009987 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009988
9989 public:
9990 /// \brief A region within an expression which may be sequenced with respect
9991 /// to some other region.
9992 class Seq {
9993 explicit Seq(unsigned N) : Index(N) {}
9994 unsigned Index;
9995 friend class SequenceTree;
9996 public:
9997 Seq() : Index(0) {}
9998 };
9999
10000 SequenceTree() { Values.push_back(Value(0)); }
10001 Seq root() const { return Seq(0); }
10002
10003 /// \brief Create a new sequence of operations, which is an unsequenced
10004 /// subset of \p Parent. This sequence of operations is sequenced with
10005 /// respect to other children of \p Parent.
10006 Seq allocate(Seq Parent) {
10007 Values.push_back(Value(Parent.Index));
10008 return Seq(Values.size() - 1);
10009 }
10010
10011 /// \brief Merge a sequence of operations into its parent.
10012 void merge(Seq S) {
10013 Values[S.Index].Merged = true;
10014 }
10015
10016 /// \brief Determine whether two operations are unsequenced. This operation
10017 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10018 /// should have been merged into its parent as appropriate.
10019 bool isUnsequenced(Seq Cur, Seq Old) {
10020 unsigned C = representative(Cur.Index);
10021 unsigned Target = representative(Old.Index);
10022 while (C >= Target) {
10023 if (C == Target)
10024 return true;
10025 C = Values[C].Parent;
10026 }
10027 return false;
10028 }
10029
10030 private:
10031 /// \brief Pick a representative for a sequence.
10032 unsigned representative(unsigned K) {
10033 if (Values[K].Merged)
10034 // Perform path compression as we go.
10035 return Values[K].Parent = representative(Values[K].Parent);
10036 return K;
10037 }
10038 };
10039
10040 /// An object for which we can track unsequenced uses.
10041 typedef NamedDecl *Object;
10042
10043 /// Different flavors of object usage which we track. We only track the
10044 /// least-sequenced usage of each kind.
10045 enum UsageKind {
10046 /// A read of an object. Multiple unsequenced reads are OK.
10047 UK_Use,
10048 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010049 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010050 UK_ModAsValue,
10051 /// A modification of an object which is not sequenced before the value
10052 /// computation of the expression, such as n++.
10053 UK_ModAsSideEffect,
10054
10055 UK_Count = UK_ModAsSideEffect + 1
10056 };
10057
10058 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010059 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010060 Expr *Use;
10061 SequenceTree::Seq Seq;
10062 };
10063
10064 struct UsageInfo {
10065 UsageInfo() : Diagnosed(false) {}
10066 Usage Uses[UK_Count];
10067 /// Have we issued a diagnostic for this variable already?
10068 bool Diagnosed;
10069 };
10070 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10071
10072 Sema &SemaRef;
10073 /// Sequenced regions within the expression.
10074 SequenceTree Tree;
10075 /// Declaration modifications and references which we have seen.
10076 UsageInfoMap UsageMap;
10077 /// The region we are currently within.
10078 SequenceTree::Seq Region;
10079 /// Filled in with declarations which were modified as a side-effect
10080 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010081 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010082 /// Expressions to check later. We defer checking these to reduce
10083 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010084 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010085
10086 /// RAII object wrapping the visitation of a sequenced subexpression of an
10087 /// expression. At the end of this process, the side-effects of the evaluation
10088 /// become sequenced with respect to the value computation of the result, so
10089 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10090 /// UK_ModAsValue.
10091 struct SequencedSubexpression {
10092 SequencedSubexpression(SequenceChecker &Self)
10093 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10094 Self.ModAsSideEffect = &ModAsSideEffect;
10095 }
10096 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010097 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10098 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010099 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010100 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10101 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010102 }
10103 Self.ModAsSideEffect = OldModAsSideEffect;
10104 }
10105
10106 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010107 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10108 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010109 };
10110
Richard Smith40238f02013-06-20 22:21:56 +000010111 /// RAII object wrapping the visitation of a subexpression which we might
10112 /// choose to evaluate as a constant. If any subexpression is evaluated and
10113 /// found to be non-constant, this allows us to suppress the evaluation of
10114 /// the outer expression.
10115 class EvaluationTracker {
10116 public:
10117 EvaluationTracker(SequenceChecker &Self)
10118 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10119 Self.EvalTracker = this;
10120 }
10121 ~EvaluationTracker() {
10122 Self.EvalTracker = Prev;
10123 if (Prev)
10124 Prev->EvalOK &= EvalOK;
10125 }
10126
10127 bool evaluate(const Expr *E, bool &Result) {
10128 if (!EvalOK || E->isValueDependent())
10129 return false;
10130 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10131 return EvalOK;
10132 }
10133
10134 private:
10135 SequenceChecker &Self;
10136 EvaluationTracker *Prev;
10137 bool EvalOK;
10138 } *EvalTracker;
10139
Richard Smithc406cb72013-01-17 01:17:56 +000010140 /// \brief Find the object which is produced by the specified expression,
10141 /// if any.
10142 Object getObject(Expr *E, bool Mod) const {
10143 E = E->IgnoreParenCasts();
10144 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10145 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10146 return getObject(UO->getSubExpr(), Mod);
10147 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10148 if (BO->getOpcode() == BO_Comma)
10149 return getObject(BO->getRHS(), Mod);
10150 if (Mod && BO->isAssignmentOp())
10151 return getObject(BO->getLHS(), Mod);
10152 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10153 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10154 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10155 return ME->getMemberDecl();
10156 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10157 // FIXME: If this is a reference, map through to its value.
10158 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010159 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010160 }
10161
10162 /// \brief Note that an object was modified or used by an expression.
10163 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10164 Usage &U = UI.Uses[UK];
10165 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10166 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10167 ModAsSideEffect->push_back(std::make_pair(O, U));
10168 U.Use = Ref;
10169 U.Seq = Region;
10170 }
10171 }
10172 /// \brief Check whether a modification or use conflicts with a prior usage.
10173 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10174 bool IsModMod) {
10175 if (UI.Diagnosed)
10176 return;
10177
10178 const Usage &U = UI.Uses[OtherKind];
10179 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10180 return;
10181
10182 Expr *Mod = U.Use;
10183 Expr *ModOrUse = Ref;
10184 if (OtherKind == UK_Use)
10185 std::swap(Mod, ModOrUse);
10186
10187 SemaRef.Diag(Mod->getExprLoc(),
10188 IsModMod ? diag::warn_unsequenced_mod_mod
10189 : diag::warn_unsequenced_mod_use)
10190 << O << SourceRange(ModOrUse->getExprLoc());
10191 UI.Diagnosed = true;
10192 }
10193
10194 void notePreUse(Object O, Expr *Use) {
10195 UsageInfo &U = UsageMap[O];
10196 // Uses conflict with other modifications.
10197 checkUsage(O, U, Use, UK_ModAsValue, false);
10198 }
10199 void notePostUse(Object O, Expr *Use) {
10200 UsageInfo &U = UsageMap[O];
10201 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10202 addUsage(U, O, Use, UK_Use);
10203 }
10204
10205 void notePreMod(Object O, Expr *Mod) {
10206 UsageInfo &U = UsageMap[O];
10207 // Modifications conflict with other modifications and with uses.
10208 checkUsage(O, U, Mod, UK_ModAsValue, true);
10209 checkUsage(O, U, Mod, UK_Use, false);
10210 }
10211 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10212 UsageInfo &U = UsageMap[O];
10213 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10214 addUsage(U, O, Use, UK);
10215 }
10216
10217public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010218 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010219 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10220 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010221 Visit(E);
10222 }
10223
10224 void VisitStmt(Stmt *S) {
10225 // Skip all statements which aren't expressions for now.
10226 }
10227
10228 void VisitExpr(Expr *E) {
10229 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010230 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010231 }
10232
10233 void VisitCastExpr(CastExpr *E) {
10234 Object O = Object();
10235 if (E->getCastKind() == CK_LValueToRValue)
10236 O = getObject(E->getSubExpr(), false);
10237
10238 if (O)
10239 notePreUse(O, E);
10240 VisitExpr(E);
10241 if (O)
10242 notePostUse(O, E);
10243 }
10244
10245 void VisitBinComma(BinaryOperator *BO) {
10246 // C++11 [expr.comma]p1:
10247 // Every value computation and side effect associated with the left
10248 // expression is sequenced before every value computation and side
10249 // effect associated with the right expression.
10250 SequenceTree::Seq LHS = Tree.allocate(Region);
10251 SequenceTree::Seq RHS = Tree.allocate(Region);
10252 SequenceTree::Seq OldRegion = Region;
10253
10254 {
10255 SequencedSubexpression SeqLHS(*this);
10256 Region = LHS;
10257 Visit(BO->getLHS());
10258 }
10259
10260 Region = RHS;
10261 Visit(BO->getRHS());
10262
10263 Region = OldRegion;
10264
10265 // Forget that LHS and RHS are sequenced. They are both unsequenced
10266 // with respect to other stuff.
10267 Tree.merge(LHS);
10268 Tree.merge(RHS);
10269 }
10270
10271 void VisitBinAssign(BinaryOperator *BO) {
10272 // The modification is sequenced after the value computation of the LHS
10273 // and RHS, so check it before inspecting the operands and update the
10274 // map afterwards.
10275 Object O = getObject(BO->getLHS(), true);
10276 if (!O)
10277 return VisitExpr(BO);
10278
10279 notePreMod(O, BO);
10280
10281 // C++11 [expr.ass]p7:
10282 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10283 // only once.
10284 //
10285 // Therefore, for a compound assignment operator, O is considered used
10286 // everywhere except within the evaluation of E1 itself.
10287 if (isa<CompoundAssignOperator>(BO))
10288 notePreUse(O, BO);
10289
10290 Visit(BO->getLHS());
10291
10292 if (isa<CompoundAssignOperator>(BO))
10293 notePostUse(O, BO);
10294
10295 Visit(BO->getRHS());
10296
Richard Smith83e37bee2013-06-26 23:16:51 +000010297 // C++11 [expr.ass]p1:
10298 // the assignment is sequenced [...] before the value computation of the
10299 // assignment expression.
10300 // C11 6.5.16/3 has no such rule.
10301 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10302 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010303 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010304
Richard Smithc406cb72013-01-17 01:17:56 +000010305 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10306 VisitBinAssign(CAO);
10307 }
10308
10309 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10310 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10311 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10312 Object O = getObject(UO->getSubExpr(), true);
10313 if (!O)
10314 return VisitExpr(UO);
10315
10316 notePreMod(O, UO);
10317 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010318 // C++11 [expr.pre.incr]p1:
10319 // the expression ++x is equivalent to x+=1
10320 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10321 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010322 }
10323
10324 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10325 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10326 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10327 Object O = getObject(UO->getSubExpr(), true);
10328 if (!O)
10329 return VisitExpr(UO);
10330
10331 notePreMod(O, UO);
10332 Visit(UO->getSubExpr());
10333 notePostMod(O, UO, UK_ModAsSideEffect);
10334 }
10335
10336 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10337 void VisitBinLOr(BinaryOperator *BO) {
10338 // The side-effects of the LHS of an '&&' are sequenced before the
10339 // value computation of the RHS, and hence before the value computation
10340 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10341 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010342 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010343 {
10344 SequencedSubexpression Sequenced(*this);
10345 Visit(BO->getLHS());
10346 }
10347
10348 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010349 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010350 if (!Result)
10351 Visit(BO->getRHS());
10352 } else {
10353 // Check for unsequenced operations in the RHS, treating it as an
10354 // entirely separate evaluation.
10355 //
10356 // FIXME: If there are operations in the RHS which are unsequenced
10357 // with respect to operations outside the RHS, and those operations
10358 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010359 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010360 }
Richard Smithc406cb72013-01-17 01:17:56 +000010361 }
10362 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010363 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010364 {
10365 SequencedSubexpression Sequenced(*this);
10366 Visit(BO->getLHS());
10367 }
10368
10369 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010370 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010371 if (Result)
10372 Visit(BO->getRHS());
10373 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010374 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010375 }
Richard Smithc406cb72013-01-17 01:17:56 +000010376 }
10377
10378 // Only visit the condition, unless we can be sure which subexpression will
10379 // be chosen.
10380 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010381 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010382 {
10383 SequencedSubexpression Sequenced(*this);
10384 Visit(CO->getCond());
10385 }
Richard Smithc406cb72013-01-17 01:17:56 +000010386
10387 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010388 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010389 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010390 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010391 WorkList.push_back(CO->getTrueExpr());
10392 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010393 }
Richard Smithc406cb72013-01-17 01:17:56 +000010394 }
10395
Richard Smithe3dbfe02013-06-30 10:40:20 +000010396 void VisitCallExpr(CallExpr *CE) {
10397 // C++11 [intro.execution]p15:
10398 // When calling a function [...], every value computation and side effect
10399 // associated with any argument expression, or with the postfix expression
10400 // designating the called function, is sequenced before execution of every
10401 // expression or statement in the body of the function [and thus before
10402 // the value computation of its result].
10403 SequencedSubexpression Sequenced(*this);
10404 Base::VisitCallExpr(CE);
10405
10406 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10407 }
10408
Richard Smithc406cb72013-01-17 01:17:56 +000010409 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010410 // This is a call, so all subexpressions are sequenced before the result.
10411 SequencedSubexpression Sequenced(*this);
10412
Richard Smithc406cb72013-01-17 01:17:56 +000010413 if (!CCE->isListInitialization())
10414 return VisitExpr(CCE);
10415
10416 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010417 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010418 SequenceTree::Seq Parent = Region;
10419 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10420 E = CCE->arg_end();
10421 I != E; ++I) {
10422 Region = Tree.allocate(Parent);
10423 Elts.push_back(Region);
10424 Visit(*I);
10425 }
10426
10427 // Forget that the initializers are sequenced.
10428 Region = Parent;
10429 for (unsigned I = 0; I < Elts.size(); ++I)
10430 Tree.merge(Elts[I]);
10431 }
10432
10433 void VisitInitListExpr(InitListExpr *ILE) {
10434 if (!SemaRef.getLangOpts().CPlusPlus11)
10435 return VisitExpr(ILE);
10436
10437 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010438 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010439 SequenceTree::Seq Parent = Region;
10440 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10441 Expr *E = ILE->getInit(I);
10442 if (!E) continue;
10443 Region = Tree.allocate(Parent);
10444 Elts.push_back(Region);
10445 Visit(E);
10446 }
10447
10448 // Forget that the initializers are sequenced.
10449 Region = Parent;
10450 for (unsigned I = 0; I < Elts.size(); ++I)
10451 Tree.merge(Elts[I]);
10452 }
10453};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010454} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010455
10456void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010457 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010458 WorkList.push_back(E);
10459 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010460 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010461 SequenceChecker(*this, Item, WorkList);
10462 }
Richard Smithc406cb72013-01-17 01:17:56 +000010463}
10464
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010465void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10466 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010467 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010468 if (!E->isInstantiationDependent())
10469 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010470 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010471 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010472 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010473}
10474
John McCall1f425642010-11-11 03:21:53 +000010475void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10476 FieldDecl *BitField,
10477 Expr *Init) {
10478 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10479}
10480
David Majnemer61a5bbf2015-04-07 22:08:51 +000010481static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10482 SourceLocation Loc) {
10483 if (!PType->isVariablyModifiedType())
10484 return;
10485 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10486 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10487 return;
10488 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010489 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10490 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10491 return;
10492 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010493 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10494 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10495 return;
10496 }
10497
10498 const ArrayType *AT = S.Context.getAsArrayType(PType);
10499 if (!AT)
10500 return;
10501
10502 if (AT->getSizeModifier() != ArrayType::Star) {
10503 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10504 return;
10505 }
10506
10507 S.Diag(Loc, diag::err_array_star_in_function_definition);
10508}
10509
Mike Stump0c2ec772010-01-21 03:59:47 +000010510/// CheckParmsForFunctionDef - Check that the parameters of the given
10511/// function are appropriate for the definition of a function. This
10512/// takes care of any checks that cannot be performed on the
10513/// declaration itself, e.g., that the types of each of the function
10514/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010515bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010516 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010517 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010518 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010519 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10520 // function declarator that is part of a function definition of
10521 // that function shall not have incomplete type.
10522 //
10523 // This is also C++ [dcl.fct]p6.
10524 if (!Param->isInvalidDecl() &&
10525 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010526 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010527 Param->setInvalidDecl();
10528 HasInvalidParm = true;
10529 }
10530
10531 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10532 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010533 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010534 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010535 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010536 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010537 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010538
10539 // C99 6.7.5.3p12:
10540 // If the function declarator is not part of a definition of that
10541 // function, parameters may have incomplete type and may use the [*]
10542 // notation in their sequences of declarator specifiers to specify
10543 // variable length array types.
10544 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010545 // FIXME: This diagnostic should point the '[*]' if source-location
10546 // information is added for it.
10547 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010548
10549 // MSVC destroys objects passed by value in the callee. Therefore a
10550 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010551 // object's destructor. However, we don't perform any direct access check
10552 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010553 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10554 .getCXXABI()
10555 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010556 if (!Param->isInvalidDecl()) {
10557 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10558 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10559 if (!ClassDecl->isInvalidDecl() &&
10560 !ClassDecl->hasIrrelevantDestructor() &&
10561 !ClassDecl->isDependentContext()) {
10562 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10563 MarkFunctionReferenced(Param->getLocation(), Destructor);
10564 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10565 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010566 }
10567 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010568 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010569
10570 // Parameters with the pass_object_size attribute only need to be marked
10571 // constant at function definitions. Because we lack information about
10572 // whether we're on a declaration or definition when we're instantiating the
10573 // attribute, we need to check for constness here.
10574 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10575 if (!Param->getType().isConstQualified())
10576 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10577 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010578 }
10579
10580 return HasInvalidParm;
10581}
John McCall2b5c1b22010-08-12 21:44:57 +000010582
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010583/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10584/// or MemberExpr.
10585static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10586 ASTContext &Context) {
10587 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10588 return Context.getDeclAlign(DRE->getDecl());
10589
10590 if (const auto *ME = dyn_cast<MemberExpr>(E))
10591 return Context.getDeclAlign(ME->getMemberDecl());
10592
10593 return TypeAlign;
10594}
10595
John McCall2b5c1b22010-08-12 21:44:57 +000010596/// CheckCastAlign - Implements -Wcast-align, which warns when a
10597/// pointer cast increases the alignment requirements.
10598void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10599 // This is actually a lot of work to potentially be doing on every
10600 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010601 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010602 return;
10603
10604 // Ignore dependent types.
10605 if (T->isDependentType() || Op->getType()->isDependentType())
10606 return;
10607
10608 // Require that the destination be a pointer type.
10609 const PointerType *DestPtr = T->getAs<PointerType>();
10610 if (!DestPtr) return;
10611
10612 // If the destination has alignment 1, we're done.
10613 QualType DestPointee = DestPtr->getPointeeType();
10614 if (DestPointee->isIncompleteType()) return;
10615 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10616 if (DestAlign.isOne()) return;
10617
10618 // Require that the source be a pointer type.
10619 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10620 if (!SrcPtr) return;
10621 QualType SrcPointee = SrcPtr->getPointeeType();
10622
10623 // Whitelist casts from cv void*. We already implicitly
10624 // whitelisted casts to cv void*, since they have alignment 1.
10625 // Also whitelist casts involving incomplete types, which implicitly
10626 // includes 'void'.
10627 if (SrcPointee->isIncompleteType()) return;
10628
10629 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010630
10631 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10632 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10633 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10634 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10635 if (UO->getOpcode() == UO_AddrOf)
10636 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10637 }
10638
John McCall2b5c1b22010-08-12 21:44:57 +000010639 if (SrcAlign >= DestAlign) return;
10640
10641 Diag(TRange.getBegin(), diag::warn_cast_align)
10642 << Op->getType() << T
10643 << static_cast<unsigned>(SrcAlign.getQuantity())
10644 << static_cast<unsigned>(DestAlign.getQuantity())
10645 << TRange << Op->getSourceRange();
10646}
10647
Chandler Carruth28389f02011-08-05 09:10:50 +000010648/// \brief Check whether this array fits the idiom of a size-one tail padded
10649/// array member of a struct.
10650///
10651/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10652/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010653static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010654 const NamedDecl *ND) {
10655 if (Size != 1 || !ND) return false;
10656
10657 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10658 if (!FD) return false;
10659
10660 // Don't consider sizes resulting from macro expansions or template argument
10661 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010662
10663 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010664 while (TInfo) {
10665 TypeLoc TL = TInfo->getTypeLoc();
10666 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010667 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10668 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010669 TInfo = TDL->getTypeSourceInfo();
10670 continue;
10671 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010672 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10673 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010674 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10675 return false;
10676 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010677 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010678 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010679
10680 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010681 if (!RD) return false;
10682 if (RD->isUnion()) return false;
10683 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10684 if (!CRD->isStandardLayout()) return false;
10685 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010686
Benjamin Kramer8c543672011-08-06 03:04:42 +000010687 // See if this is the last field decl in the record.
10688 const Decl *D = FD;
10689 while ((D = D->getNextDeclInContext()))
10690 if (isa<FieldDecl>(D))
10691 return false;
10692 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010693}
10694
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010695void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010696 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010697 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010698 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010699 if (IndexExpr->isValueDependent())
10700 return;
10701
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010702 const Type *EffectiveType =
10703 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010704 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010705 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010706 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010707 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010708 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010709
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010710 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010711 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010712 return;
Richard Smith13f67182011-12-16 19:31:14 +000010713 if (IndexNegated)
10714 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010715
Craig Topperc3ec1492014-05-26 06:22:03 +000010716 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010717 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10718 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010719 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010720 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010721
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010722 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010723 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010724 if (!size.isStrictlyPositive())
10725 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010726
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010727 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010728 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010729 // Make sure we're comparing apples to apples when comparing index to size
10730 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10731 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010732 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010733 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010734 if (ptrarith_typesize != array_typesize) {
10735 // There's a cast to a different size type involved
10736 uint64_t ratio = array_typesize / ptrarith_typesize;
10737 // TODO: Be smarter about handling cases where array_typesize is not a
10738 // multiple of ptrarith_typesize
10739 if (ptrarith_typesize * ratio == array_typesize)
10740 size *= llvm::APInt(size.getBitWidth(), ratio);
10741 }
10742 }
10743
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010744 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010745 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010746 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010747 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010748
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010749 // For array subscripting the index must be less than size, but for pointer
10750 // arithmetic also allow the index (offset) to be equal to size since
10751 // computing the next address after the end of the array is legal and
10752 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010753 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010754 return;
10755
10756 // Also don't warn for arrays of size 1 which are members of some
10757 // structure. These are often used to approximate flexible arrays in C89
10758 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010759 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010760 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010761
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010762 // Suppress the warning if the subscript expression (as identified by the
10763 // ']' location) and the index expression are both from macro expansions
10764 // within a system header.
10765 if (ASE) {
10766 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10767 ASE->getRBracketLoc());
10768 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10769 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10770 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010771 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010772 return;
10773 }
10774 }
10775
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010776 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010777 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010778 DiagID = diag::warn_array_index_exceeds_bounds;
10779
10780 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10781 PDiag(DiagID) << index.toString(10, true)
10782 << size.toString(10, true)
10783 << (unsigned)size.getLimitedValue(~0U)
10784 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010785 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010786 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010787 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010788 DiagID = diag::warn_ptr_arith_precedes_bounds;
10789 if (index.isNegative()) index = -index;
10790 }
10791
10792 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10793 PDiag(DiagID) << index.toString(10, true)
10794 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010795 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010796
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010797 if (!ND) {
10798 // Try harder to find a NamedDecl to point at in the note.
10799 while (const ArraySubscriptExpr *ASE =
10800 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10801 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10802 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10803 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10804 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10805 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10806 }
10807
Chandler Carruth1af88f12011-02-17 21:10:52 +000010808 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010809 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10810 PDiag(diag::note_array_index_out_of_bounds)
10811 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010812}
10813
Ted Kremenekdf26df72011-03-01 18:41:00 +000010814void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010815 int AllowOnePastEnd = 0;
10816 while (expr) {
10817 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010818 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010819 case Stmt::ArraySubscriptExprClass: {
10820 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010821 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010822 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010823 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010824 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010825 case Stmt::OMPArraySectionExprClass: {
10826 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10827 if (ASE->getLowerBound())
10828 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10829 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10830 return;
10831 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010832 case Stmt::UnaryOperatorClass: {
10833 // Only unwrap the * and & unary operators
10834 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10835 expr = UO->getSubExpr();
10836 switch (UO->getOpcode()) {
10837 case UO_AddrOf:
10838 AllowOnePastEnd++;
10839 break;
10840 case UO_Deref:
10841 AllowOnePastEnd--;
10842 break;
10843 default:
10844 return;
10845 }
10846 break;
10847 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010848 case Stmt::ConditionalOperatorClass: {
10849 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10850 if (const Expr *lhs = cond->getLHS())
10851 CheckArrayAccess(lhs);
10852 if (const Expr *rhs = cond->getRHS())
10853 CheckArrayAccess(rhs);
10854 return;
10855 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010856 case Stmt::CXXOperatorCallExprClass: {
10857 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10858 for (const auto *Arg : OCE->arguments())
10859 CheckArrayAccess(Arg);
10860 return;
10861 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010862 default:
10863 return;
10864 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010865 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010866}
John McCall31168b02011-06-15 23:02:42 +000010867
10868//===--- CHECK: Objective-C retain cycles ----------------------------------//
10869
10870namespace {
10871 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010872 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010873 VarDecl *Variable;
10874 SourceRange Range;
10875 SourceLocation Loc;
10876 bool Indirect;
10877
10878 void setLocsFrom(Expr *e) {
10879 Loc = e->getExprLoc();
10880 Range = e->getSourceRange();
10881 }
10882 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010883} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010884
10885/// Consider whether capturing the given variable can possibly lead to
10886/// a retain cycle.
10887static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010888 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010889 // lifetime. In MRR, it's captured strongly if the variable is
10890 // __block and has an appropriate type.
10891 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10892 return false;
10893
10894 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010895 if (ref)
10896 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010897 return true;
10898}
10899
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010900static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010901 while (true) {
10902 e = e->IgnoreParens();
10903 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10904 switch (cast->getCastKind()) {
10905 case CK_BitCast:
10906 case CK_LValueBitCast:
10907 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010908 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010909 e = cast->getSubExpr();
10910 continue;
10911
John McCall31168b02011-06-15 23:02:42 +000010912 default:
10913 return false;
10914 }
10915 }
10916
10917 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10918 ObjCIvarDecl *ivar = ref->getDecl();
10919 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10920 return false;
10921
10922 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010923 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010924 return false;
10925
10926 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10927 owner.Indirect = true;
10928 return true;
10929 }
10930
10931 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10932 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10933 if (!var) return false;
10934 return considerVariable(var, ref, owner);
10935 }
10936
John McCall31168b02011-06-15 23:02:42 +000010937 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10938 if (member->isArrow()) return false;
10939
10940 // Don't count this as an indirect ownership.
10941 e = member->getBase();
10942 continue;
10943 }
10944
John McCallfe96e0b2011-11-06 09:01:30 +000010945 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10946 // Only pay attention to pseudo-objects on property references.
10947 ObjCPropertyRefExpr *pre
10948 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10949 ->IgnoreParens());
10950 if (!pre) return false;
10951 if (pre->isImplicitProperty()) return false;
10952 ObjCPropertyDecl *property = pre->getExplicitProperty();
10953 if (!property->isRetaining() &&
10954 !(property->getPropertyIvarDecl() &&
10955 property->getPropertyIvarDecl()->getType()
10956 .getObjCLifetime() == Qualifiers::OCL_Strong))
10957 return false;
10958
10959 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010960 if (pre->isSuperReceiver()) {
10961 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10962 if (!owner.Variable)
10963 return false;
10964 owner.Loc = pre->getLocation();
10965 owner.Range = pre->getSourceRange();
10966 return true;
10967 }
John McCallfe96e0b2011-11-06 09:01:30 +000010968 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10969 ->getSourceExpr());
10970 continue;
10971 }
10972
John McCall31168b02011-06-15 23:02:42 +000010973 // Array ivars?
10974
10975 return false;
10976 }
10977}
10978
10979namespace {
10980 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10981 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10982 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010983 Context(Context), Variable(variable), Capturer(nullptr),
10984 VarWillBeReased(false) {}
10985 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010986 VarDecl *Variable;
10987 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010988 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010989
10990 void VisitDeclRefExpr(DeclRefExpr *ref) {
10991 if (ref->getDecl() == Variable && !Capturer)
10992 Capturer = ref;
10993 }
10994
John McCall31168b02011-06-15 23:02:42 +000010995 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10996 if (Capturer) return;
10997 Visit(ref->getBase());
10998 if (Capturer && ref->isFreeIvar())
10999 Capturer = ref;
11000 }
11001
11002 void VisitBlockExpr(BlockExpr *block) {
11003 // Look inside nested blocks
11004 if (block->getBlockDecl()->capturesVariable(Variable))
11005 Visit(block->getBlockDecl()->getBody());
11006 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011007
11008 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11009 if (Capturer) return;
11010 if (OVE->getSourceExpr())
11011 Visit(OVE->getSourceExpr());
11012 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011013 void VisitBinaryOperator(BinaryOperator *BinOp) {
11014 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11015 return;
11016 Expr *LHS = BinOp->getLHS();
11017 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11018 if (DRE->getDecl() != Variable)
11019 return;
11020 if (Expr *RHS = BinOp->getRHS()) {
11021 RHS = RHS->IgnoreParenCasts();
11022 llvm::APSInt Value;
11023 VarWillBeReased =
11024 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11025 }
11026 }
11027 }
John McCall31168b02011-06-15 23:02:42 +000011028 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011029} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011030
11031/// Check whether the given argument is a block which captures a
11032/// variable.
11033static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11034 assert(owner.Variable && owner.Loc.isValid());
11035
11036 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011037
11038 // Look through [^{...} copy] and Block_copy(^{...}).
11039 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11040 Selector Cmd = ME->getSelector();
11041 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11042 e = ME->getInstanceReceiver();
11043 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011044 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011045 e = e->IgnoreParenCasts();
11046 }
11047 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11048 if (CE->getNumArgs() == 1) {
11049 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011050 if (Fn) {
11051 const IdentifierInfo *FnI = Fn->getIdentifier();
11052 if (FnI && FnI->isStr("_Block_copy")) {
11053 e = CE->getArg(0)->IgnoreParenCasts();
11054 }
11055 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011056 }
11057 }
11058
John McCall31168b02011-06-15 23:02:42 +000011059 BlockExpr *block = dyn_cast<BlockExpr>(e);
11060 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011061 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011062
11063 FindCaptureVisitor visitor(S.Context, owner.Variable);
11064 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011065 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011066}
11067
11068static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11069 RetainCycleOwner &owner) {
11070 assert(capturer);
11071 assert(owner.Variable && owner.Loc.isValid());
11072
11073 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11074 << owner.Variable << capturer->getSourceRange();
11075 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11076 << owner.Indirect << owner.Range;
11077}
11078
11079/// Check for a keyword selector that starts with the word 'add' or
11080/// 'set'.
11081static bool isSetterLikeSelector(Selector sel) {
11082 if (sel.isUnarySelector()) return false;
11083
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011084 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011085 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011086 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011087 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011088 else if (str.startswith("add")) {
11089 // Specially whitelist 'addOperationWithBlock:'.
11090 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11091 return false;
11092 str = str.substr(3);
11093 }
John McCall31168b02011-06-15 23:02:42 +000011094 else
11095 return false;
11096
11097 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011098 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011099}
11100
Benjamin Kramer3a743452015-03-09 15:03:32 +000011101static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11102 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011103 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11104 Message->getReceiverInterface(),
11105 NSAPI::ClassId_NSMutableArray);
11106 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011107 return None;
11108 }
11109
11110 Selector Sel = Message->getSelector();
11111
11112 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11113 S.NSAPIObj->getNSArrayMethodKind(Sel);
11114 if (!MKOpt) {
11115 return None;
11116 }
11117
11118 NSAPI::NSArrayMethodKind MK = *MKOpt;
11119
11120 switch (MK) {
11121 case NSAPI::NSMutableArr_addObject:
11122 case NSAPI::NSMutableArr_insertObjectAtIndex:
11123 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11124 return 0;
11125 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11126 return 1;
11127
11128 default:
11129 return None;
11130 }
11131
11132 return None;
11133}
11134
11135static
11136Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11137 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011138 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11139 Message->getReceiverInterface(),
11140 NSAPI::ClassId_NSMutableDictionary);
11141 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011142 return None;
11143 }
11144
11145 Selector Sel = Message->getSelector();
11146
11147 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11148 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11149 if (!MKOpt) {
11150 return None;
11151 }
11152
11153 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11154
11155 switch (MK) {
11156 case NSAPI::NSMutableDict_setObjectForKey:
11157 case NSAPI::NSMutableDict_setValueForKey:
11158 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11159 return 0;
11160
11161 default:
11162 return None;
11163 }
11164
11165 return None;
11166}
11167
11168static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011169 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11170 Message->getReceiverInterface(),
11171 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011172
Alex Denisov5dfac812015-08-06 04:51:14 +000011173 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11174 Message->getReceiverInterface(),
11175 NSAPI::ClassId_NSMutableOrderedSet);
11176 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011177 return None;
11178 }
11179
11180 Selector Sel = Message->getSelector();
11181
11182 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11183 if (!MKOpt) {
11184 return None;
11185 }
11186
11187 NSAPI::NSSetMethodKind MK = *MKOpt;
11188
11189 switch (MK) {
11190 case NSAPI::NSMutableSet_addObject:
11191 case NSAPI::NSOrderedSet_setObjectAtIndex:
11192 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11193 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11194 return 0;
11195 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11196 return 1;
11197 }
11198
11199 return None;
11200}
11201
11202void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11203 if (!Message->isInstanceMessage()) {
11204 return;
11205 }
11206
11207 Optional<int> ArgOpt;
11208
11209 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11210 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11211 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11212 return;
11213 }
11214
11215 int ArgIndex = *ArgOpt;
11216
Alex Denisove1d882c2015-03-04 17:55:52 +000011217 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11218 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11219 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11220 }
11221
Alex Denisov5dfac812015-08-06 04:51:14 +000011222 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011223 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011224 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011225 Diag(Message->getSourceRange().getBegin(),
11226 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011227 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011228 }
11229 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011230 } else {
11231 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11232
11233 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11234 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11235 }
11236
11237 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11238 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11239 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11240 ValueDecl *Decl = ReceiverRE->getDecl();
11241 Diag(Message->getSourceRange().getBegin(),
11242 diag::warn_objc_circular_container)
11243 << Decl->getName() << Decl->getName();
11244 if (!ArgRE->isObjCSelfExpr()) {
11245 Diag(Decl->getLocation(),
11246 diag::note_objc_circular_container_declared_here)
11247 << Decl->getName();
11248 }
11249 }
11250 }
11251 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11252 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11253 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11254 ObjCIvarDecl *Decl = IvarRE->getDecl();
11255 Diag(Message->getSourceRange().getBegin(),
11256 diag::warn_objc_circular_container)
11257 << Decl->getName() << Decl->getName();
11258 Diag(Decl->getLocation(),
11259 diag::note_objc_circular_container_declared_here)
11260 << Decl->getName();
11261 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011262 }
11263 }
11264 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011265}
11266
John McCall31168b02011-06-15 23:02:42 +000011267/// Check a message send to see if it's likely to cause a retain cycle.
11268void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11269 // Only check instance methods whose selector looks like a setter.
11270 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11271 return;
11272
11273 // Try to find a variable that the receiver is strongly owned by.
11274 RetainCycleOwner owner;
11275 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011276 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011277 return;
11278 } else {
11279 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11280 owner.Variable = getCurMethodDecl()->getSelfDecl();
11281 owner.Loc = msg->getSuperLoc();
11282 owner.Range = msg->getSuperLoc();
11283 }
11284
11285 // Check whether the receiver is captured by any of the arguments.
11286 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11287 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11288 return diagnoseRetainCycle(*this, capturer, owner);
11289}
11290
11291/// Check a property assign to see if it's likely to cause a retain cycle.
11292void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11293 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011294 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011295 return;
11296
11297 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11298 diagnoseRetainCycle(*this, capturer, owner);
11299}
11300
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011301void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11302 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011304 return;
11305
11306 // Because we don't have an expression for the variable, we have to set the
11307 // location explicitly here.
11308 Owner.Loc = Var->getLocation();
11309 Owner.Range = Var->getSourceRange();
11310
11311 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11312 diagnoseRetainCycle(*this, Capturer, Owner);
11313}
11314
Ted Kremenek9304da92012-12-21 08:04:28 +000011315static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11316 Expr *RHS, bool isProperty) {
11317 // Check if RHS is an Objective-C object literal, which also can get
11318 // immediately zapped in a weak reference. Note that we explicitly
11319 // allow ObjCStringLiterals, since those are designed to never really die.
11320 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011321
Ted Kremenek64873352012-12-21 22:46:35 +000011322 // This enum needs to match with the 'select' in
11323 // warn_objc_arc_literal_assign (off-by-1).
11324 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11325 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11326 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011327
11328 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011329 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011330 << (isProperty ? 0 : 1)
11331 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011332
11333 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011334}
11335
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011336static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11337 Qualifiers::ObjCLifetime LT,
11338 Expr *RHS, bool isProperty) {
11339 // Strip off any implicit cast added to get to the one ARC-specific.
11340 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11341 if (cast->getCastKind() == CK_ARCConsumeObject) {
11342 S.Diag(Loc, diag::warn_arc_retained_assign)
11343 << (LT == Qualifiers::OCL_ExplicitNone)
11344 << (isProperty ? 0 : 1)
11345 << RHS->getSourceRange();
11346 return true;
11347 }
11348 RHS = cast->getSubExpr();
11349 }
11350
11351 if (LT == Qualifiers::OCL_Weak &&
11352 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11353 return true;
11354
11355 return false;
11356}
11357
Ted Kremenekb36234d2012-12-21 08:04:20 +000011358bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11359 QualType LHS, Expr *RHS) {
11360 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11361
11362 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11363 return false;
11364
11365 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11366 return true;
11367
11368 return false;
11369}
11370
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011371void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11372 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011373 QualType LHSType;
11374 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011375 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011376 ObjCPropertyRefExpr *PRE
11377 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11378 if (PRE && !PRE->isImplicitProperty()) {
11379 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11380 if (PD)
11381 LHSType = PD->getType();
11382 }
11383
11384 if (LHSType.isNull())
11385 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011386
11387 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11388
11389 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011390 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011391 getCurFunction()->markSafeWeakUse(LHS);
11392 }
11393
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011394 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11395 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011396
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011397 // FIXME. Check for other life times.
11398 if (LT != Qualifiers::OCL_None)
11399 return;
11400
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011401 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011402 if (PRE->isImplicitProperty())
11403 return;
11404 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11405 if (!PD)
11406 return;
11407
Bill Wendling44426052012-12-20 19:22:21 +000011408 unsigned Attributes = PD->getPropertyAttributes();
11409 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011410 // when 'assign' attribute was not explicitly specified
11411 // by user, ignore it and rely on property type itself
11412 // for lifetime info.
11413 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11414 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11415 LHSType->isObjCRetainableType())
11416 return;
11417
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011418 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011419 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011420 Diag(Loc, diag::warn_arc_retained_property_assign)
11421 << RHS->getSourceRange();
11422 return;
11423 }
11424 RHS = cast->getSubExpr();
11425 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011426 }
Bill Wendling44426052012-12-20 19:22:21 +000011427 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011428 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11429 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011430 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011431 }
11432}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011433
11434//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11435
11436namespace {
11437bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11438 SourceLocation StmtLoc,
11439 const NullStmt *Body) {
11440 // Do not warn if the body is a macro that expands to nothing, e.g:
11441 //
11442 // #define CALL(x)
11443 // if (condition)
11444 // CALL(0);
11445 //
11446 if (Body->hasLeadingEmptyMacro())
11447 return false;
11448
11449 // Get line numbers of statement and body.
11450 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011451 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011452 &StmtLineInvalid);
11453 if (StmtLineInvalid)
11454 return false;
11455
11456 bool BodyLineInvalid;
11457 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11458 &BodyLineInvalid);
11459 if (BodyLineInvalid)
11460 return false;
11461
11462 // Warn if null statement and body are on the same line.
11463 if (StmtLine != BodyLine)
11464 return false;
11465
11466 return true;
11467}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011468} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011469
11470void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11471 const Stmt *Body,
11472 unsigned DiagID) {
11473 // Since this is a syntactic check, don't emit diagnostic for template
11474 // instantiations, this just adds noise.
11475 if (CurrentInstantiationScope)
11476 return;
11477
11478 // The body should be a null statement.
11479 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11480 if (!NBody)
11481 return;
11482
11483 // Do the usual checks.
11484 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11485 return;
11486
11487 Diag(NBody->getSemiLoc(), DiagID);
11488 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11489}
11490
11491void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11492 const Stmt *PossibleBody) {
11493 assert(!CurrentInstantiationScope); // Ensured by caller
11494
11495 SourceLocation StmtLoc;
11496 const Stmt *Body;
11497 unsigned DiagID;
11498 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11499 StmtLoc = FS->getRParenLoc();
11500 Body = FS->getBody();
11501 DiagID = diag::warn_empty_for_body;
11502 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11503 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11504 Body = WS->getBody();
11505 DiagID = diag::warn_empty_while_body;
11506 } else
11507 return; // Neither `for' nor `while'.
11508
11509 // The body should be a null statement.
11510 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11511 if (!NBody)
11512 return;
11513
11514 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011515 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011516 return;
11517
11518 // Do the usual checks.
11519 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11520 return;
11521
11522 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11523 // noise level low, emit diagnostics only if for/while is followed by a
11524 // CompoundStmt, e.g.:
11525 // for (int i = 0; i < n; i++);
11526 // {
11527 // a(i);
11528 // }
11529 // or if for/while is followed by a statement with more indentation
11530 // than for/while itself:
11531 // for (int i = 0; i < n; i++);
11532 // a(i);
11533 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11534 if (!ProbableTypo) {
11535 bool BodyColInvalid;
11536 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11537 PossibleBody->getLocStart(),
11538 &BodyColInvalid);
11539 if (BodyColInvalid)
11540 return;
11541
11542 bool StmtColInvalid;
11543 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11544 S->getLocStart(),
11545 &StmtColInvalid);
11546 if (StmtColInvalid)
11547 return;
11548
11549 if (BodyCol > StmtCol)
11550 ProbableTypo = true;
11551 }
11552
11553 if (ProbableTypo) {
11554 Diag(NBody->getSemiLoc(), DiagID);
11555 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11556 }
11557}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011558
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011559//===--- CHECK: Warn on self move with std::move. -------------------------===//
11560
11561/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11562void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11563 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011564 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11565 return;
11566
Richard Smith51ec0cf2017-02-21 01:17:38 +000011567 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011568 return;
11569
11570 // Strip parens and casts away.
11571 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11572 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11573
11574 // Check for a call expression
11575 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11576 if (!CE || CE->getNumArgs() != 1)
11577 return;
11578
11579 // Check for a call to std::move
11580 const FunctionDecl *FD = CE->getDirectCallee();
11581 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11582 !FD->getIdentifier()->isStr("move"))
11583 return;
11584
11585 // Get argument from std::move
11586 RHSExpr = CE->getArg(0);
11587
11588 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11589 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11590
11591 // Two DeclRefExpr's, check that the decls are the same.
11592 if (LHSDeclRef && RHSDeclRef) {
11593 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11594 return;
11595 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11596 RHSDeclRef->getDecl()->getCanonicalDecl())
11597 return;
11598
11599 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11600 << LHSExpr->getSourceRange()
11601 << RHSExpr->getSourceRange();
11602 return;
11603 }
11604
11605 // Member variables require a different approach to check for self moves.
11606 // MemberExpr's are the same if every nested MemberExpr refers to the same
11607 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11608 // the base Expr's are CXXThisExpr's.
11609 const Expr *LHSBase = LHSExpr;
11610 const Expr *RHSBase = RHSExpr;
11611 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11612 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11613 if (!LHSME || !RHSME)
11614 return;
11615
11616 while (LHSME && RHSME) {
11617 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11618 RHSME->getMemberDecl()->getCanonicalDecl())
11619 return;
11620
11621 LHSBase = LHSME->getBase();
11622 RHSBase = RHSME->getBase();
11623 LHSME = dyn_cast<MemberExpr>(LHSBase);
11624 RHSME = dyn_cast<MemberExpr>(RHSBase);
11625 }
11626
11627 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11628 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11629 if (LHSDeclRef && RHSDeclRef) {
11630 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11631 return;
11632 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11633 RHSDeclRef->getDecl()->getCanonicalDecl())
11634 return;
11635
11636 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11637 << LHSExpr->getSourceRange()
11638 << RHSExpr->getSourceRange();
11639 return;
11640 }
11641
11642 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11643 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11644 << LHSExpr->getSourceRange()
11645 << RHSExpr->getSourceRange();
11646}
11647
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011648//===--- Layout compatibility ----------------------------------------------//
11649
11650namespace {
11651
11652bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11653
11654/// \brief Check if two enumeration types are layout-compatible.
11655bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11656 // C++11 [dcl.enum] p8:
11657 // Two enumeration types are layout-compatible if they have the same
11658 // underlying type.
11659 return ED1->isComplete() && ED2->isComplete() &&
11660 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11661}
11662
11663/// \brief Check if two fields are layout-compatible.
11664bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11665 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11666 return false;
11667
11668 if (Field1->isBitField() != Field2->isBitField())
11669 return false;
11670
11671 if (Field1->isBitField()) {
11672 // Make sure that the bit-fields are the same length.
11673 unsigned Bits1 = Field1->getBitWidthValue(C);
11674 unsigned Bits2 = Field2->getBitWidthValue(C);
11675
11676 if (Bits1 != Bits2)
11677 return false;
11678 }
11679
11680 return true;
11681}
11682
11683/// \brief Check if two standard-layout structs are layout-compatible.
11684/// (C++11 [class.mem] p17)
11685bool isLayoutCompatibleStruct(ASTContext &C,
11686 RecordDecl *RD1,
11687 RecordDecl *RD2) {
11688 // If both records are C++ classes, check that base classes match.
11689 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11690 // If one of records is a CXXRecordDecl we are in C++ mode,
11691 // thus the other one is a CXXRecordDecl, too.
11692 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11693 // Check number of base classes.
11694 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11695 return false;
11696
11697 // Check the base classes.
11698 for (CXXRecordDecl::base_class_const_iterator
11699 Base1 = D1CXX->bases_begin(),
11700 BaseEnd1 = D1CXX->bases_end(),
11701 Base2 = D2CXX->bases_begin();
11702 Base1 != BaseEnd1;
11703 ++Base1, ++Base2) {
11704 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11705 return false;
11706 }
11707 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11708 // If only RD2 is a C++ class, it should have zero base classes.
11709 if (D2CXX->getNumBases() > 0)
11710 return false;
11711 }
11712
11713 // Check the fields.
11714 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11715 Field2End = RD2->field_end(),
11716 Field1 = RD1->field_begin(),
11717 Field1End = RD1->field_end();
11718 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11719 if (!isLayoutCompatible(C, *Field1, *Field2))
11720 return false;
11721 }
11722 if (Field1 != Field1End || Field2 != Field2End)
11723 return false;
11724
11725 return true;
11726}
11727
11728/// \brief Check if two standard-layout unions are layout-compatible.
11729/// (C++11 [class.mem] p18)
11730bool isLayoutCompatibleUnion(ASTContext &C,
11731 RecordDecl *RD1,
11732 RecordDecl *RD2) {
11733 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011734 for (auto *Field2 : RD2->fields())
11735 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011736
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011737 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011738 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11739 I = UnmatchedFields.begin(),
11740 E = UnmatchedFields.end();
11741
11742 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011743 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011744 bool Result = UnmatchedFields.erase(*I);
11745 (void) Result;
11746 assert(Result);
11747 break;
11748 }
11749 }
11750 if (I == E)
11751 return false;
11752 }
11753
11754 return UnmatchedFields.empty();
11755}
11756
11757bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11758 if (RD1->isUnion() != RD2->isUnion())
11759 return false;
11760
11761 if (RD1->isUnion())
11762 return isLayoutCompatibleUnion(C, RD1, RD2);
11763 else
11764 return isLayoutCompatibleStruct(C, RD1, RD2);
11765}
11766
11767/// \brief Check if two types are layout-compatible in C++11 sense.
11768bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11769 if (T1.isNull() || T2.isNull())
11770 return false;
11771
11772 // C++11 [basic.types] p11:
11773 // If two types T1 and T2 are the same type, then T1 and T2 are
11774 // layout-compatible types.
11775 if (C.hasSameType(T1, T2))
11776 return true;
11777
11778 T1 = T1.getCanonicalType().getUnqualifiedType();
11779 T2 = T2.getCanonicalType().getUnqualifiedType();
11780
11781 const Type::TypeClass TC1 = T1->getTypeClass();
11782 const Type::TypeClass TC2 = T2->getTypeClass();
11783
11784 if (TC1 != TC2)
11785 return false;
11786
11787 if (TC1 == Type::Enum) {
11788 return isLayoutCompatible(C,
11789 cast<EnumType>(T1)->getDecl(),
11790 cast<EnumType>(T2)->getDecl());
11791 } else if (TC1 == Type::Record) {
11792 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11793 return false;
11794
11795 return isLayoutCompatible(C,
11796 cast<RecordType>(T1)->getDecl(),
11797 cast<RecordType>(T2)->getDecl());
11798 }
11799
11800 return false;
11801}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011802} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011803
11804//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11805
11806namespace {
11807/// \brief Given a type tag expression find the type tag itself.
11808///
11809/// \param TypeExpr Type tag expression, as it appears in user's code.
11810///
11811/// \param VD Declaration of an identifier that appears in a type tag.
11812///
11813/// \param MagicValue Type tag magic value.
11814bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11815 const ValueDecl **VD, uint64_t *MagicValue) {
11816 while(true) {
11817 if (!TypeExpr)
11818 return false;
11819
11820 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11821
11822 switch (TypeExpr->getStmtClass()) {
11823 case Stmt::UnaryOperatorClass: {
11824 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11825 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11826 TypeExpr = UO->getSubExpr();
11827 continue;
11828 }
11829 return false;
11830 }
11831
11832 case Stmt::DeclRefExprClass: {
11833 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11834 *VD = DRE->getDecl();
11835 return true;
11836 }
11837
11838 case Stmt::IntegerLiteralClass: {
11839 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11840 llvm::APInt MagicValueAPInt = IL->getValue();
11841 if (MagicValueAPInt.getActiveBits() <= 64) {
11842 *MagicValue = MagicValueAPInt.getZExtValue();
11843 return true;
11844 } else
11845 return false;
11846 }
11847
11848 case Stmt::BinaryConditionalOperatorClass:
11849 case Stmt::ConditionalOperatorClass: {
11850 const AbstractConditionalOperator *ACO =
11851 cast<AbstractConditionalOperator>(TypeExpr);
11852 bool Result;
11853 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11854 if (Result)
11855 TypeExpr = ACO->getTrueExpr();
11856 else
11857 TypeExpr = ACO->getFalseExpr();
11858 continue;
11859 }
11860 return false;
11861 }
11862
11863 case Stmt::BinaryOperatorClass: {
11864 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11865 if (BO->getOpcode() == BO_Comma) {
11866 TypeExpr = BO->getRHS();
11867 continue;
11868 }
11869 return false;
11870 }
11871
11872 default:
11873 return false;
11874 }
11875 }
11876}
11877
11878/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11879///
11880/// \param TypeExpr Expression that specifies a type tag.
11881///
11882/// \param MagicValues Registered magic values.
11883///
11884/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11885/// kind.
11886///
11887/// \param TypeInfo Information about the corresponding C type.
11888///
11889/// \returns true if the corresponding C type was found.
11890bool GetMatchingCType(
11891 const IdentifierInfo *ArgumentKind,
11892 const Expr *TypeExpr, const ASTContext &Ctx,
11893 const llvm::DenseMap<Sema::TypeTagMagicValue,
11894 Sema::TypeTagData> *MagicValues,
11895 bool &FoundWrongKind,
11896 Sema::TypeTagData &TypeInfo) {
11897 FoundWrongKind = false;
11898
11899 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011900 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011901
11902 uint64_t MagicValue;
11903
11904 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11905 return false;
11906
11907 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011908 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011909 if (I->getArgumentKind() != ArgumentKind) {
11910 FoundWrongKind = true;
11911 return false;
11912 }
11913 TypeInfo.Type = I->getMatchingCType();
11914 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11915 TypeInfo.MustBeNull = I->getMustBeNull();
11916 return true;
11917 }
11918 return false;
11919 }
11920
11921 if (!MagicValues)
11922 return false;
11923
11924 llvm::DenseMap<Sema::TypeTagMagicValue,
11925 Sema::TypeTagData>::const_iterator I =
11926 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11927 if (I == MagicValues->end())
11928 return false;
11929
11930 TypeInfo = I->second;
11931 return true;
11932}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011933} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011934
11935void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11936 uint64_t MagicValue, QualType Type,
11937 bool LayoutCompatible,
11938 bool MustBeNull) {
11939 if (!TypeTagForDatatypeMagicValues)
11940 TypeTagForDatatypeMagicValues.reset(
11941 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11942
11943 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11944 (*TypeTagForDatatypeMagicValues)[Magic] =
11945 TypeTagData(Type, LayoutCompatible, MustBeNull);
11946}
11947
11948namespace {
11949bool IsSameCharType(QualType T1, QualType T2) {
11950 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11951 if (!BT1)
11952 return false;
11953
11954 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11955 if (!BT2)
11956 return false;
11957
11958 BuiltinType::Kind T1Kind = BT1->getKind();
11959 BuiltinType::Kind T2Kind = BT2->getKind();
11960
11961 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11962 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11963 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11964 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11965}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011966} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011967
11968void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11969 const Expr * const *ExprArgs) {
11970 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11971 bool IsPointerAttr = Attr->getIsPointer();
11972
11973 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11974 bool FoundWrongKind;
11975 TypeTagData TypeInfo;
11976 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11977 TypeTagForDatatypeMagicValues.get(),
11978 FoundWrongKind, TypeInfo)) {
11979 if (FoundWrongKind)
11980 Diag(TypeTagExpr->getExprLoc(),
11981 diag::warn_type_tag_for_datatype_wrong_kind)
11982 << TypeTagExpr->getSourceRange();
11983 return;
11984 }
11985
11986 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11987 if (IsPointerAttr) {
11988 // Skip implicit cast of pointer to `void *' (as a function argument).
11989 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011990 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011991 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011992 ArgumentExpr = ICE->getSubExpr();
11993 }
11994 QualType ArgumentType = ArgumentExpr->getType();
11995
11996 // Passing a `void*' pointer shouldn't trigger a warning.
11997 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11998 return;
11999
12000 if (TypeInfo.MustBeNull) {
12001 // Type tag with matching void type requires a null pointer.
12002 if (!ArgumentExpr->isNullPointerConstant(Context,
12003 Expr::NPC_ValueDependentIsNotNull)) {
12004 Diag(ArgumentExpr->getExprLoc(),
12005 diag::warn_type_safety_null_pointer_required)
12006 << ArgumentKind->getName()
12007 << ArgumentExpr->getSourceRange()
12008 << TypeTagExpr->getSourceRange();
12009 }
12010 return;
12011 }
12012
12013 QualType RequiredType = TypeInfo.Type;
12014 if (IsPointerAttr)
12015 RequiredType = Context.getPointerType(RequiredType);
12016
12017 bool mismatch = false;
12018 if (!TypeInfo.LayoutCompatible) {
12019 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12020
12021 // C++11 [basic.fundamental] p1:
12022 // Plain char, signed char, and unsigned char are three distinct types.
12023 //
12024 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12025 // char' depending on the current char signedness mode.
12026 if (mismatch)
12027 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12028 RequiredType->getPointeeType())) ||
12029 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12030 mismatch = false;
12031 } else
12032 if (IsPointerAttr)
12033 mismatch = !isLayoutCompatible(Context,
12034 ArgumentType->getPointeeType(),
12035 RequiredType->getPointeeType());
12036 else
12037 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12038
12039 if (mismatch)
12040 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012041 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012042 << TypeInfo.LayoutCompatible << RequiredType
12043 << ArgumentExpr->getSourceRange()
12044 << TypeTagExpr->getSourceRange();
12045}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012046
12047void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12048 CharUnits Alignment) {
12049 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12050}
12051
12052void Sema::DiagnoseMisalignedMembers() {
12053 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012054 const NamedDecl *ND = m.RD;
12055 if (ND->getName().empty()) {
12056 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12057 ND = TD;
12058 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012059 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012060 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012061 }
12062 MisalignedMembers.clear();
12063}
12064
12065void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012066 E = E->IgnoreParens();
12067 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012068 return;
12069 if (isa<UnaryOperator>(E) &&
12070 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12071 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12072 if (isa<MemberExpr>(Op)) {
12073 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12074 MisalignedMember(Op));
12075 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012076 (T->isIntegerType() ||
12077 (T->isPointerType() &&
12078 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012079 MisalignedMembers.erase(MA);
12080 }
12081 }
12082}
12083
12084void Sema::RefersToMemberWithReducedAlignment(
12085 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012086 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12087 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012088 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012089 if (!ME)
12090 return;
12091
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012092 // No need to check expressions with an __unaligned-qualified type.
12093 if (E->getType().getQualifiers().hasUnaligned())
12094 return;
12095
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012096 // For a chain of MemberExpr like "a.b.c.d" this list
12097 // will keep FieldDecl's like [d, c, b].
12098 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12099 const MemberExpr *TopME = nullptr;
12100 bool AnyIsPacked = false;
12101 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012102 QualType BaseType = ME->getBase()->getType();
12103 if (ME->isArrow())
12104 BaseType = BaseType->getPointeeType();
12105 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012106 if (RD->isInvalidDecl())
12107 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012108
12109 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012110 auto *FD = dyn_cast<FieldDecl>(MD);
12111 // We do not care about non-data members.
12112 if (!FD || FD->isInvalidDecl())
12113 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012114
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012115 AnyIsPacked =
12116 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12117 ReverseMemberChain.push_back(FD);
12118
12119 TopME = ME;
12120 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12121 } while (ME);
12122 assert(TopME && "We did not compute a topmost MemberExpr!");
12123
12124 // Not the scope of this diagnostic.
12125 if (!AnyIsPacked)
12126 return;
12127
12128 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12129 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12130 // TODO: The innermost base of the member expression may be too complicated.
12131 // For now, just disregard these cases. This is left for future
12132 // improvement.
12133 if (!DRE && !isa<CXXThisExpr>(TopBase))
12134 return;
12135
12136 // Alignment expected by the whole expression.
12137 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12138
12139 // No need to do anything else with this case.
12140 if (ExpectedAlignment.isOne())
12141 return;
12142
12143 // Synthesize offset of the whole access.
12144 CharUnits Offset;
12145 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12146 I++) {
12147 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12148 }
12149
12150 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12151 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12152 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12153
12154 // The base expression of the innermost MemberExpr may give
12155 // stronger guarantees than the class containing the member.
12156 if (DRE && !TopME->isArrow()) {
12157 const ValueDecl *VD = DRE->getDecl();
12158 if (!VD->getType()->isReferenceType())
12159 CompleteObjectAlignment =
12160 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12161 }
12162
12163 // Check if the synthesized offset fulfills the alignment.
12164 if (Offset % ExpectedAlignment != 0 ||
12165 // It may fulfill the offset it but the effective alignment may still be
12166 // lower than the expected expression alignment.
12167 CompleteObjectAlignment < ExpectedAlignment) {
12168 // If this happens, we want to determine a sensible culprit of this.
12169 // Intuitively, watching the chain of member expressions from right to
12170 // left, we start with the required alignment (as required by the field
12171 // type) but some packed attribute in that chain has reduced the alignment.
12172 // It may happen that another packed structure increases it again. But if
12173 // we are here such increase has not been enough. So pointing the first
12174 // FieldDecl that either is packed or else its RecordDecl is,
12175 // seems reasonable.
12176 FieldDecl *FD = nullptr;
12177 CharUnits Alignment;
12178 for (FieldDecl *FDI : ReverseMemberChain) {
12179 if (FDI->hasAttr<PackedAttr>() ||
12180 FDI->getParent()->hasAttr<PackedAttr>()) {
12181 FD = FDI;
12182 Alignment = std::min(
12183 Context.getTypeAlignInChars(FD->getType()),
12184 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12185 break;
12186 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012187 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012188 assert(FD && "We did not find a packed FieldDecl!");
12189 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012190 }
12191}
12192
12193void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12194 using namespace std::placeholders;
12195 RefersToMemberWithReducedAlignment(
12196 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12197 _2, _3, _4));
12198}
12199