blob: 8446601334ee8468ae39220842139c8ffc514b0d [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;
Ted Kremeneka174c522008-07-09 17:58:53 +0000763 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000764 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000765 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000766 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000767 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000768 case Builtin::BI__va_start: {
769 switch (Context.getTargetInfo().getTriple().getArch()) {
770 case llvm::Triple::arm:
771 case llvm::Triple::thumb:
772 if (SemaBuiltinVAStartARM(TheCall))
773 return ExprError();
774 break;
775 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000776 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000777 return ExprError();
778 break;
779 }
780 break;
781 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000782 case Builtin::BI__builtin_isgreater:
783 case Builtin::BI__builtin_isgreaterequal:
784 case Builtin::BI__builtin_isless:
785 case Builtin::BI__builtin_islessequal:
786 case Builtin::BI__builtin_islessgreater:
787 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000788 if (SemaBuiltinUnorderedCompare(TheCall))
789 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000790 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000791 case Builtin::BI__builtin_fpclassify:
792 if (SemaBuiltinFPClassification(TheCall, 6))
793 return ExprError();
794 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000795 case Builtin::BI__builtin_isfinite:
796 case Builtin::BI__builtin_isinf:
797 case Builtin::BI__builtin_isinf_sign:
798 case Builtin::BI__builtin_isnan:
799 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000800 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000801 return ExprError();
802 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000803 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000804 return SemaBuiltinShuffleVector(TheCall);
805 // TheCall will be freed by the smart pointer here, but that's fine, since
806 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000807 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000808 if (SemaBuiltinPrefetch(TheCall))
809 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000810 break;
David Majnemer51169932016-10-31 05:37:48 +0000811 case Builtin::BI__builtin_alloca_with_align:
812 if (SemaBuiltinAllocaWithAlign(TheCall))
813 return ExprError();
814 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000815 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000816 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000817 if (SemaBuiltinAssume(TheCall))
818 return ExprError();
819 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000820 case Builtin::BI__builtin_assume_aligned:
821 if (SemaBuiltinAssumeAligned(TheCall))
822 return ExprError();
823 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000824 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000825 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000826 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000827 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000828 case Builtin::BI__builtin_longjmp:
829 if (SemaBuiltinLongjmp(TheCall))
830 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000831 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000832 case Builtin::BI__builtin_setjmp:
833 if (SemaBuiltinSetjmp(TheCall))
834 return ExprError();
835 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000836 case Builtin::BI_setjmp:
837 case Builtin::BI_setjmpex:
838 if (checkArgCount(*this, TheCall, 1))
839 return true;
840 break;
John McCallbebede42011-02-26 05:39:39 +0000841
842 case Builtin::BI__builtin_classify_type:
843 if (checkArgCount(*this, TheCall, 1)) return true;
844 TheCall->setType(Context.IntTy);
845 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000846 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000847 if (checkArgCount(*this, TheCall, 1)) return true;
848 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000849 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000850 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000851 case Builtin::BI__sync_fetch_and_add_1:
852 case Builtin::BI__sync_fetch_and_add_2:
853 case Builtin::BI__sync_fetch_and_add_4:
854 case Builtin::BI__sync_fetch_and_add_8:
855 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000856 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000857 case Builtin::BI__sync_fetch_and_sub_1:
858 case Builtin::BI__sync_fetch_and_sub_2:
859 case Builtin::BI__sync_fetch_and_sub_4:
860 case Builtin::BI__sync_fetch_and_sub_8:
861 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000862 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000863 case Builtin::BI__sync_fetch_and_or_1:
864 case Builtin::BI__sync_fetch_and_or_2:
865 case Builtin::BI__sync_fetch_and_or_4:
866 case Builtin::BI__sync_fetch_and_or_8:
867 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000868 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000869 case Builtin::BI__sync_fetch_and_and_1:
870 case Builtin::BI__sync_fetch_and_and_2:
871 case Builtin::BI__sync_fetch_and_and_4:
872 case Builtin::BI__sync_fetch_and_and_8:
873 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000874 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000875 case Builtin::BI__sync_fetch_and_xor_1:
876 case Builtin::BI__sync_fetch_and_xor_2:
877 case Builtin::BI__sync_fetch_and_xor_4:
878 case Builtin::BI__sync_fetch_and_xor_8:
879 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000880 case Builtin::BI__sync_fetch_and_nand:
881 case Builtin::BI__sync_fetch_and_nand_1:
882 case Builtin::BI__sync_fetch_and_nand_2:
883 case Builtin::BI__sync_fetch_and_nand_4:
884 case Builtin::BI__sync_fetch_and_nand_8:
885 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000886 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000887 case Builtin::BI__sync_add_and_fetch_1:
888 case Builtin::BI__sync_add_and_fetch_2:
889 case Builtin::BI__sync_add_and_fetch_4:
890 case Builtin::BI__sync_add_and_fetch_8:
891 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000892 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000893 case Builtin::BI__sync_sub_and_fetch_1:
894 case Builtin::BI__sync_sub_and_fetch_2:
895 case Builtin::BI__sync_sub_and_fetch_4:
896 case Builtin::BI__sync_sub_and_fetch_8:
897 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000898 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000899 case Builtin::BI__sync_and_and_fetch_1:
900 case Builtin::BI__sync_and_and_fetch_2:
901 case Builtin::BI__sync_and_and_fetch_4:
902 case Builtin::BI__sync_and_and_fetch_8:
903 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000904 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000905 case Builtin::BI__sync_or_and_fetch_1:
906 case Builtin::BI__sync_or_and_fetch_2:
907 case Builtin::BI__sync_or_and_fetch_4:
908 case Builtin::BI__sync_or_and_fetch_8:
909 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000910 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000911 case Builtin::BI__sync_xor_and_fetch_1:
912 case Builtin::BI__sync_xor_and_fetch_2:
913 case Builtin::BI__sync_xor_and_fetch_4:
914 case Builtin::BI__sync_xor_and_fetch_8:
915 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000916 case Builtin::BI__sync_nand_and_fetch:
917 case Builtin::BI__sync_nand_and_fetch_1:
918 case Builtin::BI__sync_nand_and_fetch_2:
919 case Builtin::BI__sync_nand_and_fetch_4:
920 case Builtin::BI__sync_nand_and_fetch_8:
921 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000922 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000923 case Builtin::BI__sync_val_compare_and_swap_1:
924 case Builtin::BI__sync_val_compare_and_swap_2:
925 case Builtin::BI__sync_val_compare_and_swap_4:
926 case Builtin::BI__sync_val_compare_and_swap_8:
927 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000928 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000929 case Builtin::BI__sync_bool_compare_and_swap_1:
930 case Builtin::BI__sync_bool_compare_and_swap_2:
931 case Builtin::BI__sync_bool_compare_and_swap_4:
932 case Builtin::BI__sync_bool_compare_and_swap_8:
933 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000934 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000935 case Builtin::BI__sync_lock_test_and_set_1:
936 case Builtin::BI__sync_lock_test_and_set_2:
937 case Builtin::BI__sync_lock_test_and_set_4:
938 case Builtin::BI__sync_lock_test_and_set_8:
939 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000940 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000941 case Builtin::BI__sync_lock_release_1:
942 case Builtin::BI__sync_lock_release_2:
943 case Builtin::BI__sync_lock_release_4:
944 case Builtin::BI__sync_lock_release_8:
945 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000946 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000947 case Builtin::BI__sync_swap_1:
948 case Builtin::BI__sync_swap_2:
949 case Builtin::BI__sync_swap_4:
950 case Builtin::BI__sync_swap_8:
951 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000952 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000953 case Builtin::BI__builtin_nontemporal_load:
954 case Builtin::BI__builtin_nontemporal_store:
955 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000956#define BUILTIN(ID, TYPE, ATTRS)
957#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
958 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000959 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000960#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000961 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000962 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000963 return ExprError();
964 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000965 case Builtin::BI__builtin_addressof:
966 if (SemaBuiltinAddressof(*this, TheCall))
967 return ExprError();
968 break;
John McCall03107a42015-10-29 20:48:01 +0000969 case Builtin::BI__builtin_add_overflow:
970 case Builtin::BI__builtin_sub_overflow:
971 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000972 if (SemaBuiltinOverflow(*this, TheCall))
973 return ExprError();
974 break;
Richard Smith760520b2014-06-03 23:27:44 +0000975 case Builtin::BI__builtin_operator_new:
976 case Builtin::BI__builtin_operator_delete:
977 if (!getLangOpts().CPlusPlus) {
978 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
979 << (BuiltinID == Builtin::BI__builtin_operator_new
980 ? "__builtin_operator_new"
981 : "__builtin_operator_delete")
982 << "C++";
983 return ExprError();
984 }
985 // CodeGen assumes it can find the global new and delete to call,
986 // so ensure that they are declared.
987 DeclareGlobalNewDelete();
988 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000989
990 // check secure string manipulation functions where overflows
991 // are detectable at compile time
992 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000993 case Builtin::BI__builtin___memmove_chk:
994 case Builtin::BI__builtin___memset_chk:
995 case Builtin::BI__builtin___strlcat_chk:
996 case Builtin::BI__builtin___strlcpy_chk:
997 case Builtin::BI__builtin___strncat_chk:
998 case Builtin::BI__builtin___strncpy_chk:
999 case Builtin::BI__builtin___stpncpy_chk:
1000 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1001 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001002 case Builtin::BI__builtin___memccpy_chk:
1003 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1004 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001005 case Builtin::BI__builtin___snprintf_chk:
1006 case Builtin::BI__builtin___vsnprintf_chk:
1007 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1008 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001009 case Builtin::BI__builtin_call_with_static_chain:
1010 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1011 return ExprError();
1012 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001013 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001014 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001015 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1016 diag::err_seh___except_block))
1017 return ExprError();
1018 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001019 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001020 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001021 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1022 diag::err_seh___except_filter))
1023 return ExprError();
1024 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001025 case Builtin::BI__GetExceptionInfo:
1026 if (checkArgCount(*this, TheCall, 1))
1027 return ExprError();
1028
1029 if (CheckCXXThrowOperand(
1030 TheCall->getLocStart(),
1031 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1032 TheCall))
1033 return ExprError();
1034
1035 TheCall->setType(Context.VoidPtrTy);
1036 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001037 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001038 case Builtin::BIread_pipe:
1039 case Builtin::BIwrite_pipe:
1040 // Since those two functions are declared with var args, we need a semantic
1041 // check for the argument.
1042 if (SemaBuiltinRWPipe(*this, TheCall))
1043 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001044 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001045 break;
1046 case Builtin::BIreserve_read_pipe:
1047 case Builtin::BIreserve_write_pipe:
1048 case Builtin::BIwork_group_reserve_read_pipe:
1049 case Builtin::BIwork_group_reserve_write_pipe:
1050 case Builtin::BIsub_group_reserve_read_pipe:
1051 case Builtin::BIsub_group_reserve_write_pipe:
1052 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1053 return ExprError();
1054 // Since return type of reserve_read/write_pipe built-in function is
1055 // reserve_id_t, which is not defined in the builtin def file , we used int
1056 // as return type and need to override the return type of these functions.
1057 TheCall->setType(Context.OCLReserveIDTy);
1058 break;
1059 case Builtin::BIcommit_read_pipe:
1060 case Builtin::BIcommit_write_pipe:
1061 case Builtin::BIwork_group_commit_read_pipe:
1062 case Builtin::BIwork_group_commit_write_pipe:
1063 case Builtin::BIsub_group_commit_read_pipe:
1064 case Builtin::BIsub_group_commit_write_pipe:
1065 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1066 return ExprError();
1067 break;
1068 case Builtin::BIget_pipe_num_packets:
1069 case Builtin::BIget_pipe_max_packets:
1070 if (SemaBuiltinPipePackets(*this, TheCall))
1071 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001072 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001073 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001074 case Builtin::BIto_global:
1075 case Builtin::BIto_local:
1076 case Builtin::BIto_private:
1077 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1078 return ExprError();
1079 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001080 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1081 case Builtin::BIenqueue_kernel:
1082 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1083 return ExprError();
1084 break;
1085 case Builtin::BIget_kernel_work_group_size:
1086 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1087 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1088 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001089 break;
1090 case Builtin::BI__builtin_os_log_format:
1091 case Builtin::BI__builtin_os_log_format_buffer_size:
1092 if (SemaBuiltinOSLogFormat(TheCall)) {
1093 return ExprError();
1094 }
1095 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001096 }
Richard Smith760520b2014-06-03 23:27:44 +00001097
Nate Begeman4904e322010-06-08 02:47:44 +00001098 // Since the target specific builtins for each arch overlap, only check those
1099 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001100 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001101 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001102 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001103 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001104 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001105 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001106 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1107 return ExprError();
1108 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001109 case llvm::Triple::aarch64:
1110 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001111 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001112 return ExprError();
1113 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001114 case llvm::Triple::mips:
1115 case llvm::Triple::mipsel:
1116 case llvm::Triple::mips64:
1117 case llvm::Triple::mips64el:
1118 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1119 return ExprError();
1120 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001121 case llvm::Triple::systemz:
1122 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1123 return ExprError();
1124 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001125 case llvm::Triple::x86:
1126 case llvm::Triple::x86_64:
1127 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1128 return ExprError();
1129 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001130 case llvm::Triple::ppc:
1131 case llvm::Triple::ppc64:
1132 case llvm::Triple::ppc64le:
1133 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1134 return ExprError();
1135 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001136 default:
1137 break;
1138 }
1139 }
1140
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001141 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001142}
1143
Nate Begeman91e1fea2010-06-14 05:21:25 +00001144// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001145static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001146 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001147 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001148 switch (Type.getEltType()) {
1149 case NeonTypeFlags::Int8:
1150 case NeonTypeFlags::Poly8:
1151 return shift ? 7 : (8 << IsQuad) - 1;
1152 case NeonTypeFlags::Int16:
1153 case NeonTypeFlags::Poly16:
1154 return shift ? 15 : (4 << IsQuad) - 1;
1155 case NeonTypeFlags::Int32:
1156 return shift ? 31 : (2 << IsQuad) - 1;
1157 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001158 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001159 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001160 case NeonTypeFlags::Poly128:
1161 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001162 case NeonTypeFlags::Float16:
1163 assert(!shift && "cannot shift float types!");
1164 return (4 << IsQuad) - 1;
1165 case NeonTypeFlags::Float32:
1166 assert(!shift && "cannot shift float types!");
1167 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001168 case NeonTypeFlags::Float64:
1169 assert(!shift && "cannot shift float types!");
1170 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001171 }
David Blaikie8a40f702012-01-17 06:56:22 +00001172 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001173}
1174
Bob Wilsone4d77232011-11-08 05:04:11 +00001175/// getNeonEltType - Return the QualType corresponding to the elements of
1176/// the vector type specified by the NeonTypeFlags. This is used to check
1177/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001178static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001179 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001180 switch (Flags.getEltType()) {
1181 case NeonTypeFlags::Int8:
1182 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1183 case NeonTypeFlags::Int16:
1184 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1185 case NeonTypeFlags::Int32:
1186 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1187 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001188 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001189 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1190 else
1191 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1192 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001193 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001194 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001195 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001196 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001197 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001198 if (IsInt64Long)
1199 return Context.UnsignedLongTy;
1200 else
1201 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001202 case NeonTypeFlags::Poly128:
1203 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001204 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001205 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001206 case NeonTypeFlags::Float32:
1207 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001208 case NeonTypeFlags::Float64:
1209 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001210 }
David Blaikie8a40f702012-01-17 06:56:22 +00001211 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001212}
1213
Tim Northover12670412014-02-19 10:37:05 +00001214bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001215 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001216 uint64_t mask = 0;
1217 unsigned TV = 0;
1218 int PtrArgNum = -1;
1219 bool HasConstPtr = false;
1220 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001221#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001222#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001223#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001224 }
1225
1226 // For NEON intrinsics which are overloaded on vector element type, validate
1227 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001228 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001229 if (mask) {
1230 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1231 return true;
1232
1233 TV = Result.getLimitedValue(64);
1234 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1235 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001236 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001237 }
1238
1239 if (PtrArgNum >= 0) {
1240 // Check that pointer arguments have the specified type.
1241 Expr *Arg = TheCall->getArg(PtrArgNum);
1242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1243 Arg = ICE->getSubExpr();
1244 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1245 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001246
Tim Northovera2ee4332014-03-29 15:09:45 +00001247 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001248 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1249 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001250 bool IsInt64Long =
1251 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1252 QualType EltTy =
1253 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001254 if (HasConstPtr)
1255 EltTy = EltTy.withConst();
1256 QualType LHSTy = Context.getPointerType(EltTy);
1257 AssignConvertType ConvTy;
1258 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1259 if (RHS.isInvalid())
1260 return true;
1261 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1262 RHS.get(), AA_Assigning))
1263 return true;
1264 }
1265
1266 // For NEON intrinsics which take an immediate value as part of the
1267 // instruction, range check them here.
1268 unsigned i = 0, l = 0, u = 0;
1269 switch (BuiltinID) {
1270 default:
1271 return false;
Tim Northover12670412014-02-19 10:37:05 +00001272#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001273#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001274#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001275 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001276
Richard Sandiford28940af2014-04-16 08:47:51 +00001277 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001278}
1279
Tim Northovera2ee4332014-03-29 15:09:45 +00001280bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1281 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001282 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001283 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001284 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001285 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001286 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001287 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1288 BuiltinID == AArch64::BI__builtin_arm_strex ||
1289 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001290 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001291 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001292 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1293 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1294 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001295
1296 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1297
1298 // Ensure that we have the proper number of arguments.
1299 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1300 return true;
1301
1302 // Inspect the pointer argument of the atomic builtin. This should always be
1303 // a pointer type, whose element is an integral scalar or pointer type.
1304 // Because it is a pointer type, we don't have to worry about any implicit
1305 // casts here.
1306 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1307 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1308 if (PointerArgRes.isInvalid())
1309 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001310 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001311
1312 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1313 if (!pointerType) {
1314 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1315 << PointerArg->getType() << PointerArg->getSourceRange();
1316 return true;
1317 }
1318
1319 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1320 // task is to insert the appropriate casts into the AST. First work out just
1321 // what the appropriate type is.
1322 QualType ValType = pointerType->getPointeeType();
1323 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1324 if (IsLdrex)
1325 AddrType.addConst();
1326
1327 // Issue a warning if the cast is dodgy.
1328 CastKind CastNeeded = CK_NoOp;
1329 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1330 CastNeeded = CK_BitCast;
1331 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1332 << PointerArg->getType()
1333 << Context.getPointerType(AddrType)
1334 << AA_Passing << PointerArg->getSourceRange();
1335 }
1336
1337 // Finally, do the cast and replace the argument with the corrected version.
1338 AddrType = Context.getPointerType(AddrType);
1339 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1340 if (PointerArgRes.isInvalid())
1341 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001342 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001343
1344 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1345
1346 // In general, we allow ints, floats and pointers to be loaded and stored.
1347 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1348 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1349 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1350 << PointerArg->getType() << PointerArg->getSourceRange();
1351 return true;
1352 }
1353
1354 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001355 if (Context.getTypeSize(ValType) > MaxWidth) {
1356 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001357 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1358 << PointerArg->getType() << PointerArg->getSourceRange();
1359 return true;
1360 }
1361
1362 switch (ValType.getObjCLifetime()) {
1363 case Qualifiers::OCL_None:
1364 case Qualifiers::OCL_ExplicitNone:
1365 // okay
1366 break;
1367
1368 case Qualifiers::OCL_Weak:
1369 case Qualifiers::OCL_Strong:
1370 case Qualifiers::OCL_Autoreleasing:
1371 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1372 << ValType << PointerArg->getSourceRange();
1373 return true;
1374 }
1375
Tim Northover6aacd492013-07-16 09:47:53 +00001376 if (IsLdrex) {
1377 TheCall->setType(ValType);
1378 return false;
1379 }
1380
1381 // Initialize the argument to be stored.
1382 ExprResult ValArg = TheCall->getArg(0);
1383 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1384 Context, ValType, /*consume*/ false);
1385 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1386 if (ValArg.isInvalid())
1387 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001388 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001389
1390 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1391 // but the custom checker bypasses all default analysis.
1392 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001393 return false;
1394}
1395
Nate Begeman4904e322010-06-08 02:47:44 +00001396bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001397 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001398 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1399 BuiltinID == ARM::BI__builtin_arm_strex ||
1400 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001401 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001402 }
1403
Yi Kong26d104a2014-08-13 19:18:14 +00001404 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1405 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1406 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1407 }
1408
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001409 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1410 BuiltinID == ARM::BI__builtin_arm_wsr64)
1411 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1412
1413 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1414 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1415 BuiltinID == ARM::BI__builtin_arm_wsr ||
1416 BuiltinID == ARM::BI__builtin_arm_wsrp)
1417 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1418
Tim Northover12670412014-02-19 10:37:05 +00001419 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1420 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001421
Yi Kong4efadfb2014-07-03 16:01:25 +00001422 // For intrinsics which take an immediate value as part of the instruction,
1423 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001424 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001425 switch (BuiltinID) {
1426 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001427 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1428 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001429 case ARM::BI__builtin_arm_vcvtr_f:
1430 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001431 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001432 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001433 case ARM::BI__builtin_arm_isb:
1434 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001435 }
Nate Begemand773fe62010-06-13 04:47:52 +00001436
Nate Begemanf568b072010-08-03 21:32:34 +00001437 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001438 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001439}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001440
Tim Northover573cbee2014-05-24 12:52:07 +00001441bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001442 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001443 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001444 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1445 BuiltinID == AArch64::BI__builtin_arm_strex ||
1446 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001447 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1448 }
1449
Yi Konga5548432014-08-13 19:18:20 +00001450 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1451 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1452 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1453 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1454 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1455 }
1456
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001457 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1458 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001459 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001460
1461 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1462 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1463 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1466
Tim Northovera2ee4332014-03-29 15:09:45 +00001467 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1468 return true;
1469
Yi Kong19a29ac2014-07-17 10:52:06 +00001470 // For intrinsics which take an immediate value as part of the instruction,
1471 // range check them here.
1472 unsigned i = 0, l = 0, u = 0;
1473 switch (BuiltinID) {
1474 default: return false;
1475 case AArch64::BI__builtin_arm_dmb:
1476 case AArch64::BI__builtin_arm_dsb:
1477 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1478 }
1479
Yi Kong19a29ac2014-07-17 10:52:06 +00001480 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001481}
1482
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001483// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1484// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1485// ordering for DSP is unspecified. MSA is ordered by the data format used
1486// by the underlying instruction i.e., df/m, df/n and then by size.
1487//
1488// FIXME: The size tests here should instead be tablegen'd along with the
1489// definitions from include/clang/Basic/BuiltinsMips.def.
1490// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1491// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001492bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001493 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001494 switch (BuiltinID) {
1495 default: return false;
1496 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1497 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001498 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1499 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1500 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1501 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1502 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001503 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1504 // df/m field.
1505 // These intrinsics take an unsigned 3 bit immediate.
1506 case Mips::BI__builtin_msa_bclri_b:
1507 case Mips::BI__builtin_msa_bnegi_b:
1508 case Mips::BI__builtin_msa_bseti_b:
1509 case Mips::BI__builtin_msa_sat_s_b:
1510 case Mips::BI__builtin_msa_sat_u_b:
1511 case Mips::BI__builtin_msa_slli_b:
1512 case Mips::BI__builtin_msa_srai_b:
1513 case Mips::BI__builtin_msa_srari_b:
1514 case Mips::BI__builtin_msa_srli_b:
1515 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1516 case Mips::BI__builtin_msa_binsli_b:
1517 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1518 // These intrinsics take an unsigned 4 bit immediate.
1519 case Mips::BI__builtin_msa_bclri_h:
1520 case Mips::BI__builtin_msa_bnegi_h:
1521 case Mips::BI__builtin_msa_bseti_h:
1522 case Mips::BI__builtin_msa_sat_s_h:
1523 case Mips::BI__builtin_msa_sat_u_h:
1524 case Mips::BI__builtin_msa_slli_h:
1525 case Mips::BI__builtin_msa_srai_h:
1526 case Mips::BI__builtin_msa_srari_h:
1527 case Mips::BI__builtin_msa_srli_h:
1528 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1529 case Mips::BI__builtin_msa_binsli_h:
1530 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1531 // These intrinsics take an unsigned 5 bit immedate.
1532 // The first block of intrinsics actually have an unsigned 5 bit field,
1533 // not a df/n field.
1534 case Mips::BI__builtin_msa_clei_u_b:
1535 case Mips::BI__builtin_msa_clei_u_h:
1536 case Mips::BI__builtin_msa_clei_u_w:
1537 case Mips::BI__builtin_msa_clei_u_d:
1538 case Mips::BI__builtin_msa_clti_u_b:
1539 case Mips::BI__builtin_msa_clti_u_h:
1540 case Mips::BI__builtin_msa_clti_u_w:
1541 case Mips::BI__builtin_msa_clti_u_d:
1542 case Mips::BI__builtin_msa_maxi_u_b:
1543 case Mips::BI__builtin_msa_maxi_u_h:
1544 case Mips::BI__builtin_msa_maxi_u_w:
1545 case Mips::BI__builtin_msa_maxi_u_d:
1546 case Mips::BI__builtin_msa_mini_u_b:
1547 case Mips::BI__builtin_msa_mini_u_h:
1548 case Mips::BI__builtin_msa_mini_u_w:
1549 case Mips::BI__builtin_msa_mini_u_d:
1550 case Mips::BI__builtin_msa_addvi_b:
1551 case Mips::BI__builtin_msa_addvi_h:
1552 case Mips::BI__builtin_msa_addvi_w:
1553 case Mips::BI__builtin_msa_addvi_d:
1554 case Mips::BI__builtin_msa_bclri_w:
1555 case Mips::BI__builtin_msa_bnegi_w:
1556 case Mips::BI__builtin_msa_bseti_w:
1557 case Mips::BI__builtin_msa_sat_s_w:
1558 case Mips::BI__builtin_msa_sat_u_w:
1559 case Mips::BI__builtin_msa_slli_w:
1560 case Mips::BI__builtin_msa_srai_w:
1561 case Mips::BI__builtin_msa_srari_w:
1562 case Mips::BI__builtin_msa_srli_w:
1563 case Mips::BI__builtin_msa_srlri_w:
1564 case Mips::BI__builtin_msa_subvi_b:
1565 case Mips::BI__builtin_msa_subvi_h:
1566 case Mips::BI__builtin_msa_subvi_w:
1567 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1568 case Mips::BI__builtin_msa_binsli_w:
1569 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1570 // These intrinsics take an unsigned 6 bit immediate.
1571 case Mips::BI__builtin_msa_bclri_d:
1572 case Mips::BI__builtin_msa_bnegi_d:
1573 case Mips::BI__builtin_msa_bseti_d:
1574 case Mips::BI__builtin_msa_sat_s_d:
1575 case Mips::BI__builtin_msa_sat_u_d:
1576 case Mips::BI__builtin_msa_slli_d:
1577 case Mips::BI__builtin_msa_srai_d:
1578 case Mips::BI__builtin_msa_srari_d:
1579 case Mips::BI__builtin_msa_srli_d:
1580 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1581 case Mips::BI__builtin_msa_binsli_d:
1582 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1583 // These intrinsics take a signed 5 bit immediate.
1584 case Mips::BI__builtin_msa_ceqi_b:
1585 case Mips::BI__builtin_msa_ceqi_h:
1586 case Mips::BI__builtin_msa_ceqi_w:
1587 case Mips::BI__builtin_msa_ceqi_d:
1588 case Mips::BI__builtin_msa_clti_s_b:
1589 case Mips::BI__builtin_msa_clti_s_h:
1590 case Mips::BI__builtin_msa_clti_s_w:
1591 case Mips::BI__builtin_msa_clti_s_d:
1592 case Mips::BI__builtin_msa_clei_s_b:
1593 case Mips::BI__builtin_msa_clei_s_h:
1594 case Mips::BI__builtin_msa_clei_s_w:
1595 case Mips::BI__builtin_msa_clei_s_d:
1596 case Mips::BI__builtin_msa_maxi_s_b:
1597 case Mips::BI__builtin_msa_maxi_s_h:
1598 case Mips::BI__builtin_msa_maxi_s_w:
1599 case Mips::BI__builtin_msa_maxi_s_d:
1600 case Mips::BI__builtin_msa_mini_s_b:
1601 case Mips::BI__builtin_msa_mini_s_h:
1602 case Mips::BI__builtin_msa_mini_s_w:
1603 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1604 // These intrinsics take an unsigned 8 bit immediate.
1605 case Mips::BI__builtin_msa_andi_b:
1606 case Mips::BI__builtin_msa_nori_b:
1607 case Mips::BI__builtin_msa_ori_b:
1608 case Mips::BI__builtin_msa_shf_b:
1609 case Mips::BI__builtin_msa_shf_h:
1610 case Mips::BI__builtin_msa_shf_w:
1611 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1612 case Mips::BI__builtin_msa_bseli_b:
1613 case Mips::BI__builtin_msa_bmnzi_b:
1614 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1615 // df/n format
1616 // These intrinsics take an unsigned 4 bit immediate.
1617 case Mips::BI__builtin_msa_copy_s_b:
1618 case Mips::BI__builtin_msa_copy_u_b:
1619 case Mips::BI__builtin_msa_insve_b:
1620 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001621 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1622 // These intrinsics take an unsigned 3 bit immediate.
1623 case Mips::BI__builtin_msa_copy_s_h:
1624 case Mips::BI__builtin_msa_copy_u_h:
1625 case Mips::BI__builtin_msa_insve_h:
1626 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001627 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1628 // These intrinsics take an unsigned 2 bit immediate.
1629 case Mips::BI__builtin_msa_copy_s_w:
1630 case Mips::BI__builtin_msa_copy_u_w:
1631 case Mips::BI__builtin_msa_insve_w:
1632 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001633 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1634 // These intrinsics take an unsigned 1 bit immediate.
1635 case Mips::BI__builtin_msa_copy_s_d:
1636 case Mips::BI__builtin_msa_copy_u_d:
1637 case Mips::BI__builtin_msa_insve_d:
1638 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001639 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1640 // Memory offsets and immediate loads.
1641 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001642 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001643 case Mips::BI__builtin_msa_ldi_h:
1644 case Mips::BI__builtin_msa_ldi_w:
1645 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1646 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1647 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1648 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1649 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1650 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1651 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1652 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1653 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001654 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001655
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001656 if (!m)
1657 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1658
1659 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1660 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001661}
1662
Kit Bartone50adcb2015-03-30 19:40:59 +00001663bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1664 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001665 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1666 BuiltinID == PPC::BI__builtin_divdeu ||
1667 BuiltinID == PPC::BI__builtin_bpermd;
1668 bool IsTarget64Bit = Context.getTargetInfo()
1669 .getTypeWidth(Context
1670 .getTargetInfo()
1671 .getIntPtrType()) == 64;
1672 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1673 BuiltinID == PPC::BI__builtin_divweu ||
1674 BuiltinID == PPC::BI__builtin_divde ||
1675 BuiltinID == PPC::BI__builtin_divdeu;
1676
1677 if (Is64BitBltin && !IsTarget64Bit)
1678 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1679 << TheCall->getSourceRange();
1680
1681 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1682 (BuiltinID == PPC::BI__builtin_bpermd &&
1683 !Context.getTargetInfo().hasFeature("bpermd")))
1684 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1685 << TheCall->getSourceRange();
1686
Kit Bartone50adcb2015-03-30 19:40:59 +00001687 switch (BuiltinID) {
1688 default: return false;
1689 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1690 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1691 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1692 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1693 case PPC::BI__builtin_tbegin:
1694 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1695 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1696 case PPC::BI__builtin_tabortwc:
1697 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1698 case PPC::BI__builtin_tabortwci:
1699 case PPC::BI__builtin_tabortdci:
1700 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1701 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001702 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001703 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001704 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001705 }
1706 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1707}
1708
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001709bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1710 CallExpr *TheCall) {
1711 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1712 Expr *Arg = TheCall->getArg(0);
1713 llvm::APSInt AbortCode(32);
1714 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1715 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1716 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1717 << Arg->getSourceRange();
1718 }
1719
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001720 // For intrinsics which take an immediate value as part of the instruction,
1721 // range check them here.
1722 unsigned i = 0, l = 0, u = 0;
1723 switch (BuiltinID) {
1724 default: return false;
1725 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1726 case SystemZ::BI__builtin_s390_verimb:
1727 case SystemZ::BI__builtin_s390_verimh:
1728 case SystemZ::BI__builtin_s390_verimf:
1729 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1730 case SystemZ::BI__builtin_s390_vfaeb:
1731 case SystemZ::BI__builtin_s390_vfaeh:
1732 case SystemZ::BI__builtin_s390_vfaef:
1733 case SystemZ::BI__builtin_s390_vfaebs:
1734 case SystemZ::BI__builtin_s390_vfaehs:
1735 case SystemZ::BI__builtin_s390_vfaefs:
1736 case SystemZ::BI__builtin_s390_vfaezb:
1737 case SystemZ::BI__builtin_s390_vfaezh:
1738 case SystemZ::BI__builtin_s390_vfaezf:
1739 case SystemZ::BI__builtin_s390_vfaezbs:
1740 case SystemZ::BI__builtin_s390_vfaezhs:
1741 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1742 case SystemZ::BI__builtin_s390_vfidb:
1743 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1744 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1745 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1746 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1747 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1748 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1749 case SystemZ::BI__builtin_s390_vstrcb:
1750 case SystemZ::BI__builtin_s390_vstrch:
1751 case SystemZ::BI__builtin_s390_vstrcf:
1752 case SystemZ::BI__builtin_s390_vstrczb:
1753 case SystemZ::BI__builtin_s390_vstrczh:
1754 case SystemZ::BI__builtin_s390_vstrczf:
1755 case SystemZ::BI__builtin_s390_vstrcbs:
1756 case SystemZ::BI__builtin_s390_vstrchs:
1757 case SystemZ::BI__builtin_s390_vstrcfs:
1758 case SystemZ::BI__builtin_s390_vstrczbs:
1759 case SystemZ::BI__builtin_s390_vstrczhs:
1760 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1761 }
1762 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001763}
1764
Craig Topper5ba2c502015-11-07 08:08:31 +00001765/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1766/// This checks that the target supports __builtin_cpu_supports and
1767/// that the string argument is constant and valid.
1768static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1769 Expr *Arg = TheCall->getArg(0);
1770
1771 // Check if the argument is a string literal.
1772 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1773 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1774 << Arg->getSourceRange();
1775
1776 // Check the contents of the string.
1777 StringRef Feature =
1778 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1779 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1780 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1781 << Arg->getSourceRange();
1782 return false;
1783}
1784
Craig Toppera7e253e2016-09-23 04:48:31 +00001785// Check if the rounding mode is legal.
1786bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1787 // Indicates if this instruction has rounding control or just SAE.
1788 bool HasRC = false;
1789
1790 unsigned ArgNum = 0;
1791 switch (BuiltinID) {
1792 default:
1793 return false;
1794 case X86::BI__builtin_ia32_vcvttsd2si32:
1795 case X86::BI__builtin_ia32_vcvttsd2si64:
1796 case X86::BI__builtin_ia32_vcvttsd2usi32:
1797 case X86::BI__builtin_ia32_vcvttsd2usi64:
1798 case X86::BI__builtin_ia32_vcvttss2si32:
1799 case X86::BI__builtin_ia32_vcvttss2si64:
1800 case X86::BI__builtin_ia32_vcvttss2usi32:
1801 case X86::BI__builtin_ia32_vcvttss2usi64:
1802 ArgNum = 1;
1803 break;
1804 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1805 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1806 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1807 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1808 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1809 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1810 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1811 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1812 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1813 case X86::BI__builtin_ia32_exp2pd_mask:
1814 case X86::BI__builtin_ia32_exp2ps_mask:
1815 case X86::BI__builtin_ia32_getexppd512_mask:
1816 case X86::BI__builtin_ia32_getexpps512_mask:
1817 case X86::BI__builtin_ia32_rcp28pd_mask:
1818 case X86::BI__builtin_ia32_rcp28ps_mask:
1819 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1820 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1821 case X86::BI__builtin_ia32_vcomisd:
1822 case X86::BI__builtin_ia32_vcomiss:
1823 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1824 ArgNum = 3;
1825 break;
1826 case X86::BI__builtin_ia32_cmppd512_mask:
1827 case X86::BI__builtin_ia32_cmpps512_mask:
1828 case X86::BI__builtin_ia32_cmpsd_mask:
1829 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001830 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001831 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1832 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001833 case X86::BI__builtin_ia32_maxpd512_mask:
1834 case X86::BI__builtin_ia32_maxps512_mask:
1835 case X86::BI__builtin_ia32_maxsd_round_mask:
1836 case X86::BI__builtin_ia32_maxss_round_mask:
1837 case X86::BI__builtin_ia32_minpd512_mask:
1838 case X86::BI__builtin_ia32_minps512_mask:
1839 case X86::BI__builtin_ia32_minsd_round_mask:
1840 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001841 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1842 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1843 case X86::BI__builtin_ia32_reducepd512_mask:
1844 case X86::BI__builtin_ia32_reduceps512_mask:
1845 case X86::BI__builtin_ia32_rndscalepd_mask:
1846 case X86::BI__builtin_ia32_rndscaleps_mask:
1847 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1848 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1849 ArgNum = 4;
1850 break;
1851 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001852 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001853 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001854 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001855 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001856 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001857 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001858 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001859 case X86::BI__builtin_ia32_rangepd512_mask:
1860 case X86::BI__builtin_ia32_rangeps512_mask:
1861 case X86::BI__builtin_ia32_rangesd128_round_mask:
1862 case X86::BI__builtin_ia32_rangess128_round_mask:
1863 case X86::BI__builtin_ia32_reducesd_mask:
1864 case X86::BI__builtin_ia32_reducess_mask:
1865 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1866 case X86::BI__builtin_ia32_rndscaless_round_mask:
1867 ArgNum = 5;
1868 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001869 case X86::BI__builtin_ia32_vcvtsd2si64:
1870 case X86::BI__builtin_ia32_vcvtsd2si32:
1871 case X86::BI__builtin_ia32_vcvtsd2usi32:
1872 case X86::BI__builtin_ia32_vcvtsd2usi64:
1873 case X86::BI__builtin_ia32_vcvtss2si32:
1874 case X86::BI__builtin_ia32_vcvtss2si64:
1875 case X86::BI__builtin_ia32_vcvtss2usi32:
1876 case X86::BI__builtin_ia32_vcvtss2usi64:
1877 ArgNum = 1;
1878 HasRC = true;
1879 break;
Craig Topper8e066312016-11-07 07:01:09 +00001880 case X86::BI__builtin_ia32_cvtsi2sd64:
1881 case X86::BI__builtin_ia32_cvtsi2ss32:
1882 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001883 case X86::BI__builtin_ia32_cvtusi2sd64:
1884 case X86::BI__builtin_ia32_cvtusi2ss32:
1885 case X86::BI__builtin_ia32_cvtusi2ss64:
1886 ArgNum = 2;
1887 HasRC = true;
1888 break;
1889 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1890 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1891 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1892 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1893 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1894 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1895 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1896 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1897 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1898 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1899 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001900 case X86::BI__builtin_ia32_sqrtpd512_mask:
1901 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001902 ArgNum = 3;
1903 HasRC = true;
1904 break;
1905 case X86::BI__builtin_ia32_addpd512_mask:
1906 case X86::BI__builtin_ia32_addps512_mask:
1907 case X86::BI__builtin_ia32_divpd512_mask:
1908 case X86::BI__builtin_ia32_divps512_mask:
1909 case X86::BI__builtin_ia32_mulpd512_mask:
1910 case X86::BI__builtin_ia32_mulps512_mask:
1911 case X86::BI__builtin_ia32_subpd512_mask:
1912 case X86::BI__builtin_ia32_subps512_mask:
1913 case X86::BI__builtin_ia32_addss_round_mask:
1914 case X86::BI__builtin_ia32_addsd_round_mask:
1915 case X86::BI__builtin_ia32_divss_round_mask:
1916 case X86::BI__builtin_ia32_divsd_round_mask:
1917 case X86::BI__builtin_ia32_mulss_round_mask:
1918 case X86::BI__builtin_ia32_mulsd_round_mask:
1919 case X86::BI__builtin_ia32_subss_round_mask:
1920 case X86::BI__builtin_ia32_subsd_round_mask:
1921 case X86::BI__builtin_ia32_scalefpd512_mask:
1922 case X86::BI__builtin_ia32_scalefps512_mask:
1923 case X86::BI__builtin_ia32_scalefsd_round_mask:
1924 case X86::BI__builtin_ia32_scalefss_round_mask:
1925 case X86::BI__builtin_ia32_getmantpd512_mask:
1926 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001927 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1928 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1929 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001930 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1931 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1932 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1933 case X86::BI__builtin_ia32_vfmaddps512_mask:
1934 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1935 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1936 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1937 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1938 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1939 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1940 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1941 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1942 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1943 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1944 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1945 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1946 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1947 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1948 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1949 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1950 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1951 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1952 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1953 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1954 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1955 case X86::BI__builtin_ia32_vfmaddss3_mask:
1956 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1957 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1958 ArgNum = 4;
1959 HasRC = true;
1960 break;
1961 case X86::BI__builtin_ia32_getmantsd_round_mask:
1962 case X86::BI__builtin_ia32_getmantss_round_mask:
1963 ArgNum = 5;
1964 HasRC = true;
1965 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00001966 }
1967
1968 llvm::APSInt Result;
1969
1970 // We can't check the value of a dependent argument.
1971 Expr *Arg = TheCall->getArg(ArgNum);
1972 if (Arg->isTypeDependent() || Arg->isValueDependent())
1973 return false;
1974
1975 // Check constant-ness first.
1976 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1977 return true;
1978
1979 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1980 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1981 // combined with ROUND_NO_EXC.
1982 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1983 Result == 8/*ROUND_NO_EXC*/ ||
1984 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1985 return false;
1986
1987 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1988 << Arg->getSourceRange();
1989}
1990
Craig Topperdf5beb22017-03-13 17:16:50 +00001991// Check if the gather/scatter scale is legal.
1992bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
1993 CallExpr *TheCall) {
1994 unsigned ArgNum = 0;
1995 switch (BuiltinID) {
1996 default:
1997 return false;
1998 case X86::BI__builtin_ia32_gatherpfdpd:
1999 case X86::BI__builtin_ia32_gatherpfdps:
2000 case X86::BI__builtin_ia32_gatherpfqpd:
2001 case X86::BI__builtin_ia32_gatherpfqps:
2002 case X86::BI__builtin_ia32_scatterpfdpd:
2003 case X86::BI__builtin_ia32_scatterpfdps:
2004 case X86::BI__builtin_ia32_scatterpfqpd:
2005 case X86::BI__builtin_ia32_scatterpfqps:
2006 ArgNum = 3;
2007 break;
2008 case X86::BI__builtin_ia32_gatherd_pd:
2009 case X86::BI__builtin_ia32_gatherd_pd256:
2010 case X86::BI__builtin_ia32_gatherq_pd:
2011 case X86::BI__builtin_ia32_gatherq_pd256:
2012 case X86::BI__builtin_ia32_gatherd_ps:
2013 case X86::BI__builtin_ia32_gatherd_ps256:
2014 case X86::BI__builtin_ia32_gatherq_ps:
2015 case X86::BI__builtin_ia32_gatherq_ps256:
2016 case X86::BI__builtin_ia32_gatherd_q:
2017 case X86::BI__builtin_ia32_gatherd_q256:
2018 case X86::BI__builtin_ia32_gatherq_q:
2019 case X86::BI__builtin_ia32_gatherq_q256:
2020 case X86::BI__builtin_ia32_gatherd_d:
2021 case X86::BI__builtin_ia32_gatherd_d256:
2022 case X86::BI__builtin_ia32_gatherq_d:
2023 case X86::BI__builtin_ia32_gatherq_d256:
2024 case X86::BI__builtin_ia32_gather3div2df:
2025 case X86::BI__builtin_ia32_gather3div2di:
2026 case X86::BI__builtin_ia32_gather3div4df:
2027 case X86::BI__builtin_ia32_gather3div4di:
2028 case X86::BI__builtin_ia32_gather3div4sf:
2029 case X86::BI__builtin_ia32_gather3div4si:
2030 case X86::BI__builtin_ia32_gather3div8sf:
2031 case X86::BI__builtin_ia32_gather3div8si:
2032 case X86::BI__builtin_ia32_gather3siv2df:
2033 case X86::BI__builtin_ia32_gather3siv2di:
2034 case X86::BI__builtin_ia32_gather3siv4df:
2035 case X86::BI__builtin_ia32_gather3siv4di:
2036 case X86::BI__builtin_ia32_gather3siv4sf:
2037 case X86::BI__builtin_ia32_gather3siv4si:
2038 case X86::BI__builtin_ia32_gather3siv8sf:
2039 case X86::BI__builtin_ia32_gather3siv8si:
2040 case X86::BI__builtin_ia32_gathersiv8df:
2041 case X86::BI__builtin_ia32_gathersiv16sf:
2042 case X86::BI__builtin_ia32_gatherdiv8df:
2043 case X86::BI__builtin_ia32_gatherdiv16sf:
2044 case X86::BI__builtin_ia32_gathersiv8di:
2045 case X86::BI__builtin_ia32_gathersiv16si:
2046 case X86::BI__builtin_ia32_gatherdiv8di:
2047 case X86::BI__builtin_ia32_gatherdiv16si:
2048 case X86::BI__builtin_ia32_scatterdiv2df:
2049 case X86::BI__builtin_ia32_scatterdiv2di:
2050 case X86::BI__builtin_ia32_scatterdiv4df:
2051 case X86::BI__builtin_ia32_scatterdiv4di:
2052 case X86::BI__builtin_ia32_scatterdiv4sf:
2053 case X86::BI__builtin_ia32_scatterdiv4si:
2054 case X86::BI__builtin_ia32_scatterdiv8sf:
2055 case X86::BI__builtin_ia32_scatterdiv8si:
2056 case X86::BI__builtin_ia32_scattersiv2df:
2057 case X86::BI__builtin_ia32_scattersiv2di:
2058 case X86::BI__builtin_ia32_scattersiv4df:
2059 case X86::BI__builtin_ia32_scattersiv4di:
2060 case X86::BI__builtin_ia32_scattersiv4sf:
2061 case X86::BI__builtin_ia32_scattersiv4si:
2062 case X86::BI__builtin_ia32_scattersiv8sf:
2063 case X86::BI__builtin_ia32_scattersiv8si:
2064 case X86::BI__builtin_ia32_scattersiv8df:
2065 case X86::BI__builtin_ia32_scattersiv16sf:
2066 case X86::BI__builtin_ia32_scatterdiv8df:
2067 case X86::BI__builtin_ia32_scatterdiv16sf:
2068 case X86::BI__builtin_ia32_scattersiv8di:
2069 case X86::BI__builtin_ia32_scattersiv16si:
2070 case X86::BI__builtin_ia32_scatterdiv8di:
2071 case X86::BI__builtin_ia32_scatterdiv16si:
2072 ArgNum = 4;
2073 break;
2074 }
2075
2076 llvm::APSInt Result;
2077
2078 // We can't check the value of a dependent argument.
2079 Expr *Arg = TheCall->getArg(ArgNum);
2080 if (Arg->isTypeDependent() || Arg->isValueDependent())
2081 return false;
2082
2083 // Check constant-ness first.
2084 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2085 return true;
2086
2087 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2088 return false;
2089
2090 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2091 << Arg->getSourceRange();
2092}
2093
Craig Topperf0ddc892016-09-23 04:48:27 +00002094bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2095 if (BuiltinID == X86::BI__builtin_cpu_supports)
2096 return SemaBuiltinCpuSupports(*this, TheCall);
2097
2098 if (BuiltinID == X86::BI__builtin_ms_va_start)
Reid Kleckner2b0fa122017-05-02 20:10:03 +00002099 return SemaBuiltinVAStart(BuiltinID, TheCall);
Craig Topperf0ddc892016-09-23 04:48:27 +00002100
Craig Toppera7e253e2016-09-23 04:48:31 +00002101 // If the intrinsic has rounding or SAE make sure its valid.
2102 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2103 return true;
2104
Craig Topperdf5beb22017-03-13 17:16:50 +00002105 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2106 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2107 return true;
2108
Craig Topperf0ddc892016-09-23 04:48:27 +00002109 // For intrinsics which take an immediate value as part of the instruction,
2110 // range check them here.
2111 int i = 0, l = 0, u = 0;
2112 switch (BuiltinID) {
2113 default:
2114 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002115 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002116 i = 1; l = 0; u = 3;
2117 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002118 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002119 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2120 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2121 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2122 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002123 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002124 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002125 case X86::BI__builtin_ia32_vpermil2pd:
2126 case X86::BI__builtin_ia32_vpermil2pd256:
2127 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002128 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002129 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002130 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002131 case X86::BI__builtin_ia32_cmpb128_mask:
2132 case X86::BI__builtin_ia32_cmpw128_mask:
2133 case X86::BI__builtin_ia32_cmpd128_mask:
2134 case X86::BI__builtin_ia32_cmpq128_mask:
2135 case X86::BI__builtin_ia32_cmpb256_mask:
2136 case X86::BI__builtin_ia32_cmpw256_mask:
2137 case X86::BI__builtin_ia32_cmpd256_mask:
2138 case X86::BI__builtin_ia32_cmpq256_mask:
2139 case X86::BI__builtin_ia32_cmpb512_mask:
2140 case X86::BI__builtin_ia32_cmpw512_mask:
2141 case X86::BI__builtin_ia32_cmpd512_mask:
2142 case X86::BI__builtin_ia32_cmpq512_mask:
2143 case X86::BI__builtin_ia32_ucmpb128_mask:
2144 case X86::BI__builtin_ia32_ucmpw128_mask:
2145 case X86::BI__builtin_ia32_ucmpd128_mask:
2146 case X86::BI__builtin_ia32_ucmpq128_mask:
2147 case X86::BI__builtin_ia32_ucmpb256_mask:
2148 case X86::BI__builtin_ia32_ucmpw256_mask:
2149 case X86::BI__builtin_ia32_ucmpd256_mask:
2150 case X86::BI__builtin_ia32_ucmpq256_mask:
2151 case X86::BI__builtin_ia32_ucmpb512_mask:
2152 case X86::BI__builtin_ia32_ucmpw512_mask:
2153 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002154 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002155 case X86::BI__builtin_ia32_vpcomub:
2156 case X86::BI__builtin_ia32_vpcomuw:
2157 case X86::BI__builtin_ia32_vpcomud:
2158 case X86::BI__builtin_ia32_vpcomuq:
2159 case X86::BI__builtin_ia32_vpcomb:
2160 case X86::BI__builtin_ia32_vpcomw:
2161 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002162 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002163 i = 2; l = 0; u = 7;
2164 break;
2165 case X86::BI__builtin_ia32_roundps:
2166 case X86::BI__builtin_ia32_roundpd:
2167 case X86::BI__builtin_ia32_roundps256:
2168 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002169 i = 1; l = 0; u = 15;
2170 break;
2171 case X86::BI__builtin_ia32_roundss:
2172 case X86::BI__builtin_ia32_roundsd:
2173 case X86::BI__builtin_ia32_rangepd128_mask:
2174 case X86::BI__builtin_ia32_rangepd256_mask:
2175 case X86::BI__builtin_ia32_rangepd512_mask:
2176 case X86::BI__builtin_ia32_rangeps128_mask:
2177 case X86::BI__builtin_ia32_rangeps256_mask:
2178 case X86::BI__builtin_ia32_rangeps512_mask:
2179 case X86::BI__builtin_ia32_getmantsd_round_mask:
2180 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002181 i = 2; l = 0; u = 15;
2182 break;
2183 case X86::BI__builtin_ia32_cmpps:
2184 case X86::BI__builtin_ia32_cmpss:
2185 case X86::BI__builtin_ia32_cmppd:
2186 case X86::BI__builtin_ia32_cmpsd:
2187 case X86::BI__builtin_ia32_cmpps256:
2188 case X86::BI__builtin_ia32_cmppd256:
2189 case X86::BI__builtin_ia32_cmpps128_mask:
2190 case X86::BI__builtin_ia32_cmppd128_mask:
2191 case X86::BI__builtin_ia32_cmpps256_mask:
2192 case X86::BI__builtin_ia32_cmppd256_mask:
2193 case X86::BI__builtin_ia32_cmpps512_mask:
2194 case X86::BI__builtin_ia32_cmppd512_mask:
2195 case X86::BI__builtin_ia32_cmpsd_mask:
2196 case X86::BI__builtin_ia32_cmpss_mask:
2197 i = 2; l = 0; u = 31;
2198 break;
2199 case X86::BI__builtin_ia32_xabort:
2200 i = 0; l = -128; u = 255;
2201 break;
2202 case X86::BI__builtin_ia32_pshufw:
2203 case X86::BI__builtin_ia32_aeskeygenassist128:
2204 i = 1; l = -128; u = 255;
2205 break;
2206 case X86::BI__builtin_ia32_vcvtps2ph:
2207 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002208 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2209 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2210 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2211 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2212 case X86::BI__builtin_ia32_rndscaleps_mask:
2213 case X86::BI__builtin_ia32_rndscalepd_mask:
2214 case X86::BI__builtin_ia32_reducepd128_mask:
2215 case X86::BI__builtin_ia32_reducepd256_mask:
2216 case X86::BI__builtin_ia32_reducepd512_mask:
2217 case X86::BI__builtin_ia32_reduceps128_mask:
2218 case X86::BI__builtin_ia32_reduceps256_mask:
2219 case X86::BI__builtin_ia32_reduceps512_mask:
2220 case X86::BI__builtin_ia32_prold512_mask:
2221 case X86::BI__builtin_ia32_prolq512_mask:
2222 case X86::BI__builtin_ia32_prold128_mask:
2223 case X86::BI__builtin_ia32_prold256_mask:
2224 case X86::BI__builtin_ia32_prolq128_mask:
2225 case X86::BI__builtin_ia32_prolq256_mask:
2226 case X86::BI__builtin_ia32_prord128_mask:
2227 case X86::BI__builtin_ia32_prord256_mask:
2228 case X86::BI__builtin_ia32_prorq128_mask:
2229 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002230 case X86::BI__builtin_ia32_fpclasspd128_mask:
2231 case X86::BI__builtin_ia32_fpclasspd256_mask:
2232 case X86::BI__builtin_ia32_fpclassps128_mask:
2233 case X86::BI__builtin_ia32_fpclassps256_mask:
2234 case X86::BI__builtin_ia32_fpclassps512_mask:
2235 case X86::BI__builtin_ia32_fpclasspd512_mask:
2236 case X86::BI__builtin_ia32_fpclasssd_mask:
2237 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002238 i = 1; l = 0; u = 255;
2239 break;
2240 case X86::BI__builtin_ia32_palignr:
2241 case X86::BI__builtin_ia32_insertps128:
2242 case X86::BI__builtin_ia32_dpps:
2243 case X86::BI__builtin_ia32_dppd:
2244 case X86::BI__builtin_ia32_dpps256:
2245 case X86::BI__builtin_ia32_mpsadbw128:
2246 case X86::BI__builtin_ia32_mpsadbw256:
2247 case X86::BI__builtin_ia32_pcmpistrm128:
2248 case X86::BI__builtin_ia32_pcmpistri128:
2249 case X86::BI__builtin_ia32_pcmpistria128:
2250 case X86::BI__builtin_ia32_pcmpistric128:
2251 case X86::BI__builtin_ia32_pcmpistrio128:
2252 case X86::BI__builtin_ia32_pcmpistris128:
2253 case X86::BI__builtin_ia32_pcmpistriz128:
2254 case X86::BI__builtin_ia32_pclmulqdq128:
2255 case X86::BI__builtin_ia32_vperm2f128_pd256:
2256 case X86::BI__builtin_ia32_vperm2f128_ps256:
2257 case X86::BI__builtin_ia32_vperm2f128_si256:
2258 case X86::BI__builtin_ia32_permti256:
2259 i = 2; l = -128; u = 255;
2260 break;
2261 case X86::BI__builtin_ia32_palignr128:
2262 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002263 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002264 case X86::BI__builtin_ia32_vcomisd:
2265 case X86::BI__builtin_ia32_vcomiss:
2266 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2267 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2268 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2269 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002270 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2271 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2272 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2273 i = 2; l = 0; u = 255;
2274 break;
2275 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2276 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2277 case X86::BI__builtin_ia32_fixupimmps512_mask:
2278 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2279 case X86::BI__builtin_ia32_fixupimmsd_mask:
2280 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2281 case X86::BI__builtin_ia32_fixupimmss_mask:
2282 case X86::BI__builtin_ia32_fixupimmss_maskz:
2283 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2284 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2285 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2286 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2287 case X86::BI__builtin_ia32_fixupimmps128_mask:
2288 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2289 case X86::BI__builtin_ia32_fixupimmps256_mask:
2290 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2291 case X86::BI__builtin_ia32_pternlogd512_mask:
2292 case X86::BI__builtin_ia32_pternlogd512_maskz:
2293 case X86::BI__builtin_ia32_pternlogq512_mask:
2294 case X86::BI__builtin_ia32_pternlogq512_maskz:
2295 case X86::BI__builtin_ia32_pternlogd128_mask:
2296 case X86::BI__builtin_ia32_pternlogd128_maskz:
2297 case X86::BI__builtin_ia32_pternlogd256_mask:
2298 case X86::BI__builtin_ia32_pternlogd256_maskz:
2299 case X86::BI__builtin_ia32_pternlogq128_mask:
2300 case X86::BI__builtin_ia32_pternlogq128_maskz:
2301 case X86::BI__builtin_ia32_pternlogq256_mask:
2302 case X86::BI__builtin_ia32_pternlogq256_maskz:
2303 i = 3; l = 0; u = 255;
2304 break;
Craig Topper9625db02017-03-12 22:19:10 +00002305 case X86::BI__builtin_ia32_gatherpfdpd:
2306 case X86::BI__builtin_ia32_gatherpfdps:
2307 case X86::BI__builtin_ia32_gatherpfqpd:
2308 case X86::BI__builtin_ia32_gatherpfqps:
2309 case X86::BI__builtin_ia32_scatterpfdpd:
2310 case X86::BI__builtin_ia32_scatterpfdps:
2311 case X86::BI__builtin_ia32_scatterpfqpd:
2312 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002313 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002314 break;
Craig Topper39c87102016-05-18 03:18:12 +00002315 case X86::BI__builtin_ia32_pcmpestrm128:
2316 case X86::BI__builtin_ia32_pcmpestri128:
2317 case X86::BI__builtin_ia32_pcmpestria128:
2318 case X86::BI__builtin_ia32_pcmpestric128:
2319 case X86::BI__builtin_ia32_pcmpestrio128:
2320 case X86::BI__builtin_ia32_pcmpestris128:
2321 case X86::BI__builtin_ia32_pcmpestriz128:
2322 i = 4; l = -128; u = 255;
2323 break;
2324 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2325 case X86::BI__builtin_ia32_rndscaless_round_mask:
2326 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002327 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002328 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002329 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002330}
2331
Richard Smith55ce3522012-06-25 20:30:08 +00002332/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2333/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2334/// Returns true when the format fits the function and the FormatStringInfo has
2335/// been populated.
2336bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2337 FormatStringInfo *FSI) {
2338 FSI->HasVAListArg = Format->getFirstArg() == 0;
2339 FSI->FormatIdx = Format->getFormatIdx() - 1;
2340 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002341
Richard Smith55ce3522012-06-25 20:30:08 +00002342 // The way the format attribute works in GCC, the implicit this argument
2343 // of member functions is counted. However, it doesn't appear in our own
2344 // lists, so decrement format_idx in that case.
2345 if (IsCXXMember) {
2346 if(FSI->FormatIdx == 0)
2347 return false;
2348 --FSI->FormatIdx;
2349 if (FSI->FirstDataArg != 0)
2350 --FSI->FirstDataArg;
2351 }
2352 return true;
2353}
Mike Stump11289f42009-09-09 15:08:12 +00002354
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002355/// Checks if a the given expression evaluates to null.
2356///
2357/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002358static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002359 // If the expression has non-null type, it doesn't evaluate to null.
2360 if (auto nullability
2361 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2362 if (*nullability == NullabilityKind::NonNull)
2363 return false;
2364 }
2365
Ted Kremeneka146db32014-01-17 06:24:47 +00002366 // As a special case, transparent unions initialized with zero are
2367 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002368 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002369 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2370 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002371 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002372 if (const InitListExpr *ILE =
2373 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002374 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002375 }
2376
2377 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002378 return (!Expr->isValueDependent() &&
2379 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2380 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002381}
2382
2383static void CheckNonNullArgument(Sema &S,
2384 const Expr *ArgExpr,
2385 SourceLocation CallSiteLoc) {
2386 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002387 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2388 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002389}
2390
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002391bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2392 FormatStringInfo FSI;
2393 if ((GetFormatStringType(Format) == FST_NSString) &&
2394 getFormatStringInfo(Format, false, &FSI)) {
2395 Idx = FSI.FormatIdx;
2396 return true;
2397 }
2398 return false;
2399}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002400/// \brief Diagnose use of %s directive in an NSString which is being passed
2401/// as formatting string to formatting method.
2402static void
2403DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2404 const NamedDecl *FDecl,
2405 Expr **Args,
2406 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002407 unsigned Idx = 0;
2408 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002409 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2410 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002411 Idx = 2;
2412 Format = true;
2413 }
2414 else
2415 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2416 if (S.GetFormatNSStringIdx(I, Idx)) {
2417 Format = true;
2418 break;
2419 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002420 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002421 if (!Format || NumArgs <= Idx)
2422 return;
2423 const Expr *FormatExpr = Args[Idx];
2424 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2425 FormatExpr = CSCE->getSubExpr();
2426 const StringLiteral *FormatString;
2427 if (const ObjCStringLiteral *OSL =
2428 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2429 FormatString = OSL->getString();
2430 else
2431 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2432 if (!FormatString)
2433 return;
2434 if (S.FormatStringHasSArg(FormatString)) {
2435 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2436 << "%s" << 1 << 1;
2437 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2438 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002439 }
2440}
2441
Douglas Gregorb4866e82015-06-19 18:13:19 +00002442/// Determine whether the given type has a non-null nullability annotation.
2443static bool isNonNullType(ASTContext &ctx, QualType type) {
2444 if (auto nullability = type->getNullability(ctx))
2445 return *nullability == NullabilityKind::NonNull;
2446
2447 return false;
2448}
2449
Ted Kremenek2bc73332014-01-17 06:24:43 +00002450static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002451 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002452 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002453 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002454 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002455 assert((FDecl || Proto) && "Need a function declaration or prototype");
2456
Ted Kremenek9aedc152014-01-17 06:24:56 +00002457 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002458 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002459 if (FDecl) {
2460 // Handle the nonnull attribute on the function/method declaration itself.
2461 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2462 if (!NonNull->args_size()) {
2463 // Easy case: all pointer arguments are nonnull.
2464 for (const auto *Arg : Args)
2465 if (S.isValidPointerAttrType(Arg->getType()))
2466 CheckNonNullArgument(S, Arg, CallSiteLoc);
2467 return;
2468 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002469
Douglas Gregorb4866e82015-06-19 18:13:19 +00002470 for (unsigned Val : NonNull->args()) {
2471 if (Val >= Args.size())
2472 continue;
2473 if (NonNullArgs.empty())
2474 NonNullArgs.resize(Args.size());
2475 NonNullArgs.set(Val);
2476 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002477 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002478 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002479
Douglas Gregorb4866e82015-06-19 18:13:19 +00002480 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2481 // Handle the nonnull attribute on the parameters of the
2482 // function/method.
2483 ArrayRef<ParmVarDecl*> parms;
2484 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2485 parms = FD->parameters();
2486 else
2487 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2488
2489 unsigned ParamIndex = 0;
2490 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2491 I != E; ++I, ++ParamIndex) {
2492 const ParmVarDecl *PVD = *I;
2493 if (PVD->hasAttr<NonNullAttr>() ||
2494 isNonNullType(S.Context, PVD->getType())) {
2495 if (NonNullArgs.empty())
2496 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002497
Douglas Gregorb4866e82015-06-19 18:13:19 +00002498 NonNullArgs.set(ParamIndex);
2499 }
2500 }
2501 } else {
2502 // If we have a non-function, non-method declaration but no
2503 // function prototype, try to dig out the function prototype.
2504 if (!Proto) {
2505 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2506 QualType type = VD->getType().getNonReferenceType();
2507 if (auto pointerType = type->getAs<PointerType>())
2508 type = pointerType->getPointeeType();
2509 else if (auto blockType = type->getAs<BlockPointerType>())
2510 type = blockType->getPointeeType();
2511 // FIXME: data member pointers?
2512
2513 // Dig out the function prototype, if there is one.
2514 Proto = type->getAs<FunctionProtoType>();
2515 }
2516 }
2517
2518 // Fill in non-null argument information from the nullability
2519 // information on the parameter types (if we have them).
2520 if (Proto) {
2521 unsigned Index = 0;
2522 for (auto paramType : Proto->getParamTypes()) {
2523 if (isNonNullType(S.Context, paramType)) {
2524 if (NonNullArgs.empty())
2525 NonNullArgs.resize(Args.size());
2526
2527 NonNullArgs.set(Index);
2528 }
2529
2530 ++Index;
2531 }
2532 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002533 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002534
Douglas Gregorb4866e82015-06-19 18:13:19 +00002535 // Check for non-null arguments.
2536 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2537 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002538 if (NonNullArgs[ArgIndex])
2539 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002540 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002541}
2542
Richard Smith55ce3522012-06-25 20:30:08 +00002543/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002544/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2545/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002546void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002547 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2548 bool IsMemberFunction, SourceLocation Loc,
2549 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002550 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002551 if (CurContext->isDependentContext())
2552 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002553
Ted Kremenekb8176da2010-09-09 04:33:05 +00002554 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002555 llvm::SmallBitVector CheckedVarArgs;
2556 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002557 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002558 // Only create vector if there are format attributes.
2559 CheckedVarArgs.resize(Args.size());
2560
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002561 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002562 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002563 }
Richard Smithd7293d72013-08-05 18:49:43 +00002564 }
Richard Smith55ce3522012-06-25 20:30:08 +00002565
2566 // Refuse POD arguments that weren't caught by the format string
2567 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002568 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2569 if (CallType != VariadicDoesNotApply &&
2570 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002571 unsigned NumParams = Proto ? Proto->getNumParams()
2572 : FDecl && isa<FunctionDecl>(FDecl)
2573 ? cast<FunctionDecl>(FDecl)->getNumParams()
2574 : FDecl && isa<ObjCMethodDecl>(FDecl)
2575 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2576 : 0;
2577
Alp Toker9cacbab2014-01-20 20:26:09 +00002578 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002579 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002580 if (const Expr *Arg = Args[ArgIdx]) {
2581 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2582 checkVariadicArgument(Arg, CallType);
2583 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002584 }
Richard Smithd7293d72013-08-05 18:49:43 +00002585 }
Mike Stump11289f42009-09-09 15:08:12 +00002586
Douglas Gregorb4866e82015-06-19 18:13:19 +00002587 if (FDecl || Proto) {
2588 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002589
Richard Trieu41bc0992013-06-22 00:20:41 +00002590 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002591 if (FDecl) {
2592 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2593 CheckArgumentWithTypeTag(I, Args.data());
2594 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002595 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002596
2597 if (FD)
2598 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002599}
2600
2601/// CheckConstructorCall - Check a constructor call for correctness and safety
2602/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002603void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2604 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002605 const FunctionProtoType *Proto,
2606 SourceLocation Loc) {
2607 VariadicCallType CallType =
2608 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002609 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2610 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002611}
2612
2613/// CheckFunctionCall - Check a direct function call for various correctness
2614/// and safety properties not strictly enforced by the C type system.
2615bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2616 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002617 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2618 isa<CXXMethodDecl>(FDecl);
2619 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2620 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002621 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2622 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002623 Expr** Args = TheCall->getArgs();
2624 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002625
2626 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002627 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002628 // If this is a call to a member operator, hide the first argument
2629 // from checkCall.
2630 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002631 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002632 ++Args;
2633 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002634 } else if (IsMemberFunction)
2635 ImplicitThis =
2636 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2637
2638 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002639 IsMemberFunction, TheCall->getRParenLoc(),
2640 TheCall->getCallee()->getSourceRange(), CallType);
2641
2642 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2643 // None of the checks below are needed for functions that don't have
2644 // simple names (e.g., C++ conversion functions).
2645 if (!FnInfo)
2646 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002647
Richard Trieua7f30b12016-12-06 01:42:28 +00002648 CheckAbsoluteValueFunction(TheCall, FDecl);
2649 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002650
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002651 if (getLangOpts().ObjC1)
2652 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002653
Anna Zaks22122702012-01-17 00:37:07 +00002654 unsigned CMId = FDecl->getMemoryFunctionKind();
2655 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002656 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002657
Anna Zaks201d4892012-01-13 21:52:01 +00002658 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002659 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002660 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002661 else if (CMId == Builtin::BIstrncat)
2662 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002663 else
Anna Zaks22122702012-01-17 00:37:07 +00002664 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002665
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002666 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002667}
2668
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002669bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002670 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002671 VariadicCallType CallType =
2672 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002673
George Burgess IVce6284b2017-01-28 02:19:40 +00002674 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2675 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002676 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002677
2678 return false;
2679}
2680
Richard Trieu664c4c62013-06-20 21:03:13 +00002681bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2682 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002683 QualType Ty;
2684 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002685 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002686 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002687 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002688 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002689 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002690
Douglas Gregorb4866e82015-06-19 18:13:19 +00002691 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2692 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002693 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002694
Richard Trieu664c4c62013-06-20 21:03:13 +00002695 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002696 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002697 CallType = VariadicDoesNotApply;
2698 } else if (Ty->isBlockPointerType()) {
2699 CallType = VariadicBlock;
2700 } else { // Ty->isFunctionPointerType()
2701 CallType = VariadicFunction;
2702 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002703
George Burgess IVce6284b2017-01-28 02:19:40 +00002704 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002705 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2706 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002707 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002708
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002709 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002710}
2711
Richard Trieu41bc0992013-06-22 00:20:41 +00002712/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2713/// such as function pointers returned from functions.
2714bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002715 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002716 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002717 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002718 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002719 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002720 TheCall->getCallee()->getSourceRange(), CallType);
2721
2722 return false;
2723}
2724
Tim Northovere94a34c2014-03-11 10:49:14 +00002725static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002726 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002727 return false;
2728
JF Bastiendda2cb12016-04-18 18:01:49 +00002729 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002730 switch (Op) {
2731 case AtomicExpr::AO__c11_atomic_init:
2732 llvm_unreachable("There is no ordering argument for an init");
2733
2734 case AtomicExpr::AO__c11_atomic_load:
2735 case AtomicExpr::AO__atomic_load_n:
2736 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002737 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2738 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002739
2740 case AtomicExpr::AO__c11_atomic_store:
2741 case AtomicExpr::AO__atomic_store:
2742 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002743 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2744 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2745 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002746
2747 default:
2748 return true;
2749 }
2750}
2751
Richard Smithfeea8832012-04-12 05:08:17 +00002752ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2753 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002754 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2755 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002756
Richard Smithfeea8832012-04-12 05:08:17 +00002757 // All these operations take one of the following forms:
2758 enum {
2759 // C __c11_atomic_init(A *, C)
2760 Init,
2761 // C __c11_atomic_load(A *, int)
2762 Load,
2763 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002764 LoadCopy,
2765 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002766 Copy,
2767 // C __c11_atomic_add(A *, M, int)
2768 Arithmetic,
2769 // C __atomic_exchange_n(A *, CP, int)
2770 Xchg,
2771 // void __atomic_exchange(A *, C *, CP, int)
2772 GNUXchg,
2773 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2774 C11CmpXchg,
2775 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2776 GNUCmpXchg
2777 } Form = Init;
Eric Fiselier8d662442016-03-30 23:39:56 +00002778 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2779 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002780 // where:
2781 // C is an appropriate type,
2782 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2783 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2784 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2785 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002786
Gabor Horvath98bd0982015-03-16 09:59:54 +00002787 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2788 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2789 AtomicExpr::AO__atomic_load,
2790 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00002791 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2792 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2793 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2794 Op == AtomicExpr::AO__atomic_store_n ||
2795 Op == AtomicExpr::AO__atomic_exchange_n ||
2796 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2797 bool IsAddSub = false;
2798
2799 switch (Op) {
2800 case AtomicExpr::AO__c11_atomic_init:
2801 Form = Init;
2802 break;
2803
2804 case AtomicExpr::AO__c11_atomic_load:
2805 case AtomicExpr::AO__atomic_load_n:
2806 Form = Load;
2807 break;
2808
Richard Smithfeea8832012-04-12 05:08:17 +00002809 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002810 Form = LoadCopy;
2811 break;
2812
2813 case AtomicExpr::AO__c11_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002814 case AtomicExpr::AO__atomic_store:
2815 case AtomicExpr::AO__atomic_store_n:
2816 Form = Copy;
2817 break;
2818
2819 case AtomicExpr::AO__c11_atomic_fetch_add:
2820 case AtomicExpr::AO__c11_atomic_fetch_sub:
2821 case AtomicExpr::AO__atomic_fetch_add:
2822 case AtomicExpr::AO__atomic_fetch_sub:
2823 case AtomicExpr::AO__atomic_add_fetch:
2824 case AtomicExpr::AO__atomic_sub_fetch:
2825 IsAddSub = true;
2826 // Fall through.
2827 case AtomicExpr::AO__c11_atomic_fetch_and:
2828 case AtomicExpr::AO__c11_atomic_fetch_or:
2829 case AtomicExpr::AO__c11_atomic_fetch_xor:
2830 case AtomicExpr::AO__atomic_fetch_and:
2831 case AtomicExpr::AO__atomic_fetch_or:
2832 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002833 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002834 case AtomicExpr::AO__atomic_and_fetch:
2835 case AtomicExpr::AO__atomic_or_fetch:
2836 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002837 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002838 Form = Arithmetic;
2839 break;
2840
2841 case AtomicExpr::AO__c11_atomic_exchange:
2842 case AtomicExpr::AO__atomic_exchange_n:
2843 Form = Xchg;
2844 break;
2845
2846 case AtomicExpr::AO__atomic_exchange:
2847 Form = GNUXchg;
2848 break;
2849
2850 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2851 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2852 Form = C11CmpXchg;
2853 break;
2854
2855 case AtomicExpr::AO__atomic_compare_exchange:
2856 case AtomicExpr::AO__atomic_compare_exchange_n:
2857 Form = GNUCmpXchg;
2858 break;
2859 }
2860
2861 // Check we have the right number of arguments.
2862 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002863 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002864 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002865 << TheCall->getCallee()->getSourceRange();
2866 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00002867 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2868 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002869 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00002870 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002871 << TheCall->getCallee()->getSourceRange();
2872 return ExprError();
2873 }
2874
Richard Smithfeea8832012-04-12 05:08:17 +00002875 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002876 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00002877 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2878 if (ConvertedPtr.isInvalid())
2879 return ExprError();
2880
2881 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002882 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2883 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00002884 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002885 << Ptr->getType() << Ptr->getSourceRange();
2886 return ExprError();
2887 }
2888
Richard Smithfeea8832012-04-12 05:08:17 +00002889 // For a __c11 builtin, this should be a pointer to an _Atomic type.
2890 QualType AtomTy = pointerType->getPointeeType(); // 'A'
2891 QualType ValType = AtomTy; // 'C'
2892 if (IsC11) {
2893 if (!AtomTy->isAtomicType()) {
2894 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2895 << Ptr->getType() << Ptr->getSourceRange();
2896 return ExprError();
2897 }
Richard Smithe00921a2012-09-15 06:09:58 +00002898 if (AtomTy.isConstQualified()) {
2899 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2900 << Ptr->getType() << Ptr->getSourceRange();
2901 return ExprError();
2902 }
Richard Smithfeea8832012-04-12 05:08:17 +00002903 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00002904 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002905 if (ValType.isConstQualified()) {
2906 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2907 << Ptr->getType() << Ptr->getSourceRange();
2908 return ExprError();
2909 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002910 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002911
Richard Smithfeea8832012-04-12 05:08:17 +00002912 // For an arithmetic operation, the implied arithmetic must be well-formed.
2913 if (Form == Arithmetic) {
2914 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2915 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2916 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2917 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2918 return ExprError();
2919 }
2920 if (!IsAddSub && !ValType->isIntegerType()) {
2921 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2922 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2923 return ExprError();
2924 }
David Majnemere85cff82015-01-28 05:48:06 +00002925 if (IsC11 && ValType->isPointerType() &&
2926 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2927 diag::err_incomplete_type)) {
2928 return ExprError();
2929 }
Richard Smithfeea8832012-04-12 05:08:17 +00002930 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2931 // For __atomic_*_n operations, the value type must be a scalar integral or
2932 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002933 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00002934 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2935 return ExprError();
2936 }
2937
Eli Friedmanaa769812013-09-11 03:49:34 +00002938 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2939 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00002940 // For GNU atomics, require a trivially-copyable type. This is not part of
2941 // the GNU atomics specification, but we enforce it for sanity.
2942 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002943 << Ptr->getType() << Ptr->getSourceRange();
2944 return ExprError();
2945 }
2946
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002947 switch (ValType.getObjCLifetime()) {
2948 case Qualifiers::OCL_None:
2949 case Qualifiers::OCL_ExplicitNone:
2950 // okay
2951 break;
2952
2953 case Qualifiers::OCL_Weak:
2954 case Qualifiers::OCL_Strong:
2955 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002956 // FIXME: Can this happen? By this point, ValType should be known
2957 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002958 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2959 << ValType << Ptr->getSourceRange();
2960 return ExprError();
2961 }
2962
David Majnemerc6eb6502015-06-03 00:26:35 +00002963 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2964 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00002965 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00002966 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00002967 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002968 QualType ResultType = ValType;
Eric Fiselier8d662442016-03-30 23:39:56 +00002969 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002970 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002971 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002972 ResultType = Context.BoolTy;
2973
Richard Smithfeea8832012-04-12 05:08:17 +00002974 // The type of a parameter passed 'by value'. In the GNU atomics, such
2975 // arguments are actually passed as pointers.
2976 QualType ByValType = ValType; // 'CP'
2977 if (!IsC11 && !IsN)
2978 ByValType = Ptr->getType();
2979
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002980 // The first argument --- the pointer --- has a fixed type; we
2981 // deduce the types of the rest of the arguments accordingly. Walk
2982 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002983 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002984 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002985 if (i < NumVals[Form] + 1) {
2986 switch (i) {
2987 case 1:
2988 // The second argument is the non-atomic operand. For arithmetic, this
2989 // is always passed by value, and for a compare_exchange it is always
2990 // passed by address. For the rest, GNU uses by-address and C11 uses
2991 // by-value.
2992 assert(Form != Load);
2993 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2994 Ty = ValType;
2995 else if (Form == Copy || Form == Xchg)
2996 Ty = ByValType;
2997 else if (Form == Arithmetic)
2998 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002999 else {
3000 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003001 // Treat this argument as _Nonnull as we want to show a warning if
3002 // NULL is passed into it.
3003 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003004 unsigned AS = 0;
3005 // Keep address space of non-atomic pointer type.
3006 if (const PointerType *PtrTy =
3007 ValArg->getType()->getAs<PointerType>()) {
3008 AS = PtrTy->getPointeeType().getAddressSpace();
3009 }
3010 Ty = Context.getPointerType(
3011 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3012 }
Richard Smithfeea8832012-04-12 05:08:17 +00003013 break;
3014 case 2:
3015 // The third argument to compare_exchange / GNU exchange is a
3016 // (pointer to a) desired value.
3017 Ty = ByValType;
3018 break;
3019 case 3:
3020 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3021 Ty = Context.BoolTy;
3022 break;
3023 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003024 } else {
3025 // The order(s) are always converted to int.
3026 Ty = Context.IntTy;
3027 }
Richard Smithfeea8832012-04-12 05:08:17 +00003028
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003029 InitializedEntity Entity =
3030 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003031 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003032 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3033 if (Arg.isInvalid())
3034 return true;
3035 TheCall->setArg(i, Arg.get());
3036 }
3037
Richard Smithfeea8832012-04-12 05:08:17 +00003038 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003039 SmallVector<Expr*, 5> SubExprs;
3040 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003041 switch (Form) {
3042 case Init:
3043 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003044 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003045 break;
3046 case Load:
3047 SubExprs.push_back(TheCall->getArg(1)); // Order
3048 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003049 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003050 case Copy:
3051 case Arithmetic:
3052 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003053 SubExprs.push_back(TheCall->getArg(2)); // Order
3054 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003055 break;
3056 case GNUXchg:
3057 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3058 SubExprs.push_back(TheCall->getArg(3)); // Order
3059 SubExprs.push_back(TheCall->getArg(1)); // Val1
3060 SubExprs.push_back(TheCall->getArg(2)); // Val2
3061 break;
3062 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003063 SubExprs.push_back(TheCall->getArg(3)); // Order
3064 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003065 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003066 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003067 break;
3068 case GNUCmpXchg:
3069 SubExprs.push_back(TheCall->getArg(4)); // Order
3070 SubExprs.push_back(TheCall->getArg(1)); // Val1
3071 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3072 SubExprs.push_back(TheCall->getArg(2)); // Val2
3073 SubExprs.push_back(TheCall->getArg(3)); // Weak
3074 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003075 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003076
3077 if (SubExprs.size() >= 2 && Form != Init) {
3078 llvm::APSInt Result(32);
3079 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3080 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003081 Diag(SubExprs[1]->getLocStart(),
3082 diag::warn_atomic_op_has_invalid_memory_order)
3083 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003084 }
3085
Fariborz Jahanian615de762013-05-28 17:37:39 +00003086 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3087 SubExprs, ResultType, Op,
3088 TheCall->getRParenLoc());
3089
3090 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3091 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3092 Context.AtomicUsesUnsupportedLibcall(AE))
3093 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
3094 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003095
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003096 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003097}
3098
John McCall29ad95b2011-08-27 01:09:30 +00003099/// checkBuiltinArgument - Given a call to a builtin function, perform
3100/// normal type-checking on the given argument, updating the call in
3101/// place. This is useful when a builtin function requires custom
3102/// type-checking for some of its arguments but not necessarily all of
3103/// them.
3104///
3105/// Returns true on error.
3106static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3107 FunctionDecl *Fn = E->getDirectCallee();
3108 assert(Fn && "builtin call without direct callee!");
3109
3110 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3111 InitializedEntity Entity =
3112 InitializedEntity::InitializeParameter(S.Context, Param);
3113
3114 ExprResult Arg = E->getArg(0);
3115 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3116 if (Arg.isInvalid())
3117 return true;
3118
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003119 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003120 return false;
3121}
3122
Chris Lattnerdc046542009-05-08 06:58:22 +00003123/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3124/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3125/// type of its first argument. The main ActOnCallExpr routines have already
3126/// promoted the types of arguments because all of these calls are prototyped as
3127/// void(...).
3128///
3129/// This function goes through and does final semantic checking for these
3130/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003131ExprResult
3132Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003133 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003134 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3135 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3136
3137 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003138 if (TheCall->getNumArgs() < 1) {
3139 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3140 << 0 << 1 << TheCall->getNumArgs()
3141 << TheCall->getCallee()->getSourceRange();
3142 return ExprError();
3143 }
Mike Stump11289f42009-09-09 15:08:12 +00003144
Chris Lattnerdc046542009-05-08 06:58:22 +00003145 // Inspect the first argument of the atomic builtin. This should always be
3146 // a pointer type, whose element is an integral scalar or pointer type.
3147 // Because it is a pointer type, we don't have to worry about any implicit
3148 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003149 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003150 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003151 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3152 if (FirstArgResult.isInvalid())
3153 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003154 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003155 TheCall->setArg(0, FirstArg);
3156
John McCall31168b02011-06-15 23:02:42 +00003157 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3158 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003159 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3160 << FirstArg->getType() << FirstArg->getSourceRange();
3161 return ExprError();
3162 }
Mike Stump11289f42009-09-09 15:08:12 +00003163
John McCall31168b02011-06-15 23:02:42 +00003164 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003165 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003166 !ValType->isBlockPointerType()) {
3167 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3168 << FirstArg->getType() << FirstArg->getSourceRange();
3169 return ExprError();
3170 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003171
John McCall31168b02011-06-15 23:02:42 +00003172 switch (ValType.getObjCLifetime()) {
3173 case Qualifiers::OCL_None:
3174 case Qualifiers::OCL_ExplicitNone:
3175 // okay
3176 break;
3177
3178 case Qualifiers::OCL_Weak:
3179 case Qualifiers::OCL_Strong:
3180 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003181 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003182 << ValType << FirstArg->getSourceRange();
3183 return ExprError();
3184 }
3185
John McCallb50451a2011-10-05 07:41:44 +00003186 // Strip any qualifiers off ValType.
3187 ValType = ValType.getUnqualifiedType();
3188
Chandler Carruth3973af72010-07-18 20:54:12 +00003189 // The majority of builtins return a value, but a few have special return
3190 // types, so allow them to override appropriately below.
3191 QualType ResultType = ValType;
3192
Chris Lattnerdc046542009-05-08 06:58:22 +00003193 // We need to figure out which concrete builtin this maps onto. For example,
3194 // __sync_fetch_and_add with a 2 byte object turns into
3195 // __sync_fetch_and_add_2.
3196#define BUILTIN_ROW(x) \
3197 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3198 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003199
Chris Lattnerdc046542009-05-08 06:58:22 +00003200 static const unsigned BuiltinIndices[][5] = {
3201 BUILTIN_ROW(__sync_fetch_and_add),
3202 BUILTIN_ROW(__sync_fetch_and_sub),
3203 BUILTIN_ROW(__sync_fetch_and_or),
3204 BUILTIN_ROW(__sync_fetch_and_and),
3205 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003206 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003207
Chris Lattnerdc046542009-05-08 06:58:22 +00003208 BUILTIN_ROW(__sync_add_and_fetch),
3209 BUILTIN_ROW(__sync_sub_and_fetch),
3210 BUILTIN_ROW(__sync_and_and_fetch),
3211 BUILTIN_ROW(__sync_or_and_fetch),
3212 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003213 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003214
Chris Lattnerdc046542009-05-08 06:58:22 +00003215 BUILTIN_ROW(__sync_val_compare_and_swap),
3216 BUILTIN_ROW(__sync_bool_compare_and_swap),
3217 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003218 BUILTIN_ROW(__sync_lock_release),
3219 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003220 };
Mike Stump11289f42009-09-09 15:08:12 +00003221#undef BUILTIN_ROW
3222
Chris Lattnerdc046542009-05-08 06:58:22 +00003223 // Determine the index of the size.
3224 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003225 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003226 case 1: SizeIndex = 0; break;
3227 case 2: SizeIndex = 1; break;
3228 case 4: SizeIndex = 2; break;
3229 case 8: SizeIndex = 3; break;
3230 case 16: SizeIndex = 4; break;
3231 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003232 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3233 << FirstArg->getType() << FirstArg->getSourceRange();
3234 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003235 }
Mike Stump11289f42009-09-09 15:08:12 +00003236
Chris Lattnerdc046542009-05-08 06:58:22 +00003237 // Each of these builtins has one pointer argument, followed by some number of
3238 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3239 // that we ignore. Find out which row of BuiltinIndices to read from as well
3240 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003241 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003242 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003243 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003244 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003245 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003246 case Builtin::BI__sync_fetch_and_add:
3247 case Builtin::BI__sync_fetch_and_add_1:
3248 case Builtin::BI__sync_fetch_and_add_2:
3249 case Builtin::BI__sync_fetch_and_add_4:
3250 case Builtin::BI__sync_fetch_and_add_8:
3251 case Builtin::BI__sync_fetch_and_add_16:
3252 BuiltinIndex = 0;
3253 break;
3254
3255 case Builtin::BI__sync_fetch_and_sub:
3256 case Builtin::BI__sync_fetch_and_sub_1:
3257 case Builtin::BI__sync_fetch_and_sub_2:
3258 case Builtin::BI__sync_fetch_and_sub_4:
3259 case Builtin::BI__sync_fetch_and_sub_8:
3260 case Builtin::BI__sync_fetch_and_sub_16:
3261 BuiltinIndex = 1;
3262 break;
3263
3264 case Builtin::BI__sync_fetch_and_or:
3265 case Builtin::BI__sync_fetch_and_or_1:
3266 case Builtin::BI__sync_fetch_and_or_2:
3267 case Builtin::BI__sync_fetch_and_or_4:
3268 case Builtin::BI__sync_fetch_and_or_8:
3269 case Builtin::BI__sync_fetch_and_or_16:
3270 BuiltinIndex = 2;
3271 break;
3272
3273 case Builtin::BI__sync_fetch_and_and:
3274 case Builtin::BI__sync_fetch_and_and_1:
3275 case Builtin::BI__sync_fetch_and_and_2:
3276 case Builtin::BI__sync_fetch_and_and_4:
3277 case Builtin::BI__sync_fetch_and_and_8:
3278 case Builtin::BI__sync_fetch_and_and_16:
3279 BuiltinIndex = 3;
3280 break;
Mike Stump11289f42009-09-09 15:08:12 +00003281
Douglas Gregor73722482011-11-28 16:30:08 +00003282 case Builtin::BI__sync_fetch_and_xor:
3283 case Builtin::BI__sync_fetch_and_xor_1:
3284 case Builtin::BI__sync_fetch_and_xor_2:
3285 case Builtin::BI__sync_fetch_and_xor_4:
3286 case Builtin::BI__sync_fetch_and_xor_8:
3287 case Builtin::BI__sync_fetch_and_xor_16:
3288 BuiltinIndex = 4;
3289 break;
3290
Hal Finkeld2208b52014-10-02 20:53:50 +00003291 case Builtin::BI__sync_fetch_and_nand:
3292 case Builtin::BI__sync_fetch_and_nand_1:
3293 case Builtin::BI__sync_fetch_and_nand_2:
3294 case Builtin::BI__sync_fetch_and_nand_4:
3295 case Builtin::BI__sync_fetch_and_nand_8:
3296 case Builtin::BI__sync_fetch_and_nand_16:
3297 BuiltinIndex = 5;
3298 WarnAboutSemanticsChange = true;
3299 break;
3300
Douglas Gregor73722482011-11-28 16:30:08 +00003301 case Builtin::BI__sync_add_and_fetch:
3302 case Builtin::BI__sync_add_and_fetch_1:
3303 case Builtin::BI__sync_add_and_fetch_2:
3304 case Builtin::BI__sync_add_and_fetch_4:
3305 case Builtin::BI__sync_add_and_fetch_8:
3306 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003307 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003308 break;
3309
3310 case Builtin::BI__sync_sub_and_fetch:
3311 case Builtin::BI__sync_sub_and_fetch_1:
3312 case Builtin::BI__sync_sub_and_fetch_2:
3313 case Builtin::BI__sync_sub_and_fetch_4:
3314 case Builtin::BI__sync_sub_and_fetch_8:
3315 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003316 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003317 break;
3318
3319 case Builtin::BI__sync_and_and_fetch:
3320 case Builtin::BI__sync_and_and_fetch_1:
3321 case Builtin::BI__sync_and_and_fetch_2:
3322 case Builtin::BI__sync_and_and_fetch_4:
3323 case Builtin::BI__sync_and_and_fetch_8:
3324 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003325 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003326 break;
3327
3328 case Builtin::BI__sync_or_and_fetch:
3329 case Builtin::BI__sync_or_and_fetch_1:
3330 case Builtin::BI__sync_or_and_fetch_2:
3331 case Builtin::BI__sync_or_and_fetch_4:
3332 case Builtin::BI__sync_or_and_fetch_8:
3333 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003334 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003335 break;
3336
3337 case Builtin::BI__sync_xor_and_fetch:
3338 case Builtin::BI__sync_xor_and_fetch_1:
3339 case Builtin::BI__sync_xor_and_fetch_2:
3340 case Builtin::BI__sync_xor_and_fetch_4:
3341 case Builtin::BI__sync_xor_and_fetch_8:
3342 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003343 BuiltinIndex = 10;
3344 break;
3345
3346 case Builtin::BI__sync_nand_and_fetch:
3347 case Builtin::BI__sync_nand_and_fetch_1:
3348 case Builtin::BI__sync_nand_and_fetch_2:
3349 case Builtin::BI__sync_nand_and_fetch_4:
3350 case Builtin::BI__sync_nand_and_fetch_8:
3351 case Builtin::BI__sync_nand_and_fetch_16:
3352 BuiltinIndex = 11;
3353 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003354 break;
Mike Stump11289f42009-09-09 15:08:12 +00003355
Chris Lattnerdc046542009-05-08 06:58:22 +00003356 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003357 case Builtin::BI__sync_val_compare_and_swap_1:
3358 case Builtin::BI__sync_val_compare_and_swap_2:
3359 case Builtin::BI__sync_val_compare_and_swap_4:
3360 case Builtin::BI__sync_val_compare_and_swap_8:
3361 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003362 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003363 NumFixed = 2;
3364 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003365
Chris Lattnerdc046542009-05-08 06:58:22 +00003366 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003367 case Builtin::BI__sync_bool_compare_and_swap_1:
3368 case Builtin::BI__sync_bool_compare_and_swap_2:
3369 case Builtin::BI__sync_bool_compare_and_swap_4:
3370 case Builtin::BI__sync_bool_compare_and_swap_8:
3371 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003372 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003373 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003374 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003375 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003376
3377 case Builtin::BI__sync_lock_test_and_set:
3378 case Builtin::BI__sync_lock_test_and_set_1:
3379 case Builtin::BI__sync_lock_test_and_set_2:
3380 case Builtin::BI__sync_lock_test_and_set_4:
3381 case Builtin::BI__sync_lock_test_and_set_8:
3382 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003383 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003384 break;
3385
Chris Lattnerdc046542009-05-08 06:58:22 +00003386 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003387 case Builtin::BI__sync_lock_release_1:
3388 case Builtin::BI__sync_lock_release_2:
3389 case Builtin::BI__sync_lock_release_4:
3390 case Builtin::BI__sync_lock_release_8:
3391 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003392 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003393 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003394 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003395 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003396
3397 case Builtin::BI__sync_swap:
3398 case Builtin::BI__sync_swap_1:
3399 case Builtin::BI__sync_swap_2:
3400 case Builtin::BI__sync_swap_4:
3401 case Builtin::BI__sync_swap_8:
3402 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003403 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003404 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003405 }
Mike Stump11289f42009-09-09 15:08:12 +00003406
Chris Lattnerdc046542009-05-08 06:58:22 +00003407 // Now that we know how many fixed arguments we expect, first check that we
3408 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003409 if (TheCall->getNumArgs() < 1+NumFixed) {
3410 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3411 << 0 << 1+NumFixed << TheCall->getNumArgs()
3412 << TheCall->getCallee()->getSourceRange();
3413 return ExprError();
3414 }
Mike Stump11289f42009-09-09 15:08:12 +00003415
Hal Finkeld2208b52014-10-02 20:53:50 +00003416 if (WarnAboutSemanticsChange) {
3417 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3418 << TheCall->getCallee()->getSourceRange();
3419 }
3420
Chris Lattner5b9241b2009-05-08 15:36:58 +00003421 // Get the decl for the concrete builtin from this, we can tell what the
3422 // concrete integer type we should convert to is.
3423 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003424 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003425 FunctionDecl *NewBuiltinDecl;
3426 if (NewBuiltinID == BuiltinID)
3427 NewBuiltinDecl = FDecl;
3428 else {
3429 // Perform builtin lookup to avoid redeclaring it.
3430 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3431 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3432 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3433 assert(Res.getFoundDecl());
3434 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003435 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003436 return ExprError();
3437 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003438
John McCallcf142162010-08-07 06:22:56 +00003439 // The first argument --- the pointer --- has a fixed type; we
3440 // deduce the types of the rest of the arguments accordingly. Walk
3441 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003442 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003443 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003444
Chris Lattnerdc046542009-05-08 06:58:22 +00003445 // GCC does an implicit conversion to the pointer or integer ValType. This
3446 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003447 // Initialize the argument.
3448 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3449 ValType, /*consume*/ false);
3450 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003451 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003452 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003453
Chris Lattnerdc046542009-05-08 06:58:22 +00003454 // Okay, we have something that *can* be converted to the right type. Check
3455 // to see if there is a potentially weird extension going on here. This can
3456 // happen when you do an atomic operation on something like an char* and
3457 // pass in 42. The 42 gets converted to char. This is even more strange
3458 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003459 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003460 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003461 }
Mike Stump11289f42009-09-09 15:08:12 +00003462
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003463 ASTContext& Context = this->getASTContext();
3464
3465 // Create a new DeclRefExpr to refer to the new decl.
3466 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3467 Context,
3468 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003469 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003470 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003471 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003472 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003473 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003474 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003475
Chris Lattnerdc046542009-05-08 06:58:22 +00003476 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003477 // FIXME: This loses syntactic information.
3478 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3479 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3480 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003481 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003482
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003483 // Change the result type of the call to match the original value type. This
3484 // is arbitrary, but the codegen for these builtins ins design to handle it
3485 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003486 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003487
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003488 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003489}
3490
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003491/// SemaBuiltinNontemporalOverloaded - We have a call to
3492/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3493/// overloaded function based on the pointer type of its last argument.
3494///
3495/// This function goes through and does final semantic checking for these
3496/// builtins.
3497ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3498 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3499 DeclRefExpr *DRE =
3500 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3501 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3502 unsigned BuiltinID = FDecl->getBuiltinID();
3503 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3504 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3505 "Unexpected nontemporal load/store builtin!");
3506 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3507 unsigned numArgs = isStore ? 2 : 1;
3508
3509 // Ensure that we have the proper number of arguments.
3510 if (checkArgCount(*this, TheCall, numArgs))
3511 return ExprError();
3512
3513 // Inspect the last argument of the nontemporal builtin. This should always
3514 // be a pointer type, from which we imply the type of the memory access.
3515 // Because it is a pointer type, we don't have to worry about any implicit
3516 // casts here.
3517 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3518 ExprResult PointerArgResult =
3519 DefaultFunctionArrayLvalueConversion(PointerArg);
3520
3521 if (PointerArgResult.isInvalid())
3522 return ExprError();
3523 PointerArg = PointerArgResult.get();
3524 TheCall->setArg(numArgs - 1, PointerArg);
3525
3526 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3527 if (!pointerType) {
3528 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3529 << PointerArg->getType() << PointerArg->getSourceRange();
3530 return ExprError();
3531 }
3532
3533 QualType ValType = pointerType->getPointeeType();
3534
3535 // Strip any qualifiers off ValType.
3536 ValType = ValType.getUnqualifiedType();
3537 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3538 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3539 !ValType->isVectorType()) {
3540 Diag(DRE->getLocStart(),
3541 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3542 << PointerArg->getType() << PointerArg->getSourceRange();
3543 return ExprError();
3544 }
3545
3546 if (!isStore) {
3547 TheCall->setType(ValType);
3548 return TheCallResult;
3549 }
3550
3551 ExprResult ValArg = TheCall->getArg(0);
3552 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3553 Context, ValType, /*consume*/ false);
3554 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3555 if (ValArg.isInvalid())
3556 return ExprError();
3557
3558 TheCall->setArg(0, ValArg.get());
3559 TheCall->setType(Context.VoidTy);
3560 return TheCallResult;
3561}
3562
Chris Lattner6436fb62009-02-18 06:01:06 +00003563/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003564/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003565/// Note: It might also make sense to do the UTF-16 conversion here (would
3566/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003567bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003568 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003569 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3570
Douglas Gregorfb65e592011-07-27 05:40:30 +00003571 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003572 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3573 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003574 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003575 }
Mike Stump11289f42009-09-09 15:08:12 +00003576
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003577 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003578 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003579 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003580 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3581 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3582 llvm::UTF16 *ToPtr = &ToBuf[0];
3583
3584 llvm::ConversionResult Result =
3585 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3586 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003587 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003588 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003589 Diag(Arg->getLocStart(),
3590 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3591 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003592 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003593}
3594
Mehdi Amini06d367c2016-10-24 20:39:34 +00003595/// CheckObjCString - Checks that the format string argument to the os_log()
3596/// and os_trace() functions is correct, and converts it to const char *.
3597ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3598 Arg = Arg->IgnoreParenCasts();
3599 auto *Literal = dyn_cast<StringLiteral>(Arg);
3600 if (!Literal) {
3601 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3602 Literal = ObjcLiteral->getString();
3603 }
3604 }
3605
3606 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3607 return ExprError(
3608 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3609 << Arg->getSourceRange());
3610 }
3611
3612 ExprResult Result(Literal);
3613 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3614 InitializedEntity Entity =
3615 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3616 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3617 return Result;
3618}
3619
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003620/// Check that the user is calling the appropriate va_start builtin for the
3621/// target and calling convention.
3622static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3623 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3624 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3625 bool IsWindows = TT.isOSWindows();
3626 bool IsMSVAStart = BuiltinID == X86::BI__builtin_ms_va_start;
3627 if (IsX64) {
3628 clang::CallingConv CC = CC_C;
3629 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3630 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3631 if (IsMSVAStart) {
3632 // Don't allow this in System V ABI functions.
3633 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_X86_64Win64))
3634 return S.Diag(Fn->getLocStart(),
3635 diag::err_ms_va_start_used_in_sysv_function);
3636 } else {
3637 // On x86-64 Unix, don't allow this in Win64 ABI functions.
3638 // On x64 Windows, don't allow this in System V ABI functions.
3639 // (Yes, that means there's no corresponding way to support variadic
3640 // System V ABI functions on Windows.)
3641 if ((IsWindows && CC == CC_X86_64SysV) ||
3642 (!IsWindows && CC == CC_X86_64Win64))
3643 return S.Diag(Fn->getLocStart(),
3644 diag::err_va_start_used_in_wrong_abi_function)
3645 << !IsWindows;
3646 }
3647 return false;
3648 }
3649
3650 if (IsMSVAStart)
3651 return S.Diag(Fn->getLocStart(), diag::err_x86_builtin_64_only);
3652 return false;
3653}
3654
3655static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3656 ParmVarDecl **LastParam = nullptr) {
3657 // Determine whether the current function, block, or obj-c method is variadic
3658 // and get its parameter list.
3659 bool IsVariadic = false;
3660 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003661 DeclContext *Caller = S.CurContext;
3662 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3663 IsVariadic = Block->isVariadic();
3664 Params = Block->parameters();
3665 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003666 IsVariadic = FD->isVariadic();
3667 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003668 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003669 IsVariadic = MD->isVariadic();
3670 // FIXME: This isn't correct for methods (results in bogus warning).
3671 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003672 } else if (isa<CapturedDecl>(Caller)) {
3673 // We don't support va_start in a CapturedDecl.
3674 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3675 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003676 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003677 // This must be some other declcontext that parses exprs.
3678 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3679 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003680 }
3681
3682 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003683 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003684 return true;
3685 }
3686
3687 if (LastParam)
3688 *LastParam = Params.empty() ? nullptr : Params.back();
3689
3690 return false;
3691}
3692
Charles Davisc7d5c942015-09-17 20:55:33 +00003693/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3694/// for validity. Emit an error and return true on failure; return false
3695/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003696bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003697 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003698
3699 if (checkVAStartABI(*this, BuiltinID, Fn))
3700 return true;
3701
Chris Lattner08464942007-12-28 05:29:59 +00003702 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003703 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003704 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003705 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3706 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003707 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003708 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003709 return true;
3710 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003711
3712 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003713 return Diag(TheCall->getLocEnd(),
3714 diag::err_typecheck_call_too_few_args_at_least)
3715 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003716 }
3717
John McCall29ad95b2011-08-27 01:09:30 +00003718 // Type-check the first argument normally.
3719 if (checkBuiltinArgument(*this, TheCall, 0))
3720 return true;
3721
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003722 // Check that the current function is variadic, and get its last parameter.
3723 ParmVarDecl *LastParam;
3724 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003725 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003726
Chris Lattner43be2e62007-12-19 23:59:04 +00003727 // Verify that the second argument to the builtin is the last argument of the
3728 // current function or method.
3729 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003730 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003731
Nico Weber9eea7642013-05-24 23:31:57 +00003732 // These are valid if SecondArgIsLastNamedArgument is false after the next
3733 // block.
3734 QualType Type;
3735 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003736 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003737
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003738 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3739 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003740 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003741
3742 Type = PV->getType();
3743 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003744 IsCRegister =
3745 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003746 }
3747 }
Mike Stump11289f42009-09-09 15:08:12 +00003748
Chris Lattner43be2e62007-12-19 23:59:04 +00003749 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003750 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003751 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003752 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003753 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3754 // Promotable integers are UB, but enumerations need a bit of
3755 // extra checking to see what their promotable type actually is.
3756 if (!Type->isPromotableIntegerType())
3757 return false;
3758 if (!Type->isEnumeralType())
3759 return true;
3760 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3761 return !(ED &&
3762 Context.typesAreCompatible(ED->getPromotionType(), Type));
3763 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003764 unsigned Reason = 0;
3765 if (Type->isReferenceType()) Reason = 1;
3766 else if (IsCRegister) Reason = 2;
3767 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003768 Diag(ParamLoc, diag::note_parameter_type) << Type;
3769 }
3770
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003771 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003772 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003773}
Chris Lattner43be2e62007-12-19 23:59:04 +00003774
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003775bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3776 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3777 // const char *named_addr);
3778
3779 Expr *Func = Call->getCallee();
3780
3781 if (Call->getNumArgs() < 3)
3782 return Diag(Call->getLocEnd(),
3783 diag::err_typecheck_call_too_few_args_at_least)
3784 << 0 /*function call*/ << 3 << Call->getNumArgs();
3785
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003786 // Type-check the first argument normally.
3787 if (checkBuiltinArgument(*this, Call, 0))
3788 return true;
3789
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003790 // Check that the current function is variadic.
3791 if (checkVAStartIsInVariadicFunction(*this, Func))
3792 return true;
3793
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00003794 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003795 unsigned ArgNo;
3796 QualType Type;
3797 } ArgumentTypes[] = {
3798 { 1, Context.getPointerType(Context.CharTy.withConst()) },
3799 { 2, Context.getSizeType() },
3800 };
3801
3802 for (const auto &AT : ArgumentTypes) {
3803 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3804 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3805 continue;
3806 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3807 << Arg->getType() << AT.Type << 1 /* different class */
3808 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3809 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3810 }
3811
3812 return false;
3813}
3814
Chris Lattner2da14fb2007-12-20 00:26:33 +00003815/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3816/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003817bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3818 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003819 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003820 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003821 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003822 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003823 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003824 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003825 << SourceRange(TheCall->getArg(2)->getLocStart(),
3826 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003827
John Wiegley01296292011-04-08 18:41:53 +00003828 ExprResult OrigArg0 = TheCall->getArg(0);
3829 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003830
Chris Lattner2da14fb2007-12-20 00:26:33 +00003831 // Do standard promotions between the two arguments, returning their common
3832 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003833 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003834 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3835 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00003836
3837 // Make sure any conversions are pushed back into the call; this is
3838 // type safe since unordered compare builtins are declared as "_Bool
3839 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00003840 TheCall->setArg(0, OrigArg0.get());
3841 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00003842
John Wiegley01296292011-04-08 18:41:53 +00003843 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00003844 return false;
3845
Chris Lattner2da14fb2007-12-20 00:26:33 +00003846 // If the common type isn't a real floating type, then the arguments were
3847 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003848 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00003849 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003850 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00003851 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3852 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003853
Chris Lattner2da14fb2007-12-20 00:26:33 +00003854 return false;
3855}
3856
Benjamin Kramer634fc102010-02-15 22:42:31 +00003857/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3858/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00003859/// to check everything. We expect the last argument to be a floating point
3860/// value.
3861bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3862 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00003863 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003864 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00003865 if (TheCall->getNumArgs() > NumArgs)
3866 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003867 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003868 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00003869 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003870 (*(TheCall->arg_end()-1))->getLocEnd());
3871
Benjamin Kramer64aae502010-02-16 10:07:31 +00003872 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00003873
Eli Friedman7e4faac2009-08-31 20:06:00 +00003874 if (OrigArg->isTypeDependent())
3875 return false;
3876
Chris Lattner68784ef2010-05-06 05:50:07 +00003877 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00003878 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00003879 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00003880 diag::err_typecheck_call_invalid_unary_fp)
3881 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003882
Neil Hickey88c0fac2016-12-13 16:22:50 +00003883 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00003884 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00003885 // Only remove standard FloatCasts, leaving other casts inplace
3886 if (Cast->getCastKind() == CK_FloatingCast) {
3887 Expr *CastArg = Cast->getSubExpr();
3888 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3889 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3890 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3891 "promotion from float to either float or double is the only expected cast here");
3892 Cast->setSubExpr(nullptr);
3893 TheCall->setArg(NumArgs-1, CastArg);
3894 }
Chris Lattner68784ef2010-05-06 05:50:07 +00003895 }
3896 }
3897
Eli Friedman7e4faac2009-08-31 20:06:00 +00003898 return false;
3899}
3900
Tony Jiangbbc48e92017-05-24 15:13:32 +00003901// Customized Sema Checking for VSX builtins that have the following signature:
3902// vector [...] builtinName(vector [...], vector [...], const int);
3903// Which takes the same type of vectors (any legal vector type) for the first
3904// two arguments and takes compile time constant for the third argument.
3905// Example builtins are :
3906// vector double vec_xxpermdi(vector double, vector double, int);
3907// vector short vec_xxsldwi(vector short, vector short, int);
3908bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
3909 unsigned ExpectedNumArgs = 3;
3910 if (TheCall->getNumArgs() < ExpectedNumArgs)
3911 return Diag(TheCall->getLocEnd(),
3912 diag::err_typecheck_call_too_few_args_at_least)
3913 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3914 << TheCall->getSourceRange();
3915
3916 if (TheCall->getNumArgs() > ExpectedNumArgs)
3917 return Diag(TheCall->getLocEnd(),
3918 diag::err_typecheck_call_too_many_args_at_most)
3919 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
3920 << TheCall->getSourceRange();
3921
3922 // Check the third argument is a compile time constant
3923 llvm::APSInt Value;
3924 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
3925 return Diag(TheCall->getLocStart(),
3926 diag::err_vsx_builtin_nonconstant_argument)
3927 << 3 /* argument index */ << TheCall->getDirectCallee()
3928 << SourceRange(TheCall->getArg(2)->getLocStart(),
3929 TheCall->getArg(2)->getLocEnd());
3930
3931 QualType Arg1Ty = TheCall->getArg(0)->getType();
3932 QualType Arg2Ty = TheCall->getArg(1)->getType();
3933
3934 // Check the type of argument 1 and argument 2 are vectors.
3935 SourceLocation BuiltinLoc = TheCall->getLocStart();
3936 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3937 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
3938 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3939 << TheCall->getDirectCallee()
3940 << SourceRange(TheCall->getArg(0)->getLocStart(),
3941 TheCall->getArg(1)->getLocEnd());
3942 }
3943
3944 // Check the first two arguments are the same type.
3945 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
3946 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3947 << TheCall->getDirectCallee()
3948 << SourceRange(TheCall->getArg(0)->getLocStart(),
3949 TheCall->getArg(1)->getLocEnd());
3950 }
3951
3952 // When default clang type checking is turned off and the customized type
3953 // checking is used, the returning type of the function must be explicitly
3954 // set. Otherwise it is _Bool by default.
3955 TheCall->setType(Arg1Ty);
3956
3957 return false;
3958}
3959
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003960/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3961// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00003962ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00003963 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003964 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00003965 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00003966 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3967 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00003968
Nate Begemana0110022010-06-08 00:16:34 +00003969 // Determine which of the following types of shufflevector we're checking:
3970 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00003971 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00003972 QualType resType = TheCall->getArg(0)->getType();
3973 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00003974
Douglas Gregorc25f7662009-05-19 22:10:17 +00003975 if (!TheCall->getArg(0)->isTypeDependent() &&
3976 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00003977 QualType LHSType = TheCall->getArg(0)->getType();
3978 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00003979
Craig Topperbaca3892013-07-29 06:47:04 +00003980 if (!LHSType->isVectorType() || !RHSType->isVectorType())
3981 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003982 diag::err_vec_builtin_non_vector)
3983 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003984 << SourceRange(TheCall->getArg(0)->getLocStart(),
3985 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00003986
Nate Begemana0110022010-06-08 00:16:34 +00003987 numElements = LHSType->getAs<VectorType>()->getNumElements();
3988 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00003989
Nate Begemana0110022010-06-08 00:16:34 +00003990 // Check to see if we have a call with 2 vector arguments, the unary shuffle
3991 // with mask. If so, verify that RHS is an integer vector type with the
3992 // same number of elts as lhs.
3993 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00003994 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00003995 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00003996 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00003997 diag::err_vec_builtin_incompatible_vector)
3998 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00003999 << SourceRange(TheCall->getArg(1)->getLocStart(),
4000 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004001 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
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(0)->getLocStart(),
4006 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004007 } else if (numElements != numResElements) {
4008 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004009 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004010 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004011 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004012 }
4013
4014 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004015 if (TheCall->getArg(i)->isTypeDependent() ||
4016 TheCall->getArg(i)->isValueDependent())
4017 continue;
4018
Nate Begemana0110022010-06-08 00:16:34 +00004019 llvm::APSInt Result(32);
4020 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4021 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004022 diag::err_shufflevector_nonconstant_argument)
4023 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004024
Craig Topper50ad5b72013-08-03 17:40:38 +00004025 // Allow -1 which will be translated to undef in the IR.
4026 if (Result.isSigned() && Result.isAllOnesValue())
4027 continue;
4028
Chris Lattner7ab824e2008-08-10 02:05:13 +00004029 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004030 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004031 diag::err_shufflevector_argument_too_large)
4032 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004033 }
4034
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004035 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004036
Chris Lattner7ab824e2008-08-10 02:05:13 +00004037 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004038 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004039 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004040 }
4041
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004042 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4043 TheCall->getCallee()->getLocStart(),
4044 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004045}
Chris Lattner43be2e62007-12-19 23:59:04 +00004046
Hal Finkelc4d7c822013-09-18 03:29:45 +00004047/// SemaConvertVectorExpr - Handle __builtin_convertvector
4048ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4049 SourceLocation BuiltinLoc,
4050 SourceLocation RParenLoc) {
4051 ExprValueKind VK = VK_RValue;
4052 ExprObjectKind OK = OK_Ordinary;
4053 QualType DstTy = TInfo->getType();
4054 QualType SrcTy = E->getType();
4055
4056 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4057 return ExprError(Diag(BuiltinLoc,
4058 diag::err_convertvector_non_vector)
4059 << E->getSourceRange());
4060 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4061 return ExprError(Diag(BuiltinLoc,
4062 diag::err_convertvector_non_vector_type));
4063
4064 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4065 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4066 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4067 if (SrcElts != DstElts)
4068 return ExprError(Diag(BuiltinLoc,
4069 diag::err_convertvector_incompatible_vector)
4070 << E->getSourceRange());
4071 }
4072
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004073 return new (Context)
4074 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004075}
4076
Daniel Dunbarb7257262008-07-21 22:59:13 +00004077/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4078// This is declared to take (const void*, ...) and can take two
4079// optional constant int args.
4080bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004081 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004082
Chris Lattner3b054132008-11-19 05:08:23 +00004083 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004084 return Diag(TheCall->getLocEnd(),
4085 diag::err_typecheck_call_too_many_args_at_most)
4086 << 0 /*function call*/ << 3 << NumArgs
4087 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004088
4089 // Argument 0 is checked for us and the remaining arguments must be
4090 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004091 for (unsigned i = 1; i != NumArgs; ++i)
4092 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004093 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004094
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004095 return false;
4096}
4097
Hal Finkelf0417332014-07-17 14:25:55 +00004098/// SemaBuiltinAssume - Handle __assume (MS Extension).
4099// __assume does not evaluate its arguments, and should warn if its argument
4100// has side effects.
4101bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4102 Expr *Arg = TheCall->getArg(0);
4103 if (Arg->isInstantiationDependent()) return false;
4104
4105 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004106 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004107 << Arg->getSourceRange()
4108 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4109
4110 return false;
4111}
4112
David Majnemer86b1bfa2016-10-31 18:07:57 +00004113/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004114/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4115/// than 8.
4116bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4117 // The alignment must be a constant integer.
4118 Expr *Arg = TheCall->getArg(1);
4119
4120 // We can't check the value of a dependent argument.
4121 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004122 if (const auto *UE =
4123 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4124 if (UE->getKind() == UETT_AlignOf)
4125 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4126 << Arg->getSourceRange();
4127
David Majnemer51169932016-10-31 05:37:48 +00004128 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4129
4130 if (!Result.isPowerOf2())
4131 return Diag(TheCall->getLocStart(),
4132 diag::err_alignment_not_power_of_two)
4133 << Arg->getSourceRange();
4134
4135 if (Result < Context.getCharWidth())
4136 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4137 << (unsigned)Context.getCharWidth()
4138 << Arg->getSourceRange();
4139
4140 if (Result > INT32_MAX)
4141 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4142 << INT32_MAX
4143 << Arg->getSourceRange();
4144 }
4145
4146 return false;
4147}
4148
4149/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004150/// as (const void*, size_t, ...) and can take one optional constant int arg.
4151bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4152 unsigned NumArgs = TheCall->getNumArgs();
4153
4154 if (NumArgs > 3)
4155 return Diag(TheCall->getLocEnd(),
4156 diag::err_typecheck_call_too_many_args_at_most)
4157 << 0 /*function call*/ << 3 << NumArgs
4158 << TheCall->getSourceRange();
4159
4160 // The alignment must be a constant integer.
4161 Expr *Arg = TheCall->getArg(1);
4162
4163 // We can't check the value of a dependent argument.
4164 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4165 llvm::APSInt Result;
4166 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4167 return true;
4168
4169 if (!Result.isPowerOf2())
4170 return Diag(TheCall->getLocStart(),
4171 diag::err_alignment_not_power_of_two)
4172 << Arg->getSourceRange();
4173 }
4174
4175 if (NumArgs > 2) {
4176 ExprResult Arg(TheCall->getArg(2));
4177 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4178 Context.getSizeType(), false);
4179 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4180 if (Arg.isInvalid()) return true;
4181 TheCall->setArg(2, Arg.get());
4182 }
Hal Finkelf0417332014-07-17 14:25:55 +00004183
4184 return false;
4185}
4186
Mehdi Amini06d367c2016-10-24 20:39:34 +00004187bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4188 unsigned BuiltinID =
4189 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4190 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4191
4192 unsigned NumArgs = TheCall->getNumArgs();
4193 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4194 if (NumArgs < NumRequiredArgs) {
4195 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4196 << 0 /* function call */ << NumRequiredArgs << NumArgs
4197 << TheCall->getSourceRange();
4198 }
4199 if (NumArgs >= NumRequiredArgs + 0x100) {
4200 return Diag(TheCall->getLocEnd(),
4201 diag::err_typecheck_call_too_many_args_at_most)
4202 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4203 << TheCall->getSourceRange();
4204 }
4205 unsigned i = 0;
4206
4207 // For formatting call, check buffer arg.
4208 if (!IsSizeCall) {
4209 ExprResult Arg(TheCall->getArg(i));
4210 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4211 Context, Context.VoidPtrTy, false);
4212 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4213 if (Arg.isInvalid())
4214 return true;
4215 TheCall->setArg(i, Arg.get());
4216 i++;
4217 }
4218
4219 // Check string literal arg.
4220 unsigned FormatIdx = i;
4221 {
4222 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4223 if (Arg.isInvalid())
4224 return true;
4225 TheCall->setArg(i, Arg.get());
4226 i++;
4227 }
4228
4229 // Make sure variadic args are scalar.
4230 unsigned FirstDataArg = i;
4231 while (i < NumArgs) {
4232 ExprResult Arg = DefaultVariadicArgumentPromotion(
4233 TheCall->getArg(i), VariadicFunction, nullptr);
4234 if (Arg.isInvalid())
4235 return true;
4236 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4237 if (ArgSize.getQuantity() >= 0x100) {
4238 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4239 << i << (int)ArgSize.getQuantity() << 0xff
4240 << TheCall->getSourceRange();
4241 }
4242 TheCall->setArg(i, Arg.get());
4243 i++;
4244 }
4245
4246 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4247 // call to avoid duplicate diagnostics.
4248 if (!IsSizeCall) {
4249 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4250 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4251 bool Success = CheckFormatArguments(
4252 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4253 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4254 CheckedVarArgs);
4255 if (!Success)
4256 return true;
4257 }
4258
4259 if (IsSizeCall) {
4260 TheCall->setType(Context.getSizeType());
4261 } else {
4262 TheCall->setType(Context.VoidPtrTy);
4263 }
4264 return false;
4265}
4266
Eric Christopher8d0c6212010-04-17 02:26:23 +00004267/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4268/// TheCall is a constant expression.
4269bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4270 llvm::APSInt &Result) {
4271 Expr *Arg = TheCall->getArg(ArgNum);
4272 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4273 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4274
4275 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4276
4277 if (!Arg->isIntegerConstantExpr(Result, Context))
4278 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004279 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004280
Chris Lattnerd545ad12009-09-23 06:06:36 +00004281 return false;
4282}
4283
Richard Sandiford28940af2014-04-16 08:47:51 +00004284/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4285/// TheCall is a constant expression in the range [Low, High].
4286bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4287 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004288 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004289
4290 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004291 Expr *Arg = TheCall->getArg(ArgNum);
4292 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004293 return false;
4294
Eric Christopher8d0c6212010-04-17 02:26:23 +00004295 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004296 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004297 return true;
4298
Richard Sandiford28940af2014-04-16 08:47:51 +00004299 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004300 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004301 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004302
4303 return false;
4304}
4305
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004306/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4307/// TheCall is a constant expression is a multiple of Num..
4308bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4309 unsigned Num) {
4310 llvm::APSInt Result;
4311
4312 // We can't check the value of a dependent argument.
4313 Expr *Arg = TheCall->getArg(ArgNum);
4314 if (Arg->isTypeDependent() || Arg->isValueDependent())
4315 return false;
4316
4317 // Check constant-ness first.
4318 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4319 return true;
4320
4321 if (Result.getSExtValue() % Num != 0)
4322 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4323 << Num << Arg->getSourceRange();
4324
4325 return false;
4326}
4327
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004328/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4329/// TheCall is an ARM/AArch64 special register string literal.
4330bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4331 int ArgNum, unsigned ExpectedFieldNum,
4332 bool AllowName) {
4333 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4334 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4335 BuiltinID == ARM::BI__builtin_arm_rsr ||
4336 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4337 BuiltinID == ARM::BI__builtin_arm_wsr ||
4338 BuiltinID == ARM::BI__builtin_arm_wsrp;
4339 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4340 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4341 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4342 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4343 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4344 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4345 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4346
4347 // We can't check the value of a dependent argument.
4348 Expr *Arg = TheCall->getArg(ArgNum);
4349 if (Arg->isTypeDependent() || Arg->isValueDependent())
4350 return false;
4351
4352 // Check if the argument is a string literal.
4353 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4354 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4355 << Arg->getSourceRange();
4356
4357 // Check the type of special register given.
4358 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4359 SmallVector<StringRef, 6> Fields;
4360 Reg.split(Fields, ":");
4361
4362 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4363 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4364 << Arg->getSourceRange();
4365
4366 // If the string is the name of a register then we cannot check that it is
4367 // valid here but if the string is of one the forms described in ACLE then we
4368 // can check that the supplied fields are integers and within the valid
4369 // ranges.
4370 if (Fields.size() > 1) {
4371 bool FiveFields = Fields.size() == 5;
4372
4373 bool ValidString = true;
4374 if (IsARMBuiltin) {
4375 ValidString &= Fields[0].startswith_lower("cp") ||
4376 Fields[0].startswith_lower("p");
4377 if (ValidString)
4378 Fields[0] =
4379 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4380
4381 ValidString &= Fields[2].startswith_lower("c");
4382 if (ValidString)
4383 Fields[2] = Fields[2].drop_front(1);
4384
4385 if (FiveFields) {
4386 ValidString &= Fields[3].startswith_lower("c");
4387 if (ValidString)
4388 Fields[3] = Fields[3].drop_front(1);
4389 }
4390 }
4391
4392 SmallVector<int, 5> Ranges;
4393 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004394 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004395 else
4396 Ranges.append({15, 7, 15});
4397
4398 for (unsigned i=0; i<Fields.size(); ++i) {
4399 int IntField;
4400 ValidString &= !Fields[i].getAsInteger(10, IntField);
4401 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4402 }
4403
4404 if (!ValidString)
4405 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4406 << Arg->getSourceRange();
4407
4408 } else if (IsAArch64Builtin && Fields.size() == 1) {
4409 // If the register name is one of those that appear in the condition below
4410 // and the special register builtin being used is one of the write builtins,
4411 // then we require that the argument provided for writing to the register
4412 // is an integer constant expression. This is because it will be lowered to
4413 // an MSR (immediate) instruction, so we need to know the immediate at
4414 // compile time.
4415 if (TheCall->getNumArgs() != 2)
4416 return false;
4417
4418 std::string RegLower = Reg.lower();
4419 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4420 RegLower != "pan" && RegLower != "uao")
4421 return false;
4422
4423 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4424 }
4425
4426 return false;
4427}
4428
Eli Friedmanc97d0142009-05-03 06:04:26 +00004429/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004430/// This checks that the target supports __builtin_longjmp and
4431/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004432bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004433 if (!Context.getTargetInfo().hasSjLjLowering())
4434 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4435 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4436
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004437 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004438 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004439
Eric Christopher8d0c6212010-04-17 02:26:23 +00004440 // TODO: This is less than ideal. Overload this to take a value.
4441 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4442 return true;
4443
4444 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004445 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4446 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4447
4448 return false;
4449}
4450
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004451/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4452/// This checks that the target supports __builtin_setjmp.
4453bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4454 if (!Context.getTargetInfo().hasSjLjLowering())
4455 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4456 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4457 return false;
4458}
4459
Richard Smithd7293d72013-08-05 18:49:43 +00004460namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004461class UncoveredArgHandler {
4462 enum { Unknown = -1, AllCovered = -2 };
4463 signed FirstUncoveredArg;
4464 SmallVector<const Expr *, 4> DiagnosticExprs;
4465
4466public:
4467 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4468
4469 bool hasUncoveredArg() const {
4470 return (FirstUncoveredArg >= 0);
4471 }
4472
4473 unsigned getUncoveredArg() const {
4474 assert(hasUncoveredArg() && "no uncovered argument");
4475 return FirstUncoveredArg;
4476 }
4477
4478 void setAllCovered() {
4479 // A string has been found with all arguments covered, so clear out
4480 // the diagnostics.
4481 DiagnosticExprs.clear();
4482 FirstUncoveredArg = AllCovered;
4483 }
4484
4485 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4486 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4487
4488 // Don't update if a previous string covers all arguments.
4489 if (FirstUncoveredArg == AllCovered)
4490 return;
4491
4492 // UncoveredArgHandler tracks the highest uncovered argument index
4493 // and with it all the strings that match this index.
4494 if (NewFirstUncoveredArg == FirstUncoveredArg)
4495 DiagnosticExprs.push_back(StrExpr);
4496 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4497 DiagnosticExprs.clear();
4498 DiagnosticExprs.push_back(StrExpr);
4499 FirstUncoveredArg = NewFirstUncoveredArg;
4500 }
4501 }
4502
4503 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4504};
4505
Richard Smithd7293d72013-08-05 18:49:43 +00004506enum StringLiteralCheckType {
4507 SLCT_NotALiteral,
4508 SLCT_UncheckedLiteral,
4509 SLCT_CheckedLiteral
4510};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004511} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004512
Stephen Hines648c3692016-09-16 01:07:04 +00004513static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4514 BinaryOperatorKind BinOpKind,
4515 bool AddendIsRight) {
4516 unsigned BitWidth = Offset.getBitWidth();
4517 unsigned AddendBitWidth = Addend.getBitWidth();
4518 // There might be negative interim results.
4519 if (Addend.isUnsigned()) {
4520 Addend = Addend.zext(++AddendBitWidth);
4521 Addend.setIsSigned(true);
4522 }
4523 // Adjust the bit width of the APSInts.
4524 if (AddendBitWidth > BitWidth) {
4525 Offset = Offset.sext(AddendBitWidth);
4526 BitWidth = AddendBitWidth;
4527 } else if (BitWidth > AddendBitWidth) {
4528 Addend = Addend.sext(BitWidth);
4529 }
4530
4531 bool Ov = false;
4532 llvm::APSInt ResOffset = Offset;
4533 if (BinOpKind == BO_Add)
4534 ResOffset = Offset.sadd_ov(Addend, Ov);
4535 else {
4536 assert(AddendIsRight && BinOpKind == BO_Sub &&
4537 "operator must be add or sub with addend on the right");
4538 ResOffset = Offset.ssub_ov(Addend, Ov);
4539 }
4540
4541 // We add an offset to a pointer here so we should support an offset as big as
4542 // possible.
4543 if (Ov) {
4544 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004545 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004546 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4547 return;
4548 }
4549
4550 Offset = ResOffset;
4551}
4552
4553namespace {
4554// This is a wrapper class around StringLiteral to support offsetted string
4555// literals as format strings. It takes the offset into account when returning
4556// the string and its length or the source locations to display notes correctly.
4557class FormatStringLiteral {
4558 const StringLiteral *FExpr;
4559 int64_t Offset;
4560
4561 public:
4562 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4563 : FExpr(fexpr), Offset(Offset) {}
4564
4565 StringRef getString() const {
4566 return FExpr->getString().drop_front(Offset);
4567 }
4568
4569 unsigned getByteLength() const {
4570 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4571 }
4572 unsigned getLength() const { return FExpr->getLength() - Offset; }
4573 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4574
4575 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4576
4577 QualType getType() const { return FExpr->getType(); }
4578
4579 bool isAscii() const { return FExpr->isAscii(); }
4580 bool isWide() const { return FExpr->isWide(); }
4581 bool isUTF8() const { return FExpr->isUTF8(); }
4582 bool isUTF16() const { return FExpr->isUTF16(); }
4583 bool isUTF32() const { return FExpr->isUTF32(); }
4584 bool isPascal() const { return FExpr->isPascal(); }
4585
4586 SourceLocation getLocationOfByte(
4587 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4588 const TargetInfo &Target, unsigned *StartToken = nullptr,
4589 unsigned *StartTokenByteOffset = nullptr) const {
4590 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4591 StartToken, StartTokenByteOffset);
4592 }
4593
4594 SourceLocation getLocStart() const LLVM_READONLY {
4595 return FExpr->getLocStart().getLocWithOffset(Offset);
4596 }
4597 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4598};
4599} // end anonymous namespace
4600
4601static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004602 const Expr *OrigFormatExpr,
4603 ArrayRef<const Expr *> Args,
4604 bool HasVAListArg, unsigned format_idx,
4605 unsigned firstDataArg,
4606 Sema::FormatStringType Type,
4607 bool inFunctionCall,
4608 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004609 llvm::SmallBitVector &CheckedVarArgs,
4610 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004611
Richard Smith55ce3522012-06-25 20:30:08 +00004612// Determine if an expression is a string literal or constant string.
4613// If this function returns false on the arguments to a function expecting a
4614// format string, we will usually need to emit a warning.
4615// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004616static StringLiteralCheckType
4617checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4618 bool HasVAListArg, unsigned format_idx,
4619 unsigned firstDataArg, Sema::FormatStringType Type,
4620 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004621 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004622 UncoveredArgHandler &UncoveredArg,
4623 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004624 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004625 assert(Offset.isSigned() && "invalid offset");
4626
Douglas Gregorc25f7662009-05-19 22:10:17 +00004627 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004628 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004629
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004630 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004631
Richard Smithd7293d72013-08-05 18:49:43 +00004632 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004633 // Technically -Wformat-nonliteral does not warn about this case.
4634 // The behavior of printf and friends in this case is implementation
4635 // dependent. Ideally if the format string cannot be null then
4636 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004637 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004638
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004639 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004640 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004641 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004642 // The expression is a literal if both sub-expressions were, and it was
4643 // completely checked only if both sub-expressions were checked.
4644 const AbstractConditionalOperator *C =
4645 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004646
4647 // Determine whether it is necessary to check both sub-expressions, for
4648 // example, because the condition expression is a constant that can be
4649 // evaluated at compile time.
4650 bool CheckLeft = true, CheckRight = true;
4651
4652 bool Cond;
4653 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4654 if (Cond)
4655 CheckRight = false;
4656 else
4657 CheckLeft = false;
4658 }
4659
Stephen Hines648c3692016-09-16 01:07:04 +00004660 // We need to maintain the offsets for the right and the left hand side
4661 // separately to check if every possible indexed expression is a valid
4662 // string literal. They might have different offsets for different string
4663 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004664 StringLiteralCheckType Left;
4665 if (!CheckLeft)
4666 Left = SLCT_UncheckedLiteral;
4667 else {
4668 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4669 HasVAListArg, format_idx, firstDataArg,
4670 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004671 CheckedVarArgs, UncoveredArg, Offset);
4672 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004673 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004674 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004675 }
4676
Richard Smith55ce3522012-06-25 20:30:08 +00004677 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004678 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004679 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004680 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004681 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004682
4683 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004684 }
4685
4686 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004687 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4688 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004689 }
4690
John McCallc07a0c72011-02-17 10:25:35 +00004691 case Stmt::OpaqueValueExprClass:
4692 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4693 E = src;
4694 goto tryAgain;
4695 }
Richard Smith55ce3522012-06-25 20:30:08 +00004696 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004697
Ted Kremeneka8890832011-02-24 23:03:04 +00004698 case Stmt::PredefinedExprClass:
4699 // While __func__, etc., are technically not string literals, they
4700 // cannot contain format specifiers and thus are not a security
4701 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004702 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004703
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004704 case Stmt::DeclRefExprClass: {
4705 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004706
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004707 // As an exception, do not flag errors for variables binding to
4708 // const string literals.
4709 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4710 bool isConstant = false;
4711 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004712
Richard Smithd7293d72013-08-05 18:49:43 +00004713 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4714 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004715 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004716 isConstant = T.isConstant(S.Context) &&
4717 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004718 } else if (T->isObjCObjectPointerType()) {
4719 // In ObjC, there is usually no "const ObjectPointer" type,
4720 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004721 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004722 }
Mike Stump11289f42009-09-09 15:08:12 +00004723
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004724 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004725 if (const Expr *Init = VD->getAnyInitializer()) {
4726 // Look through initializers like const char c[] = { "foo" }
4727 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4728 if (InitList->isStringLiteralInit())
4729 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4730 }
Richard Smithd7293d72013-08-05 18:49:43 +00004731 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004732 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004733 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004734 /*InFunctionCall*/ false, CheckedVarArgs,
4735 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004736 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004737 }
Mike Stump11289f42009-09-09 15:08:12 +00004738
Anders Carlssonb012ca92009-06-28 19:55:58 +00004739 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4740 // special check to see if the format string is a function parameter
4741 // of the function calling the printf function. If the function
4742 // has an attribute indicating it is a printf-like function, then we
4743 // should suppress warnings concerning non-literals being used in a call
4744 // to a vprintf function. For example:
4745 //
4746 // void
4747 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4748 // va_list ap;
4749 // va_start(ap, fmt);
4750 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4751 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004752 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004753 if (HasVAListArg) {
4754 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4755 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4756 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004757 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004758 // adjust for implicit parameter
4759 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4760 if (MD->isInstance())
4761 ++PVIndex;
4762 // We also check if the formats are compatible.
4763 // We can't pass a 'scanf' string to a 'printf' function.
4764 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004765 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004766 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004767 }
4768 }
4769 }
4770 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004771 }
Mike Stump11289f42009-09-09 15:08:12 +00004772
Richard Smith55ce3522012-06-25 20:30:08 +00004773 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004774 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004775
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004776 case Stmt::CallExprClass:
4777 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004778 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004779 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4780 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4781 unsigned ArgIndex = FA->getFormatIdx();
4782 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4783 if (MD->isInstance())
4784 --ArgIndex;
4785 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004786
Richard Smithd7293d72013-08-05 18:49:43 +00004787 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004788 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004789 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004790 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004791 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4792 unsigned BuiltinID = FD->getBuiltinID();
4793 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4794 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4795 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004796 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004797 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004798 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004799 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004800 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004801 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004802 }
4803 }
Mike Stump11289f42009-09-09 15:08:12 +00004804
Richard Smith55ce3522012-06-25 20:30:08 +00004805 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004806 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004807 case Stmt::ObjCMessageExprClass: {
4808 const auto *ME = cast<ObjCMessageExpr>(E);
4809 if (const auto *ND = ME->getMethodDecl()) {
4810 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4811 unsigned ArgIndex = FA->getFormatIdx();
4812 const Expr *Arg = ME->getArg(ArgIndex - 1);
4813 return checkFormatStringExpr(
4814 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4815 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4816 }
4817 }
4818
4819 return SLCT_NotALiteral;
4820 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004821 case Stmt::ObjCStringLiteralClass:
4822 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004823 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004824
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004825 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004826 StrE = ObjCFExpr->getString();
4827 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004828 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004829
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004830 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004831 if (Offset.isNegative() || Offset > StrE->getLength()) {
4832 // TODO: It would be better to have an explicit warning for out of
4833 // bounds literals.
4834 return SLCT_NotALiteral;
4835 }
4836 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4837 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004838 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004839 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00004840 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004841 }
Mike Stump11289f42009-09-09 15:08:12 +00004842
Richard Smith55ce3522012-06-25 20:30:08 +00004843 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004844 }
Stephen Hines648c3692016-09-16 01:07:04 +00004845 case Stmt::BinaryOperatorClass: {
4846 llvm::APSInt LResult;
4847 llvm::APSInt RResult;
4848
4849 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4850
4851 // A string literal + an int offset is still a string literal.
4852 if (BinOp->isAdditiveOp()) {
4853 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4854 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4855
4856 if (LIsInt != RIsInt) {
4857 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4858
4859 if (LIsInt) {
4860 if (BinOpKind == BO_Add) {
4861 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4862 E = BinOp->getRHS();
4863 goto tryAgain;
4864 }
4865 } else {
4866 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4867 E = BinOp->getLHS();
4868 goto tryAgain;
4869 }
4870 }
Stephen Hines648c3692016-09-16 01:07:04 +00004871 }
George Burgess IVd273aab2016-09-22 00:00:26 +00004872
4873 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00004874 }
4875 case Stmt::UnaryOperatorClass: {
4876 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4877 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4878 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4879 llvm::APSInt IndexResult;
4880 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4881 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4882 E = ASE->getBase();
4883 goto tryAgain;
4884 }
4885 }
4886
4887 return SLCT_NotALiteral;
4888 }
Mike Stump11289f42009-09-09 15:08:12 +00004889
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004890 default:
Richard Smith55ce3522012-06-25 20:30:08 +00004891 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004892 }
4893}
4894
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004895Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00004896 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00004897 .Case("scanf", FST_Scanf)
4898 .Cases("printf", "printf0", FST_Printf)
4899 .Cases("NSString", "CFString", FST_NSString)
4900 .Case("strftime", FST_Strftime)
4901 .Case("strfmon", FST_Strfmon)
4902 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4903 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4904 .Case("os_trace", FST_OSLog)
4905 .Case("os_log", FST_OSLog)
4906 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004907}
4908
Jordan Rose3e0ec582012-07-19 18:10:23 +00004909/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00004910/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00004911/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004912bool Sema::CheckFormatArguments(const FormatAttr *Format,
4913 ArrayRef<const Expr *> Args,
4914 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004915 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004916 SourceLocation Loc, SourceRange Range,
4917 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00004918 FormatStringInfo FSI;
4919 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004920 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00004921 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00004922 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00004923 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004924}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00004925
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004926bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004927 bool HasVAListArg, unsigned format_idx,
4928 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004929 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00004930 SourceLocation Loc, SourceRange Range,
4931 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004932 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004933 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004934 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00004935 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004936 }
Mike Stump11289f42009-09-09 15:08:12 +00004937
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004938 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004939
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004940 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00004941 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00004942 // Dynamically generated format strings are difficult to
4943 // automatically vet at compile time. Requiring that format strings
4944 // are string literals: (1) permits the checking of format strings by
4945 // the compiler and thereby (2) can practically remove the source of
4946 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00004947
Mike Stump11289f42009-09-09 15:08:12 +00004948 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00004949 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00004950 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00004951 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004952 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00004953 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00004954 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4955 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004956 /*IsFunctionCall*/ true, CheckedVarArgs,
4957 UncoveredArg,
4958 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004959
4960 // Generate a diagnostic where an uncovered argument is detected.
4961 if (UncoveredArg.hasUncoveredArg()) {
4962 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4963 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4964 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4965 }
4966
Richard Smith55ce3522012-06-25 20:30:08 +00004967 if (CT != SLCT_NotALiteral)
4968 // Literal format string found, check done!
4969 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00004970
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004971 // Strftime is particular as it always uses a single 'time' argument,
4972 // so it is safe to pass a non-literal string.
4973 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00004974 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00004975
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004976 // Do not emit diag when the string param is a macro expansion and the
4977 // format is either NSString or CFString. This is a hack to prevent
4978 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4979 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004980 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4981 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00004982 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00004983
Chris Lattnercc5d1c22009-04-29 04:59:47 +00004984 // If there are no arguments specified, warn with -Wformat-security, otherwise
4985 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004986 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00004987 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4988 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004989 switch (Type) {
4990 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004991 break;
4992 case FST_Kprintf:
4993 case FST_FreeBSDKPrintf:
4994 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00004995 Diag(FormatLoc, diag::note_format_security_fixit)
4996 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00004997 break;
4998 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00004999 Diag(FormatLoc, diag::note_format_security_fixit)
5000 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005001 break;
5002 }
5003 } else {
5004 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005005 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005006 }
Richard Smith55ce3522012-06-25 20:30:08 +00005007 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005008}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005009
Ted Kremenekab278de2010-01-28 23:39:18 +00005010namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005011class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5012protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005013 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005014 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005015 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005016 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005017 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005018 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005019 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005020 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005021 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005022 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005023 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005024 bool usesPositionalArgs;
5025 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005026 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005027 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005028 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005029 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005030
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005031public:
Stephen Hines648c3692016-09-16 01:07:04 +00005032 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005033 const Expr *origFormatExpr,
5034 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005035 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005036 ArrayRef<const Expr *> Args, unsigned formatIdx,
5037 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005038 llvm::SmallBitVector &CheckedVarArgs,
5039 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005040 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5041 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5042 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5043 usesPositionalArgs(false), atFirstArg(true),
5044 inFunctionCall(inFunctionCall), CallType(callType),
5045 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005046 CoveredArgs.resize(numDataArgs);
5047 CoveredArgs.reset();
5048 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005049
Ted Kremenek019d2242010-01-29 01:50:07 +00005050 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005051
Ted Kremenek02087932010-07-16 02:11:22 +00005052 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005053 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005054
Jordan Rose92303592012-09-08 04:00:03 +00005055 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005056 const analyze_format_string::FormatSpecifier &FS,
5057 const analyze_format_string::ConversionSpecifier &CS,
5058 const char *startSpecifier, unsigned specifierLen,
5059 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005060
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005061 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005062 const analyze_format_string::FormatSpecifier &FS,
5063 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005064
5065 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005066 const analyze_format_string::ConversionSpecifier &CS,
5067 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005068
Craig Toppere14c0f82014-03-12 04:55:44 +00005069 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005070
Craig Toppere14c0f82014-03-12 04:55:44 +00005071 void HandleInvalidPosition(const char *startSpecifier,
5072 unsigned specifierLen,
5073 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005074
Craig Toppere14c0f82014-03-12 04:55:44 +00005075 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005076
Craig Toppere14c0f82014-03-12 04:55:44 +00005077 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005078
Richard Trieu03cf7b72011-10-28 00:41:25 +00005079 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005080 static void
5081 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5082 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5083 bool IsStringLocation, Range StringRange,
5084 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005085
Ted Kremenek02087932010-07-16 02:11:22 +00005086protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005087 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5088 const char *startSpec,
5089 unsigned specifierLen,
5090 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005091
5092 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5093 const char *startSpec,
5094 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005095
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005096 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005097 CharSourceRange getSpecifierRange(const char *startSpecifier,
5098 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005099 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005100
Ted Kremenek5739de72010-01-29 01:06:55 +00005101 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005102
5103 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5104 const analyze_format_string::ConversionSpecifier &CS,
5105 const char *startSpecifier, unsigned specifierLen,
5106 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005107
5108 template <typename Range>
5109 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5110 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005111 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005112};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005113} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005114
Ted Kremenek02087932010-07-16 02:11:22 +00005115SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005116 return OrigFormatExpr->getSourceRange();
5117}
5118
Ted Kremenek02087932010-07-16 02:11:22 +00005119CharSourceRange CheckFormatHandler::
5120getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005121 SourceLocation Start = getLocationOfByte(startSpecifier);
5122 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5123
5124 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005125 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005126
5127 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005128}
5129
Ted Kremenek02087932010-07-16 02:11:22 +00005130SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005131 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5132 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005133}
5134
Ted Kremenek02087932010-07-16 02:11:22 +00005135void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5136 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005137 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5138 getLocationOfByte(startSpecifier),
5139 /*IsStringLocation*/true,
5140 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005141}
5142
Jordan Rose92303592012-09-08 04:00:03 +00005143void CheckFormatHandler::HandleInvalidLengthModifier(
5144 const analyze_format_string::FormatSpecifier &FS,
5145 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005146 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005147 using namespace analyze_format_string;
5148
5149 const LengthModifier &LM = FS.getLengthModifier();
5150 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5151
5152 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005153 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005154 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005155 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005156 getLocationOfByte(LM.getStart()),
5157 /*IsStringLocation*/true,
5158 getSpecifierRange(startSpecifier, specifierLen));
5159
5160 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5161 << FixedLM->toString()
5162 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5163
5164 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005165 FixItHint Hint;
5166 if (DiagID == diag::warn_format_nonsensical_length)
5167 Hint = FixItHint::CreateRemoval(LMRange);
5168
5169 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005170 getLocationOfByte(LM.getStart()),
5171 /*IsStringLocation*/true,
5172 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005173 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005174 }
5175}
5176
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005177void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005178 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005179 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005180 using namespace analyze_format_string;
5181
5182 const LengthModifier &LM = FS.getLengthModifier();
5183 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5184
5185 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005186 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005187 if (FixedLM) {
5188 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5189 << LM.toString() << 0,
5190 getLocationOfByte(LM.getStart()),
5191 /*IsStringLocation*/true,
5192 getSpecifierRange(startSpecifier, specifierLen));
5193
5194 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5195 << FixedLM->toString()
5196 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5197
5198 } else {
5199 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5200 << LM.toString() << 0,
5201 getLocationOfByte(LM.getStart()),
5202 /*IsStringLocation*/true,
5203 getSpecifierRange(startSpecifier, specifierLen));
5204 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005205}
5206
5207void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5208 const analyze_format_string::ConversionSpecifier &CS,
5209 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005210 using namespace analyze_format_string;
5211
5212 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005213 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005214 if (FixedCS) {
5215 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5216 << CS.toString() << /*conversion specifier*/1,
5217 getLocationOfByte(CS.getStart()),
5218 /*IsStringLocation*/true,
5219 getSpecifierRange(startSpecifier, specifierLen));
5220
5221 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5222 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5223 << FixedCS->toString()
5224 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5225 } else {
5226 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5227 << CS.toString() << /*conversion specifier*/1,
5228 getLocationOfByte(CS.getStart()),
5229 /*IsStringLocation*/true,
5230 getSpecifierRange(startSpecifier, specifierLen));
5231 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005232}
5233
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005234void CheckFormatHandler::HandlePosition(const char *startPos,
5235 unsigned posLen) {
5236 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5237 getLocationOfByte(startPos),
5238 /*IsStringLocation*/true,
5239 getSpecifierRange(startPos, posLen));
5240}
5241
Ted Kremenekd1668192010-02-27 01:41:03 +00005242void
Ted Kremenek02087932010-07-16 02:11:22 +00005243CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5244 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005245 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5246 << (unsigned) p,
5247 getLocationOfByte(startPos), /*IsStringLocation*/true,
5248 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005249}
5250
Ted Kremenek02087932010-07-16 02:11:22 +00005251void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005252 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005253 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5254 getLocationOfByte(startPos),
5255 /*IsStringLocation*/true,
5256 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005257}
5258
Ted Kremenek02087932010-07-16 02:11:22 +00005259void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005260 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005261 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005262 EmitFormatDiagnostic(
5263 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5264 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5265 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005266 }
Ted Kremenek02087932010-07-16 02:11:22 +00005267}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005268
Jordan Rose58bbe422012-07-19 18:10:08 +00005269// Note that this may return NULL if there was an error parsing or building
5270// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005271const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005272 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005273}
5274
5275void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005276 // Does the number of data arguments exceed the number of
5277 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005278 if (!HasVAListArg) {
5279 // Find any arguments that weren't covered.
5280 CoveredArgs.flip();
5281 signed notCoveredArg = CoveredArgs.find_first();
5282 if (notCoveredArg >= 0) {
5283 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005284 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5285 } else {
5286 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005287 }
5288 }
5289}
5290
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005291void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5292 const Expr *ArgExpr) {
5293 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5294 "Invalid state");
5295
5296 if (!ArgExpr)
5297 return;
5298
5299 SourceLocation Loc = ArgExpr->getLocStart();
5300
5301 if (S.getSourceManager().isInSystemMacro(Loc))
5302 return;
5303
5304 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5305 for (auto E : DiagnosticExprs)
5306 PDiag << E->getSourceRange();
5307
5308 CheckFormatHandler::EmitFormatDiagnostic(
5309 S, IsFunctionCall, DiagnosticExprs[0],
5310 PDiag, Loc, /*IsStringLocation*/false,
5311 DiagnosticExprs[0]->getSourceRange());
5312}
5313
Ted Kremenekce815422010-07-19 21:25:57 +00005314bool
5315CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5316 SourceLocation Loc,
5317 const char *startSpec,
5318 unsigned specifierLen,
5319 const char *csStart,
5320 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005321 bool keepGoing = true;
5322 if (argIndex < NumDataArgs) {
5323 // Consider the argument coverered, even though the specifier doesn't
5324 // make sense.
5325 CoveredArgs.set(argIndex);
5326 }
5327 else {
5328 // If argIndex exceeds the number of data arguments we
5329 // don't issue a warning because that is just a cascade of warnings (and
5330 // they may have intended '%%' anyway). We don't want to continue processing
5331 // the format string after this point, however, as we will like just get
5332 // gibberish when trying to match arguments.
5333 keepGoing = false;
5334 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005335
5336 StringRef Specifier(csStart, csLen);
5337
5338 // If the specifier in non-printable, it could be the first byte of a UTF-8
5339 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5340 // hex value.
5341 std::string CodePointStr;
5342 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005343 llvm::UTF32 CodePoint;
5344 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5345 const llvm::UTF8 *E =
5346 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5347 llvm::ConversionResult Result =
5348 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005349
Justin Lebar90910552016-09-30 00:38:45 +00005350 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005351 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005352 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005353 }
5354
5355 llvm::raw_string_ostream OS(CodePointStr);
5356 if (CodePoint < 256)
5357 OS << "\\x" << llvm::format("%02x", CodePoint);
5358 else if (CodePoint <= 0xFFFF)
5359 OS << "\\u" << llvm::format("%04x", CodePoint);
5360 else
5361 OS << "\\U" << llvm::format("%08x", CodePoint);
5362 OS.flush();
5363 Specifier = CodePointStr;
5364 }
5365
5366 EmitFormatDiagnostic(
5367 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5368 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5369
Ted Kremenekce815422010-07-19 21:25:57 +00005370 return keepGoing;
5371}
5372
Richard Trieu03cf7b72011-10-28 00:41:25 +00005373void
5374CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5375 const char *startSpec,
5376 unsigned specifierLen) {
5377 EmitFormatDiagnostic(
5378 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5379 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5380}
5381
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005382bool
5383CheckFormatHandler::CheckNumArgs(
5384 const analyze_format_string::FormatSpecifier &FS,
5385 const analyze_format_string::ConversionSpecifier &CS,
5386 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5387
5388 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005389 PartialDiagnostic PDiag = FS.usesPositionalArg()
5390 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5391 << (argIndex+1) << NumDataArgs)
5392 : S.PDiag(diag::warn_printf_insufficient_data_args);
5393 EmitFormatDiagnostic(
5394 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5395 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005396
5397 // Since more arguments than conversion tokens are given, by extension
5398 // all arguments are covered, so mark this as so.
5399 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005400 return false;
5401 }
5402 return true;
5403}
5404
Richard Trieu03cf7b72011-10-28 00:41:25 +00005405template<typename Range>
5406void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5407 SourceLocation Loc,
5408 bool IsStringLocation,
5409 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005410 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005411 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005412 Loc, IsStringLocation, StringRange, FixIt);
5413}
5414
5415/// \brief If the format string is not within the funcion call, emit a note
5416/// so that the function call and string are in diagnostic messages.
5417///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005418/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005419/// call and only one diagnostic message will be produced. Otherwise, an
5420/// extra note will be emitted pointing to location of the format string.
5421///
5422/// \param ArgumentExpr the expression that is passed as the format string
5423/// argument in the function call. Used for getting locations when two
5424/// diagnostics are emitted.
5425///
5426/// \param PDiag the callee should already have provided any strings for the
5427/// diagnostic message. This function only adds locations and fixits
5428/// to diagnostics.
5429///
5430/// \param Loc primary location for diagnostic. If two diagnostics are
5431/// required, one will be at Loc and a new SourceLocation will be created for
5432/// the other one.
5433///
5434/// \param IsStringLocation if true, Loc points to the format string should be
5435/// used for the note. Otherwise, Loc points to the argument list and will
5436/// be used with PDiag.
5437///
5438/// \param StringRange some or all of the string to highlight. This is
5439/// templated so it can accept either a CharSourceRange or a SourceRange.
5440///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005441/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005442template <typename Range>
5443void CheckFormatHandler::EmitFormatDiagnostic(
5444 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5445 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5446 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005447 if (InFunctionCall) {
5448 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5449 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005450 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005451 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005452 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5453 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005454
5455 const Sema::SemaDiagnosticBuilder &Note =
5456 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5457 diag::note_format_string_defined);
5458
5459 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005460 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005461 }
5462}
5463
Ted Kremenek02087932010-07-16 02:11:22 +00005464//===--- CHECK: Printf format string checking ------------------------------===//
5465
5466namespace {
5467class CheckPrintfHandler : public CheckFormatHandler {
5468public:
Stephen Hines648c3692016-09-16 01:07:04 +00005469 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005470 const Expr *origFormatExpr,
5471 const Sema::FormatStringType type, unsigned firstDataArg,
5472 unsigned numDataArgs, bool isObjC, const char *beg,
5473 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005474 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005475 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005476 llvm::SmallBitVector &CheckedVarArgs,
5477 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005478 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5479 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5480 inFunctionCall, CallType, CheckedVarArgs,
5481 UncoveredArg) {}
5482
5483 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5484
5485 /// Returns true if '%@' specifiers are allowed in the format string.
5486 bool allowsObjCArg() const {
5487 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5488 FSType == Sema::FST_OSTrace;
5489 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005490
Ted Kremenek02087932010-07-16 02:11:22 +00005491 bool HandleInvalidPrintfConversionSpecifier(
5492 const analyze_printf::PrintfSpecifier &FS,
5493 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005494 unsigned specifierLen) override;
5495
Ted Kremenek02087932010-07-16 02:11:22 +00005496 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5497 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005498 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005499 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5500 const char *StartSpecifier,
5501 unsigned SpecifierLen,
5502 const Expr *E);
5503
Ted Kremenek02087932010-07-16 02:11:22 +00005504 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5505 const char *startSpecifier, unsigned specifierLen);
5506 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5507 const analyze_printf::OptionalAmount &Amt,
5508 unsigned type,
5509 const char *startSpecifier, unsigned specifierLen);
5510 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5511 const analyze_printf::OptionalFlag &flag,
5512 const char *startSpecifier, unsigned specifierLen);
5513 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5514 const analyze_printf::OptionalFlag &ignoredFlag,
5515 const analyze_printf::OptionalFlag &flag,
5516 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005517 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005518 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005519
5520 void HandleEmptyObjCModifierFlag(const char *startFlag,
5521 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005522
Ted Kremenek2b417712015-07-02 05:39:16 +00005523 void HandleInvalidObjCModifierFlag(const char *startFlag,
5524 unsigned flagLen) override;
5525
5526 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5527 const char *flagsEnd,
5528 const char *conversionPosition)
5529 override;
5530};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005531} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005532
5533bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5534 const analyze_printf::PrintfSpecifier &FS,
5535 const char *startSpecifier,
5536 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005537 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005538 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005539
Ted Kremenekce815422010-07-19 21:25:57 +00005540 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5541 getLocationOfByte(CS.getStart()),
5542 startSpecifier, specifierLen,
5543 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005544}
5545
Ted Kremenek02087932010-07-16 02:11:22 +00005546bool CheckPrintfHandler::HandleAmount(
5547 const analyze_format_string::OptionalAmount &Amt,
5548 unsigned k, const char *startSpecifier,
5549 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005550 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005551 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005552 unsigned argIndex = Amt.getArgIndex();
5553 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005554 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5555 << k,
5556 getLocationOfByte(Amt.getStart()),
5557 /*IsStringLocation*/true,
5558 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005559 // Don't do any more checking. We will just emit
5560 // spurious errors.
5561 return false;
5562 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005563
Ted Kremenek5739de72010-01-29 01:06:55 +00005564 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005565 // Although not in conformance with C99, we also allow the argument to be
5566 // an 'unsigned int' as that is a reasonably safe case. GCC also
5567 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005568 CoveredArgs.set(argIndex);
5569 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005570 if (!Arg)
5571 return false;
5572
Ted Kremenek5739de72010-01-29 01:06:55 +00005573 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005574
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005575 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5576 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005577
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005578 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005579 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005580 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005581 << T << Arg->getSourceRange(),
5582 getLocationOfByte(Amt.getStart()),
5583 /*IsStringLocation*/true,
5584 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005585 // Don't do any more checking. We will just emit
5586 // spurious errors.
5587 return false;
5588 }
5589 }
5590 }
5591 return true;
5592}
Ted Kremenek5739de72010-01-29 01:06:55 +00005593
Tom Careb49ec692010-06-17 19:00:27 +00005594void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005595 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005596 const analyze_printf::OptionalAmount &Amt,
5597 unsigned type,
5598 const char *startSpecifier,
5599 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005600 const analyze_printf::PrintfConversionSpecifier &CS =
5601 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005602
Richard Trieu03cf7b72011-10-28 00:41:25 +00005603 FixItHint fixit =
5604 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5605 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5606 Amt.getConstantLength()))
5607 : FixItHint();
5608
5609 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5610 << type << CS.toString(),
5611 getLocationOfByte(Amt.getStart()),
5612 /*IsStringLocation*/true,
5613 getSpecifierRange(startSpecifier, specifierLen),
5614 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005615}
5616
Ted Kremenek02087932010-07-16 02:11:22 +00005617void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005618 const analyze_printf::OptionalFlag &flag,
5619 const char *startSpecifier,
5620 unsigned specifierLen) {
5621 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005622 const analyze_printf::PrintfConversionSpecifier &CS =
5623 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005624 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5625 << flag.toString() << CS.toString(),
5626 getLocationOfByte(flag.getPosition()),
5627 /*IsStringLocation*/true,
5628 getSpecifierRange(startSpecifier, specifierLen),
5629 FixItHint::CreateRemoval(
5630 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005631}
5632
5633void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005634 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005635 const analyze_printf::OptionalFlag &ignoredFlag,
5636 const analyze_printf::OptionalFlag &flag,
5637 const char *startSpecifier,
5638 unsigned specifierLen) {
5639 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005640 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5641 << ignoredFlag.toString() << flag.toString(),
5642 getLocationOfByte(ignoredFlag.getPosition()),
5643 /*IsStringLocation*/true,
5644 getSpecifierRange(startSpecifier, specifierLen),
5645 FixItHint::CreateRemoval(
5646 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005647}
5648
Ted Kremenek2b417712015-07-02 05:39:16 +00005649// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5650// bool IsStringLocation, Range StringRange,
5651// ArrayRef<FixItHint> Fixit = None);
5652
5653void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5654 unsigned flagLen) {
5655 // Warn about an empty flag.
5656 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5657 getLocationOfByte(startFlag),
5658 /*IsStringLocation*/true,
5659 getSpecifierRange(startFlag, flagLen));
5660}
5661
5662void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5663 unsigned flagLen) {
5664 // Warn about an invalid flag.
5665 auto Range = getSpecifierRange(startFlag, flagLen);
5666 StringRef flag(startFlag, flagLen);
5667 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5668 getLocationOfByte(startFlag),
5669 /*IsStringLocation*/true,
5670 Range, FixItHint::CreateRemoval(Range));
5671}
5672
5673void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5674 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5675 // Warn about using '[...]' without a '@' conversion.
5676 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5677 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5678 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5679 getLocationOfByte(conversionPosition),
5680 /*IsStringLocation*/true,
5681 Range, FixItHint::CreateRemoval(Range));
5682}
5683
Richard Smith55ce3522012-06-25 20:30:08 +00005684// Determines if the specified is a C++ class or struct containing
5685// a member with the specified name and kind (e.g. a CXXMethodDecl named
5686// "c_str()").
5687template<typename MemberKind>
5688static llvm::SmallPtrSet<MemberKind*, 1>
5689CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5690 const RecordType *RT = Ty->getAs<RecordType>();
5691 llvm::SmallPtrSet<MemberKind*, 1> Results;
5692
5693 if (!RT)
5694 return Results;
5695 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005696 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005697 return Results;
5698
Alp Tokerb6cc5922014-05-03 03:45:55 +00005699 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005700 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005701 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005702
5703 // We just need to include all members of the right kind turned up by the
5704 // filter, at this point.
5705 if (S.LookupQualifiedName(R, RT->getDecl()))
5706 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5707 NamedDecl *decl = (*I)->getUnderlyingDecl();
5708 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5709 Results.insert(FK);
5710 }
5711 return Results;
5712}
5713
Richard Smith2868a732014-02-28 01:36:39 +00005714/// Check if we could call '.c_str()' on an object.
5715///
5716/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5717/// allow the call, or if it would be ambiguous).
5718bool Sema::hasCStrMethod(const Expr *E) {
5719 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5720 MethodSet Results =
5721 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5722 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5723 MI != ME; ++MI)
5724 if ((*MI)->getMinRequiredArguments() == 0)
5725 return true;
5726 return false;
5727}
5728
Richard Smith55ce3522012-06-25 20:30:08 +00005729// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005730// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005731// Returns true when a c_str() conversion method is found.
5732bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005733 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005734 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5735
5736 MethodSet Results =
5737 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5738
5739 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5740 MI != ME; ++MI) {
5741 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005742 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005743 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005744 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005745 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005746 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5747 << "c_str()"
5748 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5749 return true;
5750 }
5751 }
5752
5753 return false;
5754}
5755
Ted Kremenekab278de2010-01-28 23:39:18 +00005756bool
Ted Kremenek02087932010-07-16 02:11:22 +00005757CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005758 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005759 const char *startSpecifier,
5760 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005761 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005762 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005763 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005764
Ted Kremenek6cd69422010-07-19 22:01:06 +00005765 if (FS.consumesDataArgument()) {
5766 if (atFirstArg) {
5767 atFirstArg = false;
5768 usesPositionalArgs = FS.usesPositionalArg();
5769 }
5770 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005771 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5772 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005773 return false;
5774 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005775 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005776
Ted Kremenekd1668192010-02-27 01:41:03 +00005777 // First check if the field width, precision, and conversion specifier
5778 // have matching data arguments.
5779 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5780 startSpecifier, specifierLen)) {
5781 return false;
5782 }
5783
5784 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5785 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005786 return false;
5787 }
5788
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005789 if (!CS.consumesDataArgument()) {
5790 // FIXME: Technically specifying a precision or field width here
5791 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005792 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005793 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005794
Ted Kremenek4a49d982010-02-26 19:18:41 +00005795 // Consume the argument.
5796 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005797 if (argIndex < NumDataArgs) {
5798 // The check to see if the argIndex is valid will come later.
5799 // We set the bit here because we may exit early from this
5800 // function if we encounter some other error.
5801 CoveredArgs.set(argIndex);
5802 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005803
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005804 // FreeBSD kernel extensions.
5805 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5806 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5807 // We need at least two arguments.
5808 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5809 return false;
5810
5811 // Claim the second argument.
5812 CoveredArgs.set(argIndex + 1);
5813
5814 // Type check the first argument (int for %b, pointer for %D)
5815 const Expr *Ex = getDataArg(argIndex);
5816 const analyze_printf::ArgType &AT =
5817 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5818 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5819 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5820 EmitFormatDiagnostic(
5821 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5822 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5823 << false << Ex->getSourceRange(),
5824 Ex->getLocStart(), /*IsStringLocation*/false,
5825 getSpecifierRange(startSpecifier, specifierLen));
5826
5827 // Type check the second argument (char * for both %b and %D)
5828 Ex = getDataArg(argIndex + 1);
5829 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5830 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5831 EmitFormatDiagnostic(
5832 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5833 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5834 << false << Ex->getSourceRange(),
5835 Ex->getLocStart(), /*IsStringLocation*/false,
5836 getSpecifierRange(startSpecifier, specifierLen));
5837
5838 return true;
5839 }
5840
Ted Kremenek4a49d982010-02-26 19:18:41 +00005841 // Check for using an Objective-C specific conversion specifier
5842 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00005843 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00005844 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5845 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00005846 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005847
Mehdi Amini06d367c2016-10-24 20:39:34 +00005848 // %P can only be used with os_log.
5849 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
5850 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5851 specifierLen);
5852 }
5853
5854 // %n is not allowed with os_log.
5855 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
5856 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5857 getLocationOfByte(CS.getStart()),
5858 /*IsStringLocation*/ false,
5859 getSpecifierRange(startSpecifier, specifierLen));
5860
5861 return true;
5862 }
5863
5864 // Only scalars are allowed for os_trace.
5865 if (FSType == Sema::FST_OSTrace &&
5866 (CS.getKind() == ConversionSpecifier::PArg ||
5867 CS.getKind() == ConversionSpecifier::sArg ||
5868 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
5869 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5870 specifierLen);
5871 }
5872
5873 // Check for use of public/private annotation outside of os_log().
5874 if (FSType != Sema::FST_OSLog) {
5875 if (FS.isPublic().isSet()) {
5876 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5877 << "public",
5878 getLocationOfByte(FS.isPublic().getPosition()),
5879 /*IsStringLocation*/ false,
5880 getSpecifierRange(startSpecifier, specifierLen));
5881 }
5882 if (FS.isPrivate().isSet()) {
5883 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5884 << "private",
5885 getLocationOfByte(FS.isPrivate().getPosition()),
5886 /*IsStringLocation*/ false,
5887 getSpecifierRange(startSpecifier, specifierLen));
5888 }
5889 }
5890
Tom Careb49ec692010-06-17 19:00:27 +00005891 // Check for invalid use of field width
5892 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00005893 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00005894 startSpecifier, specifierLen);
5895 }
5896
5897 // Check for invalid use of precision
5898 if (!FS.hasValidPrecision()) {
5899 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5900 startSpecifier, specifierLen);
5901 }
5902
Mehdi Amini06d367c2016-10-24 20:39:34 +00005903 // Precision is mandatory for %P specifier.
5904 if (CS.getKind() == ConversionSpecifier::PArg &&
5905 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5906 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5907 getLocationOfByte(startSpecifier),
5908 /*IsStringLocation*/ false,
5909 getSpecifierRange(startSpecifier, specifierLen));
5910 }
5911
Tom Careb49ec692010-06-17 19:00:27 +00005912 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00005913 if (!FS.hasValidThousandsGroupingPrefix())
5914 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005915 if (!FS.hasValidLeadingZeros())
5916 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5917 if (!FS.hasValidPlusPrefix())
5918 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00005919 if (!FS.hasValidSpacePrefix())
5920 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005921 if (!FS.hasValidAlternativeForm())
5922 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5923 if (!FS.hasValidLeftJustified())
5924 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5925
5926 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00005927 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5928 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5929 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00005930 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5931 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5932 startSpecifier, specifierLen);
5933
5934 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00005935 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00005936 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5937 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00005938 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005939 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00005940 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00005941 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5942 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00005943
Jordan Rose92303592012-09-08 04:00:03 +00005944 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5945 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5946
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005947 // The remaining checks depend on the data arguments.
5948 if (HasVAListArg)
5949 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005950
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005951 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00005952 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005953
Jordan Rose58bbe422012-07-19 18:10:08 +00005954 const Expr *Arg = getDataArg(argIndex);
5955 if (!Arg)
5956 return true;
5957
5958 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00005959}
5960
Jordan Roseaee34382012-09-05 22:56:26 +00005961static bool requiresParensToAddCast(const Expr *E) {
5962 // FIXME: We should have a general way to reason about operator
5963 // precedence and whether parens are actually needed here.
5964 // Take care of a few common cases where they aren't.
5965 const Expr *Inside = E->IgnoreImpCasts();
5966 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5967 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5968
5969 switch (Inside->getStmtClass()) {
5970 case Stmt::ArraySubscriptExprClass:
5971 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005972 case Stmt::CharacterLiteralClass:
5973 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005974 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005975 case Stmt::FloatingLiteralClass:
5976 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005977 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005978 case Stmt::ObjCArrayLiteralClass:
5979 case Stmt::ObjCBoolLiteralExprClass:
5980 case Stmt::ObjCBoxedExprClass:
5981 case Stmt::ObjCDictionaryLiteralClass:
5982 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005983 case Stmt::ObjCIvarRefExprClass:
5984 case Stmt::ObjCMessageExprClass:
5985 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005986 case Stmt::ObjCStringLiteralClass:
5987 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005988 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00005989 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00005990 case Stmt::UnaryOperatorClass:
5991 return false;
5992 default:
5993 return true;
5994 }
5995}
5996
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005997static std::pair<QualType, StringRef>
5998shouldNotPrintDirectly(const ASTContext &Context,
5999 QualType IntendedTy,
6000 const Expr *E) {
6001 // Use a 'while' to peel off layers of typedefs.
6002 QualType TyTy = IntendedTy;
6003 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6004 StringRef Name = UserTy->getDecl()->getName();
6005 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Alexander Shaposhnikov62351372017-06-26 23:02:27 +00006006 .Case("CFIndex", Context.LongTy)
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006007 .Case("NSInteger", Context.LongTy)
6008 .Case("NSUInteger", Context.UnsignedLongTy)
6009 .Case("SInt32", Context.IntTy)
6010 .Case("UInt32", Context.UnsignedIntTy)
6011 .Default(QualType());
6012
6013 if (!CastTy.isNull())
6014 return std::make_pair(CastTy, Name);
6015
6016 TyTy = UserTy->desugar();
6017 }
6018
6019 // Strip parens if necessary.
6020 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6021 return shouldNotPrintDirectly(Context,
6022 PE->getSubExpr()->getType(),
6023 PE->getSubExpr());
6024
6025 // If this is a conditional expression, then its result type is constructed
6026 // via usual arithmetic conversions and thus there might be no necessary
6027 // typedef sugar there. Recurse to operands to check for NSInteger &
6028 // Co. usage condition.
6029 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6030 QualType TrueTy, FalseTy;
6031 StringRef TrueName, FalseName;
6032
6033 std::tie(TrueTy, TrueName) =
6034 shouldNotPrintDirectly(Context,
6035 CO->getTrueExpr()->getType(),
6036 CO->getTrueExpr());
6037 std::tie(FalseTy, FalseName) =
6038 shouldNotPrintDirectly(Context,
6039 CO->getFalseExpr()->getType(),
6040 CO->getFalseExpr());
6041
6042 if (TrueTy == FalseTy)
6043 return std::make_pair(TrueTy, TrueName);
6044 else if (TrueTy.isNull())
6045 return std::make_pair(FalseTy, FalseName);
6046 else if (FalseTy.isNull())
6047 return std::make_pair(TrueTy, TrueName);
6048 }
6049
6050 return std::make_pair(QualType(), StringRef());
6051}
6052
Richard Smith55ce3522012-06-25 20:30:08 +00006053bool
6054CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6055 const char *StartSpecifier,
6056 unsigned SpecifierLen,
6057 const Expr *E) {
6058 using namespace analyze_format_string;
6059 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006060 // Now type check the data expression that matches the
6061 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006062 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006063 if (!AT.isValid())
6064 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006065
Jordan Rose598ec092012-12-05 18:44:40 +00006066 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006067 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6068 ExprTy = TET->getUnderlyingExpr()->getType();
6069 }
6070
Seth Cantrellb4802962015-03-04 03:12:10 +00006071 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6072
6073 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006074 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006075 }
Jordan Rose98709982012-06-04 22:48:57 +00006076
Jordan Rose22b74712012-09-05 22:56:19 +00006077 // Look through argument promotions for our error message's reported type.
6078 // This includes the integral and floating promotions, but excludes array
6079 // and function pointer decay; seeing that an argument intended to be a
6080 // string has type 'char [6]' is probably more confusing than 'char *'.
6081 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6082 if (ICE->getCastKind() == CK_IntegralCast ||
6083 ICE->getCastKind() == CK_FloatingCast) {
6084 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006085 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006086
6087 // Check if we didn't match because of an implicit cast from a 'char'
6088 // or 'short' to an 'int'. This is done because printf is a varargs
6089 // function.
6090 if (ICE->getType() == S.Context.IntTy ||
6091 ICE->getType() == S.Context.UnsignedIntTy) {
6092 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006093 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006094 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006095 }
Jordan Rose98709982012-06-04 22:48:57 +00006096 }
Jordan Rose598ec092012-12-05 18:44:40 +00006097 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6098 // Special case for 'a', which has type 'int' in C.
6099 // Note, however, that we do /not/ want to treat multibyte constants like
6100 // 'MooV' as characters! This form is deprecated but still exists.
6101 if (ExprTy == S.Context.IntTy)
6102 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6103 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006104 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006105
Jordan Rosebc53ed12014-05-31 04:12:14 +00006106 // Look through enums to their underlying type.
6107 bool IsEnum = false;
6108 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6109 ExprTy = EnumTy->getDecl()->getIntegerType();
6110 IsEnum = true;
6111 }
6112
Jordan Rose0e5badd2012-12-05 18:44:49 +00006113 // %C in an Objective-C context prints a unichar, not a wchar_t.
6114 // If the argument is an integer of some kind, believe the %C and suggest
6115 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006116 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006117 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006118 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6119 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6120 !ExprTy->isCharType()) {
6121 // 'unichar' is defined as a typedef of unsigned short, but we should
6122 // prefer using the typedef if it is visible.
6123 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006124
6125 // While we are here, check if the value is an IntegerLiteral that happens
6126 // to be within the valid range.
6127 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6128 const llvm::APInt &V = IL->getValue();
6129 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6130 return true;
6131 }
6132
Jordan Rose0e5badd2012-12-05 18:44:49 +00006133 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6134 Sema::LookupOrdinaryName);
6135 if (S.LookupName(Result, S.getCurScope())) {
6136 NamedDecl *ND = Result.getFoundDecl();
6137 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6138 if (TD->getUnderlyingType() == IntendedTy)
6139 IntendedTy = S.Context.getTypedefType(TD);
6140 }
6141 }
6142 }
6143
6144 // Special-case some of Darwin's platform-independence types by suggesting
6145 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006146 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006147 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006148 QualType CastTy;
6149 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6150 if (!CastTy.isNull()) {
6151 IntendedTy = CastTy;
6152 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006153 }
6154 }
6155
Jordan Rose22b74712012-09-05 22:56:19 +00006156 // We may be able to offer a FixItHint if it is a supported type.
6157 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006158 bool success =
6159 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006160
Jordan Rose22b74712012-09-05 22:56:19 +00006161 if (success) {
6162 // Get the fix string from the fixed format specifier
6163 SmallString<16> buf;
6164 llvm::raw_svector_ostream os(buf);
6165 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006166
Jordan Roseaee34382012-09-05 22:56:26 +00006167 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6168
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006169 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006170 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6171 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6172 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6173 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006174 // In this case, the specifier is wrong and should be changed to match
6175 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006176 EmitFormatDiagnostic(S.PDiag(diag)
6177 << AT.getRepresentativeTypeName(S.Context)
6178 << IntendedTy << IsEnum << E->getSourceRange(),
6179 E->getLocStart(),
6180 /*IsStringLocation*/ false, SpecRange,
6181 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006182 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006183 // The canonical type for formatting this value is different from the
6184 // actual type of the expression. (This occurs, for example, with Darwin's
6185 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6186 // should be printed as 'long' for 64-bit compatibility.)
6187 // Rather than emitting a normal format/argument mismatch, we want to
6188 // add a cast to the recommended type (and correct the format string
6189 // if necessary).
6190 SmallString<16> CastBuf;
6191 llvm::raw_svector_ostream CastFix(CastBuf);
6192 CastFix << "(";
6193 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6194 CastFix << ")";
6195
6196 SmallVector<FixItHint,4> Hints;
6197 if (!AT.matchesType(S.Context, IntendedTy))
6198 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6199
6200 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6201 // If there's already a cast present, just replace it.
6202 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6203 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6204
6205 } else if (!requiresParensToAddCast(E)) {
6206 // If the expression has high enough precedence,
6207 // just write the C-style cast.
6208 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6209 CastFix.str()));
6210 } else {
6211 // Otherwise, add parens around the expression as well as the cast.
6212 CastFix << "(";
6213 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6214 CastFix.str()));
6215
Alp Tokerb6cc5922014-05-03 03:45:55 +00006216 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006217 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6218 }
6219
Jordan Rose0e5badd2012-12-05 18:44:49 +00006220 if (ShouldNotPrintDirectly) {
6221 // The expression has a type that should not be printed directly.
6222 // We extract the name from the typedef because we don't want to show
6223 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006224 StringRef Name;
6225 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6226 Name = TypedefTy->getDecl()->getName();
6227 else
6228 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006229 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006230 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006231 << E->getSourceRange(),
6232 E->getLocStart(), /*IsStringLocation=*/false,
6233 SpecRange, Hints);
6234 } else {
6235 // In this case, the expression could be printed using a different
6236 // specifier, but we've decided that the specifier is probably correct
6237 // and we should cast instead. Just use the normal warning message.
6238 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006239 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6240 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006241 << E->getSourceRange(),
6242 E->getLocStart(), /*IsStringLocation*/false,
6243 SpecRange, Hints);
6244 }
Jordan Roseaee34382012-09-05 22:56:26 +00006245 }
Jordan Rose22b74712012-09-05 22:56:19 +00006246 } else {
6247 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6248 SpecifierLen);
6249 // Since the warning for passing non-POD types to variadic functions
6250 // was deferred until now, we emit a warning for non-POD
6251 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006252 switch (S.isValidVarArgType(ExprTy)) {
6253 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006254 case Sema::VAK_ValidInCXX11: {
6255 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6256 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6257 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6258 }
Richard Smithd7293d72013-08-05 18:49:43 +00006259
Seth Cantrellb4802962015-03-04 03:12:10 +00006260 EmitFormatDiagnostic(
6261 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6262 << IsEnum << CSR << E->getSourceRange(),
6263 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6264 break;
6265 }
Richard Smithd7293d72013-08-05 18:49:43 +00006266 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006267 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006268 EmitFormatDiagnostic(
6269 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006270 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006271 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006272 << CallType
6273 << AT.getRepresentativeTypeName(S.Context)
6274 << CSR
6275 << E->getSourceRange(),
6276 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006277 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006278 break;
6279
6280 case Sema::VAK_Invalid:
6281 if (ExprTy->isObjCObjectType())
6282 EmitFormatDiagnostic(
6283 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6284 << S.getLangOpts().CPlusPlus11
6285 << ExprTy
6286 << CallType
6287 << AT.getRepresentativeTypeName(S.Context)
6288 << CSR
6289 << E->getSourceRange(),
6290 E->getLocStart(), /*IsStringLocation*/false, CSR);
6291 else
6292 // FIXME: If this is an initializer list, suggest removing the braces
6293 // or inserting a cast to the target type.
6294 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6295 << isa<InitListExpr>(E) << ExprTy << CallType
6296 << AT.getRepresentativeTypeName(S.Context)
6297 << E->getSourceRange();
6298 break;
6299 }
6300
6301 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6302 "format string specifier index out of range");
6303 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006304 }
6305
Ted Kremenekab278de2010-01-28 23:39:18 +00006306 return true;
6307}
6308
Ted Kremenek02087932010-07-16 02:11:22 +00006309//===--- CHECK: Scanf format string checking ------------------------------===//
6310
6311namespace {
6312class CheckScanfHandler : public CheckFormatHandler {
6313public:
Stephen Hines648c3692016-09-16 01:07:04 +00006314 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006315 const Expr *origFormatExpr, Sema::FormatStringType type,
6316 unsigned firstDataArg, unsigned numDataArgs,
6317 const char *beg, bool hasVAListArg,
6318 ArrayRef<const Expr *> Args, unsigned formatIdx,
6319 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006320 llvm::SmallBitVector &CheckedVarArgs,
6321 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006322 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6323 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6324 inFunctionCall, CallType, CheckedVarArgs,
6325 UncoveredArg) {}
6326
Ted Kremenek02087932010-07-16 02:11:22 +00006327 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6328 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006329 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006330
6331 bool HandleInvalidScanfConversionSpecifier(
6332 const analyze_scanf::ScanfSpecifier &FS,
6333 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006334 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006335
Craig Toppere14c0f82014-03-12 04:55:44 +00006336 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006337};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006338} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006339
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006340void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6341 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006342 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6343 getLocationOfByte(end), /*IsStringLocation*/true,
6344 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006345}
6346
Ted Kremenekce815422010-07-19 21:25:57 +00006347bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6348 const analyze_scanf::ScanfSpecifier &FS,
6349 const char *startSpecifier,
6350 unsigned specifierLen) {
6351
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006352 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006353 FS.getConversionSpecifier();
6354
6355 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6356 getLocationOfByte(CS.getStart()),
6357 startSpecifier, specifierLen,
6358 CS.getStart(), CS.getLength());
6359}
6360
Ted Kremenek02087932010-07-16 02:11:22 +00006361bool CheckScanfHandler::HandleScanfSpecifier(
6362 const analyze_scanf::ScanfSpecifier &FS,
6363 const char *startSpecifier,
6364 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006365 using namespace analyze_scanf;
6366 using namespace analyze_format_string;
6367
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006368 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006369
Ted Kremenek6cd69422010-07-19 22:01:06 +00006370 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6371 // be used to decide if we are using positional arguments consistently.
6372 if (FS.consumesDataArgument()) {
6373 if (atFirstArg) {
6374 atFirstArg = false;
6375 usesPositionalArgs = FS.usesPositionalArg();
6376 }
6377 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006378 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6379 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006380 return false;
6381 }
Ted Kremenek02087932010-07-16 02:11:22 +00006382 }
6383
6384 // Check if the field with is non-zero.
6385 const OptionalAmount &Amt = FS.getFieldWidth();
6386 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6387 if (Amt.getConstantAmount() == 0) {
6388 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6389 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006390 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6391 getLocationOfByte(Amt.getStart()),
6392 /*IsStringLocation*/true, R,
6393 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006394 }
6395 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006396
Ted Kremenek02087932010-07-16 02:11:22 +00006397 if (!FS.consumesDataArgument()) {
6398 // FIXME: Technically specifying a precision or field width here
6399 // makes no sense. Worth issuing a warning at some point.
6400 return true;
6401 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006402
Ted Kremenek02087932010-07-16 02:11:22 +00006403 // Consume the argument.
6404 unsigned argIndex = FS.getArgIndex();
6405 if (argIndex < NumDataArgs) {
6406 // The check to see if the argIndex is valid will come later.
6407 // We set the bit here because we may exit early from this
6408 // function if we encounter some other error.
6409 CoveredArgs.set(argIndex);
6410 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006411
Ted Kremenek4407ea42010-07-20 20:04:47 +00006412 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006413 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006414 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6415 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006416 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006417 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006418 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006419 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6420 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006421
Jordan Rose92303592012-09-08 04:00:03 +00006422 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6423 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6424
Ted Kremenek02087932010-07-16 02:11:22 +00006425 // The remaining checks depend on the data arguments.
6426 if (HasVAListArg)
6427 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006428
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006429 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006430 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006431
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006432 // Check that the argument type matches the format specifier.
6433 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006434 if (!Ex)
6435 return true;
6436
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006437 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006438
6439 if (!AT.isValid()) {
6440 return true;
6441 }
6442
Seth Cantrellb4802962015-03-04 03:12:10 +00006443 analyze_format_string::ArgType::MatchKind match =
6444 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006445 if (match == analyze_format_string::ArgType::Match) {
6446 return true;
6447 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006448
Seth Cantrell79340072015-03-04 05:58:08 +00006449 ScanfSpecifier fixedFS = FS;
6450 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6451 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006452
Seth Cantrell79340072015-03-04 05:58:08 +00006453 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6454 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6455 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6456 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006457
Seth Cantrell79340072015-03-04 05:58:08 +00006458 if (success) {
6459 // Get the fix string from the fixed format specifier.
6460 SmallString<128> buf;
6461 llvm::raw_svector_ostream os(buf);
6462 fixedFS.toString(os);
6463
6464 EmitFormatDiagnostic(
6465 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6466 << Ex->getType() << false << Ex->getSourceRange(),
6467 Ex->getLocStart(),
6468 /*IsStringLocation*/ false,
6469 getSpecifierRange(startSpecifier, specifierLen),
6470 FixItHint::CreateReplacement(
6471 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6472 } else {
6473 EmitFormatDiagnostic(S.PDiag(diag)
6474 << AT.getRepresentativeTypeName(S.Context)
6475 << Ex->getType() << false << Ex->getSourceRange(),
6476 Ex->getLocStart(),
6477 /*IsStringLocation*/ false,
6478 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006479 }
6480
Ted Kremenek02087932010-07-16 02:11:22 +00006481 return true;
6482}
6483
Stephen Hines648c3692016-09-16 01:07:04 +00006484static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006485 const Expr *OrigFormatExpr,
6486 ArrayRef<const Expr *> Args,
6487 bool HasVAListArg, unsigned format_idx,
6488 unsigned firstDataArg,
6489 Sema::FormatStringType Type,
6490 bool inFunctionCall,
6491 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006492 llvm::SmallBitVector &CheckedVarArgs,
6493 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006494 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006495 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006496 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006497 S, inFunctionCall, Args[format_idx],
6498 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006499 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006500 return;
6501 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006502
Ted Kremenekab278de2010-01-28 23:39:18 +00006503 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006504 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006505 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006506 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006507 const ConstantArrayType *T =
6508 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006509 assert(T && "String literal not of constant array type!");
6510 size_t TypeSize = T->getSize().getZExtValue();
6511 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006512 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006513
6514 // Emit a warning if the string literal is truncated and does not contain an
6515 // embedded null character.
6516 if (TypeSize <= StrRef.size() &&
6517 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6518 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006519 S, inFunctionCall, Args[format_idx],
6520 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006521 FExpr->getLocStart(),
6522 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6523 return;
6524 }
6525
Ted Kremenekab278de2010-01-28 23:39:18 +00006526 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006527 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006528 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006529 S, inFunctionCall, Args[format_idx],
6530 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006531 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006532 return;
6533 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006534
6535 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006536 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6537 Type == Sema::FST_OSTrace) {
6538 CheckPrintfHandler H(
6539 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6540 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6541 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6542 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006543
Hans Wennborg23926bd2011-12-15 10:25:47 +00006544 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006545 S.getLangOpts(),
6546 S.Context.getTargetInfo(),
6547 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006548 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006549 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006550 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6551 numDataArgs, Str, HasVAListArg, Args, format_idx,
6552 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006553
Hans Wennborg23926bd2011-12-15 10:25:47 +00006554 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006555 S.getLangOpts(),
6556 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006557 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006558 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006559}
6560
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006561bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6562 // Str - The format string. NOTE: this is NOT null-terminated!
6563 StringRef StrRef = FExpr->getString();
6564 const char *Str = StrRef.data();
6565 // Account for cases where the string literal is truncated in a declaration.
6566 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6567 assert(T && "String literal not of constant array type!");
6568 size_t TypeSize = T->getSize().getZExtValue();
6569 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6570 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6571 getLangOpts(),
6572 Context.getTargetInfo());
6573}
6574
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006575//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6576
6577// Returns the related absolute value function that is larger, of 0 if one
6578// does not exist.
6579static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6580 switch (AbsFunction) {
6581 default:
6582 return 0;
6583
6584 case Builtin::BI__builtin_abs:
6585 return Builtin::BI__builtin_labs;
6586 case Builtin::BI__builtin_labs:
6587 return Builtin::BI__builtin_llabs;
6588 case Builtin::BI__builtin_llabs:
6589 return 0;
6590
6591 case Builtin::BI__builtin_fabsf:
6592 return Builtin::BI__builtin_fabs;
6593 case Builtin::BI__builtin_fabs:
6594 return Builtin::BI__builtin_fabsl;
6595 case Builtin::BI__builtin_fabsl:
6596 return 0;
6597
6598 case Builtin::BI__builtin_cabsf:
6599 return Builtin::BI__builtin_cabs;
6600 case Builtin::BI__builtin_cabs:
6601 return Builtin::BI__builtin_cabsl;
6602 case Builtin::BI__builtin_cabsl:
6603 return 0;
6604
6605 case Builtin::BIabs:
6606 return Builtin::BIlabs;
6607 case Builtin::BIlabs:
6608 return Builtin::BIllabs;
6609 case Builtin::BIllabs:
6610 return 0;
6611
6612 case Builtin::BIfabsf:
6613 return Builtin::BIfabs;
6614 case Builtin::BIfabs:
6615 return Builtin::BIfabsl;
6616 case Builtin::BIfabsl:
6617 return 0;
6618
6619 case Builtin::BIcabsf:
6620 return Builtin::BIcabs;
6621 case Builtin::BIcabs:
6622 return Builtin::BIcabsl;
6623 case Builtin::BIcabsl:
6624 return 0;
6625 }
6626}
6627
6628// Returns the argument type of the absolute value function.
6629static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6630 unsigned AbsType) {
6631 if (AbsType == 0)
6632 return QualType();
6633
6634 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6635 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6636 if (Error != ASTContext::GE_None)
6637 return QualType();
6638
6639 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6640 if (!FT)
6641 return QualType();
6642
6643 if (FT->getNumParams() != 1)
6644 return QualType();
6645
6646 return FT->getParamType(0);
6647}
6648
6649// Returns the best absolute value function, or zero, based on type and
6650// current absolute value function.
6651static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6652 unsigned AbsFunctionKind) {
6653 unsigned BestKind = 0;
6654 uint64_t ArgSize = Context.getTypeSize(ArgType);
6655 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6656 Kind = getLargerAbsoluteValueFunction(Kind)) {
6657 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6658 if (Context.getTypeSize(ParamType) >= ArgSize) {
6659 if (BestKind == 0)
6660 BestKind = Kind;
6661 else if (Context.hasSameType(ParamType, ArgType)) {
6662 BestKind = Kind;
6663 break;
6664 }
6665 }
6666 }
6667 return BestKind;
6668}
6669
6670enum AbsoluteValueKind {
6671 AVK_Integer,
6672 AVK_Floating,
6673 AVK_Complex
6674};
6675
6676static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6677 if (T->isIntegralOrEnumerationType())
6678 return AVK_Integer;
6679 if (T->isRealFloatingType())
6680 return AVK_Floating;
6681 if (T->isAnyComplexType())
6682 return AVK_Complex;
6683
6684 llvm_unreachable("Type not integer, floating, or complex");
6685}
6686
6687// Changes the absolute value function to a different type. Preserves whether
6688// the function is a builtin.
6689static unsigned changeAbsFunction(unsigned AbsKind,
6690 AbsoluteValueKind ValueKind) {
6691 switch (ValueKind) {
6692 case AVK_Integer:
6693 switch (AbsKind) {
6694 default:
6695 return 0;
6696 case Builtin::BI__builtin_fabsf:
6697 case Builtin::BI__builtin_fabs:
6698 case Builtin::BI__builtin_fabsl:
6699 case Builtin::BI__builtin_cabsf:
6700 case Builtin::BI__builtin_cabs:
6701 case Builtin::BI__builtin_cabsl:
6702 return Builtin::BI__builtin_abs;
6703 case Builtin::BIfabsf:
6704 case Builtin::BIfabs:
6705 case Builtin::BIfabsl:
6706 case Builtin::BIcabsf:
6707 case Builtin::BIcabs:
6708 case Builtin::BIcabsl:
6709 return Builtin::BIabs;
6710 }
6711 case AVK_Floating:
6712 switch (AbsKind) {
6713 default:
6714 return 0;
6715 case Builtin::BI__builtin_abs:
6716 case Builtin::BI__builtin_labs:
6717 case Builtin::BI__builtin_llabs:
6718 case Builtin::BI__builtin_cabsf:
6719 case Builtin::BI__builtin_cabs:
6720 case Builtin::BI__builtin_cabsl:
6721 return Builtin::BI__builtin_fabsf;
6722 case Builtin::BIabs:
6723 case Builtin::BIlabs:
6724 case Builtin::BIllabs:
6725 case Builtin::BIcabsf:
6726 case Builtin::BIcabs:
6727 case Builtin::BIcabsl:
6728 return Builtin::BIfabsf;
6729 }
6730 case AVK_Complex:
6731 switch (AbsKind) {
6732 default:
6733 return 0;
6734 case Builtin::BI__builtin_abs:
6735 case Builtin::BI__builtin_labs:
6736 case Builtin::BI__builtin_llabs:
6737 case Builtin::BI__builtin_fabsf:
6738 case Builtin::BI__builtin_fabs:
6739 case Builtin::BI__builtin_fabsl:
6740 return Builtin::BI__builtin_cabsf;
6741 case Builtin::BIabs:
6742 case Builtin::BIlabs:
6743 case Builtin::BIllabs:
6744 case Builtin::BIfabsf:
6745 case Builtin::BIfabs:
6746 case Builtin::BIfabsl:
6747 return Builtin::BIcabsf;
6748 }
6749 }
6750 llvm_unreachable("Unable to convert function");
6751}
6752
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006753static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006754 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6755 if (!FnInfo)
6756 return 0;
6757
6758 switch (FDecl->getBuiltinID()) {
6759 default:
6760 return 0;
6761 case Builtin::BI__builtin_abs:
6762 case Builtin::BI__builtin_fabs:
6763 case Builtin::BI__builtin_fabsf:
6764 case Builtin::BI__builtin_fabsl:
6765 case Builtin::BI__builtin_labs:
6766 case Builtin::BI__builtin_llabs:
6767 case Builtin::BI__builtin_cabs:
6768 case Builtin::BI__builtin_cabsf:
6769 case Builtin::BI__builtin_cabsl:
6770 case Builtin::BIabs:
6771 case Builtin::BIlabs:
6772 case Builtin::BIllabs:
6773 case Builtin::BIfabs:
6774 case Builtin::BIfabsf:
6775 case Builtin::BIfabsl:
6776 case Builtin::BIcabs:
6777 case Builtin::BIcabsf:
6778 case Builtin::BIcabsl:
6779 return FDecl->getBuiltinID();
6780 }
6781 llvm_unreachable("Unknown Builtin type");
6782}
6783
6784// If the replacement is valid, emit a note with replacement function.
6785// Additionally, suggest including the proper header if not already included.
6786static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006787 unsigned AbsKind, QualType ArgType) {
6788 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006789 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006790 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006791 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6792 FunctionName = "std::abs";
6793 if (ArgType->isIntegralOrEnumerationType()) {
6794 HeaderName = "cstdlib";
6795 } else if (ArgType->isRealFloatingType()) {
6796 HeaderName = "cmath";
6797 } else {
6798 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006799 }
Richard Trieubeffb832014-04-15 23:47:53 +00006800
6801 // Lookup all std::abs
6802 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006803 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006804 R.suppressDiagnostics();
6805 S.LookupQualifiedName(R, Std);
6806
6807 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006808 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006809 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6810 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6811 } else {
6812 FDecl = dyn_cast<FunctionDecl>(I);
6813 }
6814 if (!FDecl)
6815 continue;
6816
6817 // Found std::abs(), check that they are the right ones.
6818 if (FDecl->getNumParams() != 1)
6819 continue;
6820
6821 // Check that the parameter type can handle the argument.
6822 QualType ParamType = FDecl->getParamDecl(0)->getType();
6823 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6824 S.Context.getTypeSize(ArgType) <=
6825 S.Context.getTypeSize(ParamType)) {
6826 // Found a function, don't need the header hint.
6827 EmitHeaderHint = false;
6828 break;
6829 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006830 }
Richard Trieubeffb832014-04-15 23:47:53 +00006831 }
6832 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006833 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006834 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6835
6836 if (HeaderName) {
6837 DeclarationName DN(&S.Context.Idents.get(FunctionName));
6838 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6839 R.suppressDiagnostics();
6840 S.LookupName(R, S.getCurScope());
6841
6842 if (R.isSingleResult()) {
6843 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6844 if (FD && FD->getBuiltinID() == AbsKind) {
6845 EmitHeaderHint = false;
6846 } else {
6847 return;
6848 }
6849 } else if (!R.empty()) {
6850 return;
6851 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006852 }
6853 }
6854
6855 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00006856 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006857
Richard Trieubeffb832014-04-15 23:47:53 +00006858 if (!HeaderName)
6859 return;
6860
6861 if (!EmitHeaderHint)
6862 return;
6863
Alp Toker5d96e0a2014-07-11 20:53:51 +00006864 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6865 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00006866}
6867
Richard Trieua7f30b12016-12-06 01:42:28 +00006868template <std::size_t StrLen>
6869static bool IsStdFunction(const FunctionDecl *FDecl,
6870 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00006871 if (!FDecl)
6872 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006873 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00006874 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00006875 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00006876 return false;
6877
6878 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006879}
6880
6881// Warn when using the wrong abs() function.
6882void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00006883 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006884 if (Call->getNumArgs() != 1)
6885 return;
6886
6887 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00006888 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00006889 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006890 return;
6891
6892 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6893 QualType ParamType = Call->getArg(0)->getType();
6894
Alp Toker5d96e0a2014-07-11 20:53:51 +00006895 // Unsigned types cannot be negative. Suggest removing the absolute value
6896 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006897 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00006898 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00006899 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006900 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6901 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00006902 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006903 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6904 return;
6905 }
6906
David Majnemer7f77eb92015-11-15 03:04:34 +00006907 // Taking the absolute value of a pointer is very suspicious, they probably
6908 // wanted to index into an array, dereference a pointer, call a function, etc.
6909 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6910 unsigned DiagType = 0;
6911 if (ArgType->isFunctionType())
6912 DiagType = 1;
6913 else if (ArgType->isArrayType())
6914 DiagType = 2;
6915
6916 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6917 return;
6918 }
6919
Richard Trieubeffb832014-04-15 23:47:53 +00006920 // std::abs has overloads which prevent most of the absolute value problems
6921 // from occurring.
6922 if (IsStdAbs)
6923 return;
6924
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006925 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6926 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6927
6928 // The argument and parameter are the same kind. Check if they are the right
6929 // size.
6930 if (ArgValueKind == ParamValueKind) {
6931 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6932 return;
6933
6934 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6935 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6936 << FDecl << ArgType << ParamType;
6937
6938 if (NewAbsKind == 0)
6939 return;
6940
6941 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006942 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006943 return;
6944 }
6945
6946 // ArgValueKind != ParamValueKind
6947 // The wrong type of absolute value function was used. Attempt to find the
6948 // proper one.
6949 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6950 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6951 if (NewAbsKind == 0)
6952 return;
6953
6954 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6955 << FDecl << ParamValueKind << ArgValueKind;
6956
6957 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00006958 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006959}
6960
Richard Trieu67c00712016-12-05 23:41:46 +00006961//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00006962void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
6963 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00006964 if (!Call || !FDecl) return;
6965
6966 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00006967 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006968 if (Call->getExprLoc().isMacroID()) return;
6969
6970 // Only care about the one template argument, two function parameter std::max
6971 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00006972 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00006973 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
6974 if (!ArgList) return;
6975 if (ArgList->size() != 1) return;
6976
6977 // Check that template type argument is unsigned integer.
6978 const auto& TA = ArgList->get(0);
6979 if (TA.getKind() != TemplateArgument::Type) return;
6980 QualType ArgType = TA.getAsType();
6981 if (!ArgType->isUnsignedIntegerType()) return;
6982
6983 // See if either argument is a literal zero.
6984 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
6985 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
6986 if (!MTE) return false;
6987 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
6988 if (!Num) return false;
6989 if (Num->getValue() != 0) return false;
6990 return true;
6991 };
6992
6993 const Expr *FirstArg = Call->getArg(0);
6994 const Expr *SecondArg = Call->getArg(1);
6995 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
6996 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
6997
6998 // Only warn when exactly one argument is zero.
6999 if (IsFirstArgZero == IsSecondArgZero) return;
7000
7001 SourceRange FirstRange = FirstArg->getSourceRange();
7002 SourceRange SecondRange = SecondArg->getSourceRange();
7003
7004 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7005
7006 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7007 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7008
7009 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7010 SourceRange RemovalRange;
7011 if (IsFirstArgZero) {
7012 RemovalRange = SourceRange(FirstRange.getBegin(),
7013 SecondRange.getBegin().getLocWithOffset(-1));
7014 } else {
7015 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7016 SecondRange.getEnd());
7017 }
7018
7019 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7020 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7021 << FixItHint::CreateRemoval(RemovalRange);
7022}
7023
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007024//===--- CHECK: Standard memory functions ---------------------------------===//
7025
Nico Weber0e6daef2013-12-26 23:38:39 +00007026/// \brief Takes the expression passed to the size_t parameter of functions
7027/// such as memcmp, strncat, etc and warns if it's a comparison.
7028///
7029/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7030static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7031 IdentifierInfo *FnName,
7032 SourceLocation FnLoc,
7033 SourceLocation RParenLoc) {
7034 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7035 if (!Size)
7036 return false;
7037
7038 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7039 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7040 return false;
7041
Nico Weber0e6daef2013-12-26 23:38:39 +00007042 SourceRange SizeRange = Size->getSourceRange();
7043 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7044 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007045 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007046 << FnName << FixItHint::CreateInsertion(
7047 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007048 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007049 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007050 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007051 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7052 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007053
7054 return true;
7055}
7056
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007057/// \brief Determine whether the given type is or contains a dynamic class type
7058/// (e.g., whether it has a vtable).
7059static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7060 bool &IsContained) {
7061 // Look through array types while ignoring qualifiers.
7062 const Type *Ty = T->getBaseElementTypeUnsafe();
7063 IsContained = false;
7064
7065 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7066 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007067 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007068 return nullptr;
7069
7070 if (RD->isDynamicClass())
7071 return RD;
7072
7073 // Check all the fields. If any bases were dynamic, the class is dynamic.
7074 // It's impossible for a class to transitively contain itself by value, so
7075 // infinite recursion is impossible.
7076 for (auto *FD : RD->fields()) {
7077 bool SubContained;
7078 if (const CXXRecordDecl *ContainedRD =
7079 getContainedDynamicClass(FD->getType(), SubContained)) {
7080 IsContained = true;
7081 return ContainedRD;
7082 }
7083 }
7084
7085 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007086}
7087
Chandler Carruth889ed862011-06-21 23:04:20 +00007088/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007089/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007090static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007091 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007092 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7093 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7094 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007095
Craig Topperc3ec1492014-05-26 06:22:03 +00007096 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007097}
7098
Chandler Carruth889ed862011-06-21 23:04:20 +00007099/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007100static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007101 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7102 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7103 if (SizeOf->getKind() == clang::UETT_SizeOf)
7104 return SizeOf->getTypeOfArgument();
7105
7106 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007107}
7108
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007109/// \brief Check for dangerous or invalid arguments to memset().
7110///
Chandler Carruthac687262011-06-03 06:23:57 +00007111/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007112/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7113/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007114///
7115/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007116void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007117 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007118 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007119 assert(BId != 0);
7120
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007121 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007122 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007123 unsigned ExpectedNumArgs =
7124 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007125 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007126 return;
7127
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007128 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007129 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007130 unsigned LenArg =
7131 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007132 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007133
Nico Weber0e6daef2013-12-26 23:38:39 +00007134 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7135 Call->getLocStart(), Call->getRParenLoc()))
7136 return;
7137
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007138 // We have special checking when the length is a sizeof expression.
7139 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7140 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7141 llvm::FoldingSetNodeID SizeOfArgID;
7142
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007143 // Although widely used, 'bzero' is not a standard function. Be more strict
7144 // with the argument types before allowing diagnostics and only allow the
7145 // form bzero(ptr, sizeof(...)).
7146 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7147 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7148 return;
7149
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007150 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7151 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007152 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007153
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007154 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007155 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007156 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007157 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007158
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007159 // Never warn about void type pointers. This can be used to suppress
7160 // false positives.
7161 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007162 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007163
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007164 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7165 // actually comparing the expressions for equality. Because computing the
7166 // expression IDs can be expensive, we only do this if the diagnostic is
7167 // enabled.
7168 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007169 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7170 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007171 // We only compute IDs for expressions if the warning is enabled, and
7172 // cache the sizeof arg's ID.
7173 if (SizeOfArgID == llvm::FoldingSetNodeID())
7174 SizeOfArg->Profile(SizeOfArgID, Context, true);
7175 llvm::FoldingSetNodeID DestID;
7176 Dest->Profile(DestID, Context, true);
7177 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007178 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7179 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007180 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007181 StringRef ReadableName = FnName->getName();
7182
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007183 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007184 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007185 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007186 if (!PointeeTy->isIncompleteType() &&
7187 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007188 ActionIdx = 2; // If the pointee's size is sizeof(char),
7189 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007190
7191 // If the function is defined as a builtin macro, do not show macro
7192 // expansion.
7193 SourceLocation SL = SizeOfArg->getExprLoc();
7194 SourceRange DSR = Dest->getSourceRange();
7195 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007196 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007197
7198 if (SM.isMacroArgExpansion(SL)) {
7199 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7200 SL = SM.getSpellingLoc(SL);
7201 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7202 SM.getSpellingLoc(DSR.getEnd()));
7203 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7204 SM.getSpellingLoc(SSR.getEnd()));
7205 }
7206
Anna Zaksd08d9152012-05-30 23:14:52 +00007207 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007208 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007209 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007210 << PointeeTy
7211 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007212 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007213 << SSR);
7214 DiagRuntimeBehavior(SL, SizeOfArg,
7215 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7216 << ActionIdx
7217 << SSR);
7218
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007219 break;
7220 }
7221 }
7222
7223 // Also check for cases where the sizeof argument is the exact same
7224 // type as the memory argument, and where it points to a user-defined
7225 // record type.
7226 if (SizeOfArgTy != QualType()) {
7227 if (PointeeTy->isRecordType() &&
7228 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7229 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7230 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7231 << FnName << SizeOfArgTy << ArgIdx
7232 << PointeeTy << Dest->getSourceRange()
7233 << LenExpr->getSourceRange());
7234 break;
7235 }
Nico Weberc5e73862011-06-14 16:14:58 +00007236 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007237 } else if (DestTy->isArrayType()) {
7238 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007239 }
Nico Weberc5e73862011-06-14 16:14:58 +00007240
Nico Weberc44b35e2015-03-21 17:37:46 +00007241 if (PointeeTy == QualType())
7242 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007243
Nico Weberc44b35e2015-03-21 17:37:46 +00007244 // Always complain about dynamic classes.
7245 bool IsContained;
7246 if (const CXXRecordDecl *ContainedRD =
7247 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007248
Nico Weberc44b35e2015-03-21 17:37:46 +00007249 unsigned OperationType = 0;
7250 // "overwritten" if we're warning about the destination for any call
7251 // but memcmp; otherwise a verb appropriate to the call.
7252 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7253 if (BId == Builtin::BImemcpy)
7254 OperationType = 1;
7255 else if(BId == Builtin::BImemmove)
7256 OperationType = 2;
7257 else if (BId == Builtin::BImemcmp)
7258 OperationType = 3;
7259 }
7260
John McCall31168b02011-06-15 23:02:42 +00007261 DiagRuntimeBehavior(
7262 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007263 PDiag(diag::warn_dyn_class_memaccess)
7264 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7265 << FnName << IsContained << ContainedRD << OperationType
7266 << Call->getCallee()->getSourceRange());
7267 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7268 BId != Builtin::BImemset)
7269 DiagRuntimeBehavior(
7270 Dest->getExprLoc(), Dest,
7271 PDiag(diag::warn_arc_object_memaccess)
7272 << ArgIdx << FnName << PointeeTy
7273 << Call->getCallee()->getSourceRange());
7274 else
7275 continue;
7276
7277 DiagRuntimeBehavior(
7278 Dest->getExprLoc(), Dest,
7279 PDiag(diag::note_bad_memaccess_silence)
7280 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7281 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007282 }
7283}
7284
Ted Kremenek6865f772011-08-18 20:55:45 +00007285// A little helper routine: ignore addition and subtraction of integer literals.
7286// This intentionally does not ignore all integer constant expressions because
7287// we don't want to remove sizeof().
7288static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7289 Ex = Ex->IgnoreParenCasts();
7290
7291 for (;;) {
7292 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7293 if (!BO || !BO->isAdditiveOp())
7294 break;
7295
7296 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7297 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7298
7299 if (isa<IntegerLiteral>(RHS))
7300 Ex = LHS;
7301 else if (isa<IntegerLiteral>(LHS))
7302 Ex = RHS;
7303 else
7304 break;
7305 }
7306
7307 return Ex;
7308}
7309
Anna Zaks13b08572012-08-08 21:42:23 +00007310static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7311 ASTContext &Context) {
7312 // Only handle constant-sized or VLAs, but not flexible members.
7313 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7314 // Only issue the FIXIT for arrays of size > 1.
7315 if (CAT->getSize().getSExtValue() <= 1)
7316 return false;
7317 } else if (!Ty->isVariableArrayType()) {
7318 return false;
7319 }
7320 return true;
7321}
7322
Ted Kremenek6865f772011-08-18 20:55:45 +00007323// Warn if the user has made the 'size' argument to strlcpy or strlcat
7324// be the size of the source, instead of the destination.
7325void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7326 IdentifierInfo *FnName) {
7327
7328 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007329 unsigned NumArgs = Call->getNumArgs();
7330 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007331 return;
7332
7333 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7334 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007335 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007336
7337 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7338 Call->getLocStart(), Call->getRParenLoc()))
7339 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007340
7341 // Look for 'strlcpy(dst, x, sizeof(x))'
7342 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7343 CompareWithSrc = Ex;
7344 else {
7345 // Look for 'strlcpy(dst, x, strlen(x))'
7346 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007347 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7348 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007349 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7350 }
7351 }
7352
7353 if (!CompareWithSrc)
7354 return;
7355
7356 // Determine if the argument to sizeof/strlen is equal to the source
7357 // argument. In principle there's all kinds of things you could do
7358 // here, for instance creating an == expression and evaluating it with
7359 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7360 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7361 if (!SrcArgDRE)
7362 return;
7363
7364 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7365 if (!CompareWithSrcDRE ||
7366 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7367 return;
7368
7369 const Expr *OriginalSizeArg = Call->getArg(2);
7370 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7371 << OriginalSizeArg->getSourceRange() << FnName;
7372
7373 // Output a FIXIT hint if the destination is an array (rather than a
7374 // pointer to an array). This could be enhanced to handle some
7375 // pointers if we know the actual size, like if DstArg is 'array+2'
7376 // we could say 'sizeof(array)-2'.
7377 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007378 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007379 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007380
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007381 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007382 llvm::raw_svector_ostream OS(sizeString);
7383 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007384 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007385 OS << ")";
7386
7387 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7388 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7389 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007390}
7391
Anna Zaks314cd092012-02-01 19:08:57 +00007392/// Check if two expressions refer to the same declaration.
7393static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7394 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7395 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7396 return D1->getDecl() == D2->getDecl();
7397 return false;
7398}
7399
7400static const Expr *getStrlenExprArg(const Expr *E) {
7401 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7402 const FunctionDecl *FD = CE->getDirectCallee();
7403 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007404 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007405 return CE->getArg(0)->IgnoreParenCasts();
7406 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007407 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007408}
7409
7410// Warn on anti-patterns as the 'size' argument to strncat.
7411// The correct size argument should look like following:
7412// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7413void Sema::CheckStrncatArguments(const CallExpr *CE,
7414 IdentifierInfo *FnName) {
7415 // Don't crash if the user has the wrong number of arguments.
7416 if (CE->getNumArgs() < 3)
7417 return;
7418 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7419 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7420 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7421
Nico Weber0e6daef2013-12-26 23:38:39 +00007422 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7423 CE->getRParenLoc()))
7424 return;
7425
Anna Zaks314cd092012-02-01 19:08:57 +00007426 // Identify common expressions, which are wrongly used as the size argument
7427 // to strncat and may lead to buffer overflows.
7428 unsigned PatternType = 0;
7429 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7430 // - sizeof(dst)
7431 if (referToTheSameDecl(SizeOfArg, DstArg))
7432 PatternType = 1;
7433 // - sizeof(src)
7434 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7435 PatternType = 2;
7436 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7437 if (BE->getOpcode() == BO_Sub) {
7438 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7439 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7440 // - sizeof(dst) - strlen(dst)
7441 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7442 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7443 PatternType = 1;
7444 // - sizeof(src) - (anything)
7445 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7446 PatternType = 2;
7447 }
7448 }
7449
7450 if (PatternType == 0)
7451 return;
7452
Anna Zaks5069aa32012-02-03 01:27:37 +00007453 // Generate the diagnostic.
7454 SourceLocation SL = LenArg->getLocStart();
7455 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007456 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007457
7458 // If the function is defined as a builtin macro, do not show macro expansion.
7459 if (SM.isMacroArgExpansion(SL)) {
7460 SL = SM.getSpellingLoc(SL);
7461 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7462 SM.getSpellingLoc(SR.getEnd()));
7463 }
7464
Anna Zaks13b08572012-08-08 21:42:23 +00007465 // Check if the destination is an array (rather than a pointer to an array).
7466 QualType DstTy = DstArg->getType();
7467 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7468 Context);
7469 if (!isKnownSizeArray) {
7470 if (PatternType == 1)
7471 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7472 else
7473 Diag(SL, diag::warn_strncat_src_size) << SR;
7474 return;
7475 }
7476
Anna Zaks314cd092012-02-01 19:08:57 +00007477 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007478 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007479 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007480 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007481
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007482 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007483 llvm::raw_svector_ostream OS(sizeString);
7484 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007485 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007486 OS << ") - ";
7487 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007488 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007489 OS << ") - 1";
7490
Anna Zaks5069aa32012-02-03 01:27:37 +00007491 Diag(SL, diag::note_strncat_wrong_size)
7492 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007493}
7494
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007495//===--- CHECK: Return Address of Stack Variable --------------------------===//
7496
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007497static const Expr *EvalVal(const Expr *E,
7498 SmallVectorImpl<const DeclRefExpr *> &refVars,
7499 const Decl *ParentDecl);
7500static const Expr *EvalAddr(const Expr *E,
7501 SmallVectorImpl<const DeclRefExpr *> &refVars,
7502 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007503
7504/// CheckReturnStackAddr - Check if a return statement returns the address
7505/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007506static void
7507CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7508 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007509
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007510 const Expr *stackE = nullptr;
7511 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007512
7513 // Perform checking for returned stack addresses, local blocks,
7514 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007515 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007516 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007517 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007518 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007519 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007520 }
7521
Craig Topperc3ec1492014-05-26 06:22:03 +00007522 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007523 return; // Nothing suspicious was found.
7524
Simon Pilgrim750bde62017-03-31 11:00:53 +00007525 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007526 // of a parameter reference doesn't need a warning.
7527 for (auto *DRE : refVars)
7528 if (isa<ParmVarDecl>(DRE->getDecl()))
7529 return;
7530
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007531 SourceLocation diagLoc;
7532 SourceRange diagRange;
7533 if (refVars.empty()) {
7534 diagLoc = stackE->getLocStart();
7535 diagRange = stackE->getSourceRange();
7536 } else {
7537 // We followed through a reference variable. 'stackE' contains the
7538 // problematic expression but we will warn at the return statement pointing
7539 // at the reference variable. We will later display the "trail" of
7540 // reference variables using notes.
7541 diagLoc = refVars[0]->getLocStart();
7542 diagRange = refVars[0]->getSourceRange();
7543 }
7544
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007545 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7546 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007547 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007548 << DR->getDecl()->getDeclName() << diagRange;
7549 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007550 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007551 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007552 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007553 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007554 // If there is an LValue->RValue conversion, then the value of the
7555 // reference type is used, not the reference.
7556 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7557 if (ICE->getCastKind() == CK_LValueToRValue) {
7558 return;
7559 }
7560 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007561 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7562 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007563 }
7564
7565 // Display the "trail" of reference variables that we followed until we
7566 // found the problematic expression using notes.
7567 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007568 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007569 // If this var binds to another reference var, show the range of the next
7570 // var, otherwise the var binds to the problematic expression, in which case
7571 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007572 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7573 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007574 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7575 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007576 }
7577}
7578
7579/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7580/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007581/// to a location on the stack, a local block, an address of a label, or a
7582/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007583/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007584/// encounter a subexpression that (1) clearly does not lead to one of the
7585/// above problematic expressions (2) is something we cannot determine leads to
7586/// a problematic expression based on such local checking.
7587///
7588/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7589/// the expression that they point to. Such variables are added to the
7590/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007591///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007592/// EvalAddr processes expressions that are pointers that are used as
7593/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007594/// At the base case of the recursion is a check for the above problematic
7595/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007596///
7597/// This implementation handles:
7598///
7599/// * pointer-to-pointer casts
7600/// * implicit conversions from array references to pointers
7601/// * taking the address of fields
7602/// * arbitrary interplay between "&" and "*" operators
7603/// * pointer arithmetic from an address of a stack variable
7604/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007605static const Expr *EvalAddr(const Expr *E,
7606 SmallVectorImpl<const DeclRefExpr *> &refVars,
7607 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007608 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007609 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007610
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007611 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007612 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007613 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007614 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007615 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007616
Peter Collingbourne91147592011-04-15 00:35:48 +00007617 E = E->IgnoreParens();
7618
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007619 // Our "symbolic interpreter" is just a dispatch off the currently
7620 // viewed AST node. We then recursively traverse the AST by calling
7621 // EvalAddr and EvalVal appropriately.
7622 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007623 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007624 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007625
Richard Smith40f08eb2014-01-30 22:05:38 +00007626 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007627 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007628 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007629
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007630 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007631 // If this is a reference variable, follow through to the expression that
7632 // it points to.
7633 if (V->hasLocalStorage() &&
7634 V->getType()->isReferenceType() && V->hasInit()) {
7635 // Add the reference variable to the "trail".
7636 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007637 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007638 }
7639
Craig Topperc3ec1492014-05-26 06:22:03 +00007640 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007641 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007642
Chris Lattner934edb22007-12-28 05:31:15 +00007643 case Stmt::UnaryOperatorClass: {
7644 // The only unary operator that make sense to handle here
7645 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007646 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007647
John McCalle3027922010-08-25 11:45:40 +00007648 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007649 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007650 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007651 }
Mike Stump11289f42009-09-09 15:08:12 +00007652
Chris Lattner934edb22007-12-28 05:31:15 +00007653 case Stmt::BinaryOperatorClass: {
7654 // Handle pointer arithmetic. All other binary operators are not valid
7655 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007656 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007657 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007658
John McCalle3027922010-08-25 11:45:40 +00007659 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007660 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007661
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007662 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007663
7664 // Determine which argument is the real pointer base. It could be
7665 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007666 if (!Base->getType()->isPointerType())
7667 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007668
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007669 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007670 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007671 }
Steve Naroff2752a172008-09-10 19:17:48 +00007672
Chris Lattner934edb22007-12-28 05:31:15 +00007673 // For conditional operators we need to see if either the LHS or RHS are
7674 // valid DeclRefExpr*s. If one of them is valid, we return it.
7675 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007676 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007677
Chris Lattner934edb22007-12-28 05:31:15 +00007678 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007679 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007680 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007681 // In C++, we can have a throw-expression, which has 'void' type.
7682 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007683 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007684 return LHS;
7685 }
Chris Lattner934edb22007-12-28 05:31:15 +00007686
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007687 // In C++, we can have a throw-expression, which has 'void' type.
7688 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007689 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007690
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007691 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007692 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007693
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007694 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007695 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007696 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007697 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007698
7699 case Stmt::AddrLabelExprClass:
7700 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007701
John McCall28fc7092011-11-10 05:35:25 +00007702 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007703 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7704 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007705
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007706 // For casts, we need to handle conversions from arrays to
7707 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007708 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007709 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007710 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007711 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007712 case Stmt::CXXStaticCastExprClass:
7713 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007714 case Stmt::CXXConstCastExprClass:
7715 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007716 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007717 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007718 case CK_LValueToRValue:
7719 case CK_NoOp:
7720 case CK_BaseToDerived:
7721 case CK_DerivedToBase:
7722 case CK_UncheckedDerivedToBase:
7723 case CK_Dynamic:
7724 case CK_CPointerToObjCPointerCast:
7725 case CK_BlockPointerToObjCPointerCast:
7726 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007727 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007728
7729 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007730 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007731
Richard Trieudadefde2014-07-02 04:39:38 +00007732 case CK_BitCast:
7733 if (SubExpr->getType()->isAnyPointerType() ||
7734 SubExpr->getType()->isBlockPointerType() ||
7735 SubExpr->getType()->isObjCQualifiedIdType())
7736 return EvalAddr(SubExpr, refVars, ParentDecl);
7737 else
7738 return nullptr;
7739
Eli Friedman8195ad72012-02-23 23:04:32 +00007740 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007741 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007742 }
Chris Lattner934edb22007-12-28 05:31:15 +00007743 }
Mike Stump11289f42009-09-09 15:08:12 +00007744
Douglas Gregorfe314812011-06-21 17:03:29 +00007745 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007746 if (const Expr *Result =
7747 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7748 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007749 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007750 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007751
Chris Lattner934edb22007-12-28 05:31:15 +00007752 // Everything else: we simply don't reason about them.
7753 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007754 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007755 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007756}
Mike Stump11289f42009-09-09 15:08:12 +00007757
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007758/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7759/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007760static const Expr *EvalVal(const Expr *E,
7761 SmallVectorImpl<const DeclRefExpr *> &refVars,
7762 const Decl *ParentDecl) {
7763 do {
7764 // We should only be called for evaluating non-pointer expressions, or
7765 // expressions with a pointer type that are not used as references but
7766 // instead
7767 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007768
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007769 // Our "symbolic interpreter" is just a dispatch off the currently
7770 // viewed AST node. We then recursively traverse the AST by calling
7771 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007772
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007773 E = E->IgnoreParens();
7774 switch (E->getStmtClass()) {
7775 case Stmt::ImplicitCastExprClass: {
7776 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7777 if (IE->getValueKind() == VK_LValue) {
7778 E = IE->getSubExpr();
7779 continue;
7780 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007781 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007782 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007783
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007784 case Stmt::ExprWithCleanupsClass:
7785 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7786 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007787
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007788 case Stmt::DeclRefExprClass: {
7789 // When we hit a DeclRefExpr we are looking at code that refers to a
7790 // variable's name. If it's not a reference variable we check if it has
7791 // local storage within the function, and if so, return the expression.
7792 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7793
7794 // If we leave the immediate function, the lifetime isn't about to end.
7795 if (DR->refersToEnclosingVariableOrCapture())
7796 return nullptr;
7797
7798 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7799 // Check if it refers to itself, e.g. "int& i = i;".
7800 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007801 return DR;
7802
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007803 if (V->hasLocalStorage()) {
7804 if (!V->getType()->isReferenceType())
7805 return DR;
7806
7807 // Reference variable, follow through to the expression that
7808 // it points to.
7809 if (V->hasInit()) {
7810 // Add the reference variable to the "trail".
7811 refVars.push_back(DR);
7812 return EvalVal(V->getInit(), refVars, V);
7813 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007814 }
7815 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007816
7817 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007818 }
Mike Stump11289f42009-09-09 15:08:12 +00007819
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007820 case Stmt::UnaryOperatorClass: {
7821 // The only unary operator that make sense to handle here
7822 // is Deref. All others don't resolve to a "name." This includes
7823 // handling all sorts of rvalues passed to a unary operator.
7824 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007825
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007826 if (U->getOpcode() == UO_Deref)
7827 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007828
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007829 return nullptr;
7830 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007831
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007832 case Stmt::ArraySubscriptExprClass: {
7833 // Array subscripts are potential references to data on the stack. We
7834 // retrieve the DeclRefExpr* for the array variable if it indeed
7835 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00007836 const auto *ASE = cast<ArraySubscriptExpr>(E);
7837 if (ASE->isTypeDependent())
7838 return nullptr;
7839 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007840 }
Mike Stump11289f42009-09-09 15:08:12 +00007841
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007842 case Stmt::OMPArraySectionExprClass: {
7843 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7844 ParentDecl);
7845 }
Mike Stump11289f42009-09-09 15:08:12 +00007846
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007847 case Stmt::ConditionalOperatorClass: {
7848 // For conditional operators we need to see if either the LHS or RHS are
7849 // non-NULL Expr's. If one is non-NULL, we return it.
7850 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007851
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007852 // Handle the GNU extension for missing LHS.
7853 if (const Expr *LHSExpr = C->getLHS()) {
7854 // In C++, we can have a throw-expression, which has 'void' type.
7855 if (!LHSExpr->getType()->isVoidType())
7856 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7857 return LHS;
7858 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007859
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007860 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007861 if (C->getRHS()->getType()->isVoidType())
7862 return nullptr;
7863
7864 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007865 }
7866
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007867 // Accesses to members are potential references to data on the stack.
7868 case Stmt::MemberExprClass: {
7869 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00007870
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007871 // Check for indirect access. We only want direct field accesses.
7872 if (M->isArrow())
7873 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007874
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007875 // Check whether the member type is itself a reference, in which case
7876 // we're not going to refer to the member, but to what the member refers
7877 // to.
7878 if (M->getMemberDecl()->getType()->isReferenceType())
7879 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007880
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007881 return EvalVal(M->getBase(), refVars, ParentDecl);
7882 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00007883
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007884 case Stmt::MaterializeTemporaryExprClass:
7885 if (const Expr *Result =
7886 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7887 refVars, ParentDecl))
7888 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007889 return E;
7890
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007891 default:
7892 // Check that we don't return or take the address of a reference to a
7893 // temporary. This is only useful in C++.
7894 if (!E->isTypeDependent() && E->isRValue())
7895 return E;
7896
7897 // Everything else: we simply don't reason about them.
7898 return nullptr;
7899 }
7900 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007901}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007902
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007903void
7904Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7905 SourceLocation ReturnLoc,
7906 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00007907 const AttrVec *Attrs,
7908 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007909 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7910
7911 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00007912 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7913 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00007914 CheckNonNullExpr(*this, RetValExp))
7915 Diag(ReturnLoc, diag::warn_null_ret)
7916 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00007917
7918 // C++11 [basic.stc.dynamic.allocation]p4:
7919 // If an allocation function declared with a non-throwing
7920 // exception-specification fails to allocate storage, it shall return
7921 // a null pointer. Any other allocation function that fails to allocate
7922 // storage shall indicate failure only by throwing an exception [...]
7923 if (FD) {
7924 OverloadedOperatorKind Op = FD->getOverloadedOperator();
7925 if (Op == OO_New || Op == OO_Array_New) {
7926 const FunctionProtoType *Proto
7927 = FD->getType()->castAs<FunctionProtoType>();
7928 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7929 CheckNonNullExpr(*this, RetValExp))
7930 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7931 << FD << getLangOpts().CPlusPlus11;
7932 }
7933 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007934}
7935
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007936//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7937
7938/// Check for comparisons of floating point operands using != and ==.
7939/// Issue a warning if these are no self-comparisons, as they are not likely
7940/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00007941void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00007942 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7943 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007944
7945 // Special case: check for x == x (which is OK).
7946 // Do not emit warnings for such cases.
7947 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7948 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7949 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00007950 return;
Mike Stump11289f42009-09-09 15:08:12 +00007951
Ted Kremenekeda40e22007-11-29 00:59:04 +00007952 // Special case: check for comparisons against literals that can be exactly
7953 // represented by APFloat. In such cases, do not emit a warning. This
7954 // is a heuristic: often comparison against such literals are used to
7955 // detect if a value in a variable has not changed. This clearly can
7956 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00007957 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7958 if (FLL->isExact())
7959 return;
7960 } else
7961 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7962 if (FLR->isExact())
7963 return;
Mike Stump11289f42009-09-09 15:08:12 +00007964
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007965 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00007966 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007967 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007968 return;
Mike Stump11289f42009-09-09 15:08:12 +00007969
David Blaikie1f4ff152012-07-16 20:47:22 +00007970 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00007971 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00007972 return;
Mike Stump11289f42009-09-09 15:08:12 +00007973
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007974 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00007975 Diag(Loc, diag::warn_floatingpoint_eq)
7976 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00007977}
John McCallca01b222010-01-04 23:21:16 +00007978
John McCall70aa5392010-01-06 05:24:50 +00007979//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7980//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00007981
John McCall70aa5392010-01-06 05:24:50 +00007982namespace {
John McCallca01b222010-01-04 23:21:16 +00007983
John McCall70aa5392010-01-06 05:24:50 +00007984/// Structure recording the 'active' range of an integer-valued
7985/// expression.
7986struct IntRange {
7987 /// The number of bits active in the int.
7988 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00007989
John McCall70aa5392010-01-06 05:24:50 +00007990 /// True if the int is known not to have negative values.
7991 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00007992
John McCall70aa5392010-01-06 05:24:50 +00007993 IntRange(unsigned Width, bool NonNegative)
7994 : Width(Width), NonNegative(NonNegative)
7995 {}
John McCallca01b222010-01-04 23:21:16 +00007996
John McCall817d4af2010-11-10 23:38:19 +00007997 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00007998 static IntRange forBoolType() {
7999 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008000 }
8001
John McCall817d4af2010-11-10 23:38:19 +00008002 /// Returns the range of an opaque value of the given integral type.
8003 static IntRange forValueOfType(ASTContext &C, QualType T) {
8004 return forValueOfCanonicalType(C,
8005 T->getCanonicalTypeInternal().getTypePtr());
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 a canonical integral type.
8009 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008010 assert(T->isCanonicalUnqualified());
8011
8012 if (const VectorType *VT = dyn_cast<VectorType>(T))
8013 T = VT->getElementType().getTypePtr();
8014 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8015 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008016 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8017 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008018
David Majnemer6a426652013-06-07 22:07:20 +00008019 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008020 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008021 EnumDecl *Enum = ET->getDecl();
8022 if (!Enum->isCompleteDefinition())
8023 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00008024
David Majnemer6a426652013-06-07 22:07:20 +00008025 unsigned NumPositive = Enum->getNumPositiveBits();
8026 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008027
David Majnemer6a426652013-06-07 22:07:20 +00008028 if (NumNegative == 0)
8029 return IntRange(NumPositive, true/*NonNegative*/);
8030 else
8031 return IntRange(std::max(NumPositive + 1, NumNegative),
8032 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008033 }
John McCall70aa5392010-01-06 05:24:50 +00008034
8035 const BuiltinType *BT = cast<BuiltinType>(T);
8036 assert(BT->isInteger());
8037
8038 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8039 }
8040
John McCall817d4af2010-11-10 23:38:19 +00008041 /// Returns the "target" range of a canonical integral type, i.e.
8042 /// the range of values expressible in the type.
8043 ///
8044 /// This matches forValueOfCanonicalType except that enums have the
8045 /// full range of their type, not the range of their enumerators.
8046 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8047 assert(T->isCanonicalUnqualified());
8048
8049 if (const VectorType *VT = dyn_cast<VectorType>(T))
8050 T = VT->getElementType().getTypePtr();
8051 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8052 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008053 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8054 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008055 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008056 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008057
8058 const BuiltinType *BT = cast<BuiltinType>(T);
8059 assert(BT->isInteger());
8060
8061 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8062 }
8063
8064 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008065 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008066 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008067 L.NonNegative && R.NonNegative);
8068 }
8069
John McCall817d4af2010-11-10 23:38:19 +00008070 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008071 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008072 return IntRange(std::min(L.Width, R.Width),
8073 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008074 }
8075};
8076
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008077IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008078 if (value.isSigned() && value.isNegative())
8079 return IntRange(value.getMinSignedBits(), false);
8080
8081 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008082 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008083
8084 // isNonNegative() just checks the sign bit without considering
8085 // signedness.
8086 return IntRange(value.getActiveBits(), true);
8087}
8088
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008089IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8090 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008091 if (result.isInt())
8092 return GetValueRange(C, result.getInt(), MaxWidth);
8093
8094 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008095 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8096 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8097 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8098 R = IntRange::join(R, El);
8099 }
John McCall70aa5392010-01-06 05:24:50 +00008100 return R;
8101 }
8102
8103 if (result.isComplexInt()) {
8104 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8105 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8106 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008107 }
8108
8109 // This can happen with lossless casts to intptr_t of "based" lvalues.
8110 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008111 // FIXME: The only reason we need to pass the type in here is to get
8112 // the sign right on this one case. It would be nice if APValue
8113 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008114 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008115 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008116}
John McCall70aa5392010-01-06 05:24:50 +00008117
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008118QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008119 QualType Ty = E->getType();
8120 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8121 Ty = AtomicRHS->getValueType();
8122 return Ty;
8123}
8124
John McCall70aa5392010-01-06 05:24:50 +00008125/// Pseudo-evaluate the given integer expression, estimating the
8126/// range of values it might take.
8127///
8128/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008129IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008130 E = E->IgnoreParens();
8131
8132 // Try a full evaluation first.
8133 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008134 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008135 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008136
8137 // I think we only want to look through implicit casts here; if the
8138 // user has an explicit widening cast, we should treat the value as
8139 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008140 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008141 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008142 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8143
Eli Friedmane6d33952013-07-08 20:20:06 +00008144 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008145
George Burgess IVdf1ed002016-01-13 01:52:39 +00008146 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8147 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008148
John McCall70aa5392010-01-06 05:24:50 +00008149 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008150 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008151 return OutputTypeRange;
8152
8153 IntRange SubRange
8154 = GetExprRange(C, CE->getSubExpr(),
8155 std::min(MaxWidth, OutputTypeRange.Width));
8156
8157 // Bail out if the subexpr's range is as wide as the cast type.
8158 if (SubRange.Width >= OutputTypeRange.Width)
8159 return OutputTypeRange;
8160
8161 // Otherwise, we take the smaller width, and we're non-negative if
8162 // either the output type or the subexpr is.
8163 return IntRange(SubRange.Width,
8164 SubRange.NonNegative || OutputTypeRange.NonNegative);
8165 }
8166
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008167 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008168 // If we can fold the condition, just take that operand.
8169 bool CondResult;
8170 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8171 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8172 : CO->getFalseExpr(),
8173 MaxWidth);
8174
8175 // Otherwise, conservatively merge.
8176 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8177 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8178 return IntRange::join(L, R);
8179 }
8180
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008181 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008182 switch (BO->getOpcode()) {
8183
8184 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008185 case BO_LAnd:
8186 case BO_LOr:
8187 case BO_LT:
8188 case BO_GT:
8189 case BO_LE:
8190 case BO_GE:
8191 case BO_EQ:
8192 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008193 return IntRange::forBoolType();
8194
John McCallc3688382011-07-13 06:35:24 +00008195 // The type of the assignments is the type of the LHS, so the RHS
8196 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008197 case BO_MulAssign:
8198 case BO_DivAssign:
8199 case BO_RemAssign:
8200 case BO_AddAssign:
8201 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008202 case BO_XorAssign:
8203 case BO_OrAssign:
8204 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008205 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008206
John McCallc3688382011-07-13 06:35:24 +00008207 // Simple assignments just pass through the RHS, which will have
8208 // been coerced to the LHS type.
8209 case BO_Assign:
8210 // TODO: bitfields?
8211 return GetExprRange(C, BO->getRHS(), MaxWidth);
8212
John McCall70aa5392010-01-06 05:24:50 +00008213 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008214 case BO_PtrMemD:
8215 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008216 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008217
John McCall2ce81ad2010-01-06 22:07:33 +00008218 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008219 case BO_And:
8220 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008221 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8222 GetExprRange(C, BO->getRHS(), MaxWidth));
8223
John McCall70aa5392010-01-06 05:24:50 +00008224 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008225 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008226 // ...except that we want to treat '1 << (blah)' as logically
8227 // positive. It's an important idiom.
8228 if (IntegerLiteral *I
8229 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8230 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008231 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008232 return IntRange(R.Width, /*NonNegative*/ true);
8233 }
8234 }
8235 // fallthrough
8236
John McCalle3027922010-08-25 11:45:40 +00008237 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008238 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008239
John McCall2ce81ad2010-01-06 22:07:33 +00008240 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008241 case BO_Shr:
8242 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008243 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8244
8245 // If the shift amount is a positive constant, drop the width by
8246 // that much.
8247 llvm::APSInt shift;
8248 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8249 shift.isNonNegative()) {
8250 unsigned zext = shift.getZExtValue();
8251 if (zext >= L.Width)
8252 L.Width = (L.NonNegative ? 0 : 1);
8253 else
8254 L.Width -= zext;
8255 }
8256
8257 return L;
8258 }
8259
8260 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008261 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008262 return GetExprRange(C, BO->getRHS(), MaxWidth);
8263
John McCall2ce81ad2010-01-06 22:07:33 +00008264 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008265 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008266 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008267 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008268 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008269
John McCall51431812011-07-14 22:39:48 +00008270 // The width of a division result is mostly determined by the size
8271 // of the LHS.
8272 case BO_Div: {
8273 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008274 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008275 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8276
8277 // If the divisor is constant, use that.
8278 llvm::APSInt divisor;
8279 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8280 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8281 if (log2 >= L.Width)
8282 L.Width = (L.NonNegative ? 0 : 1);
8283 else
8284 L.Width = std::min(L.Width - log2, MaxWidth);
8285 return L;
8286 }
8287
8288 // Otherwise, just use the LHS's width.
8289 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8290 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8291 }
8292
8293 // The result of a remainder can't be larger than the result of
8294 // either side.
8295 case BO_Rem: {
8296 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008297 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008298 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8299 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8300
8301 IntRange meet = IntRange::meet(L, R);
8302 meet.Width = std::min(meet.Width, MaxWidth);
8303 return meet;
8304 }
8305
8306 // The default behavior is okay for these.
8307 case BO_Mul:
8308 case BO_Add:
8309 case BO_Xor:
8310 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008311 break;
8312 }
8313
John McCall51431812011-07-14 22:39:48 +00008314 // The default case is to treat the operation as if it were closed
8315 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008316 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8317 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8318 return IntRange::join(L, R);
8319 }
8320
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008321 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008322 switch (UO->getOpcode()) {
8323 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008324 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008325 return IntRange::forBoolType();
8326
8327 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008328 case UO_Deref:
8329 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008330 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008331
8332 default:
8333 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8334 }
8335 }
8336
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008337 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008338 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8339
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008340 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008341 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008342 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008343
Eli Friedmane6d33952013-07-08 20:20:06 +00008344 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008345}
John McCall263a48b2010-01-04 23:31:57 +00008346
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008347IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008348 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008349}
8350
John McCall263a48b2010-01-04 23:31:57 +00008351/// Checks whether the given value, which currently has the given
8352/// source semantics, has the same value when coerced through the
8353/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008354bool IsSameFloatAfterCast(const llvm::APFloat &value,
8355 const llvm::fltSemantics &Src,
8356 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008357 llvm::APFloat truncated = value;
8358
8359 bool ignored;
8360 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8361 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8362
8363 return truncated.bitwiseIsEqual(value);
8364}
8365
8366/// Checks whether the given value, which currently has the given
8367/// source semantics, has the same value when coerced through the
8368/// target semantics.
8369///
8370/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008371bool IsSameFloatAfterCast(const APValue &value,
8372 const llvm::fltSemantics &Src,
8373 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008374 if (value.isFloat())
8375 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8376
8377 if (value.isVector()) {
8378 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8379 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8380 return false;
8381 return true;
8382 }
8383
8384 assert(value.isComplexFloat());
8385 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8386 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8387}
8388
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008389void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008390
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008391bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008392 // Suppress cases where we are comparing against an enum constant.
8393 if (const DeclRefExpr *DR =
8394 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8395 if (isa<EnumConstantDecl>(DR->getDecl()))
8396 return false;
8397
8398 // Suppress cases where the '0' value is expanded from a macro.
8399 if (E->getLocStart().isMacroID())
8400 return false;
8401
John McCallcc7e5bf2010-05-06 08:58:33 +00008402 llvm::APSInt Value;
8403 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8404}
8405
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008406bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008407 // Strip off implicit integral promotions.
8408 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008409 if (ICE->getCastKind() != CK_IntegralCast &&
8410 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008411 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008412 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008413 }
8414
8415 return E->getType()->isEnumeralType();
8416}
8417
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008418void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00008419 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008420 if (S.inTemplateInstantiation())
Richard Trieu36594562013-11-01 21:47:19 +00008421 return;
8422
John McCalle3027922010-08-25 11:45:40 +00008423 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00008424 if (E->isValueDependent())
8425 return;
8426
John McCalle3027922010-08-25 11:45:40 +00008427 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008428 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008429 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008431 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008432 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008433 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008434 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008435 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008436 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008437 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008438 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00008439 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008440 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00008441 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00008442 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8443 }
8444}
8445
Benjamin Kramer7320b992016-06-15 14:20:56 +00008446void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8447 Expr *Other, const llvm::APSInt &Value,
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008448 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00008449 // Disable warning in template instantiations.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008450 if (S.inTemplateInstantiation())
Richard Trieudd51d742013-11-01 21:19:43 +00008451 return;
8452
Richard Trieu0f097742014-04-04 04:13:47 +00008453 // TODO: Investigate using GetExprRange() to get tighter bounds
8454 // on the bit ranges.
8455 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008456 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008457 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008458 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8459 unsigned OtherWidth = OtherRange.Width;
8460
8461 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8462
Richard Trieu560910c2012-11-14 22:50:24 +00008463 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00008464 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00008465 return;
8466
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008467 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008468 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008469
Richard Trieu0f097742014-04-04 04:13:47 +00008470 // Used for diagnostic printout.
8471 enum {
8472 LiteralConstant = 0,
8473 CXXBoolLiteralTrue,
8474 CXXBoolLiteralFalse
8475 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008476
Richard Trieu0f097742014-04-04 04:13:47 +00008477 if (!OtherIsBooleanType) {
8478 QualType ConstantT = Constant->getType();
8479 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008480
Richard Trieu0f097742014-04-04 04:13:47 +00008481 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8482 return;
8483 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8484 "comparison with non-integer type");
8485
8486 bool ConstantSigned = ConstantT->isSignedIntegerType();
8487 bool CommonSigned = CommonT->isSignedIntegerType();
8488
8489 bool EqualityOnly = false;
8490
8491 if (CommonSigned) {
8492 // The common type is signed, therefore no signed to unsigned conversion.
8493 if (!OtherRange.NonNegative) {
8494 // Check that the constant is representable in type OtherT.
8495 if (ConstantSigned) {
8496 if (OtherWidth >= Value.getMinSignedBits())
8497 return;
8498 } else { // !ConstantSigned
8499 if (OtherWidth >= Value.getActiveBits() + 1)
8500 return;
8501 }
8502 } else { // !OtherSigned
8503 // Check that the constant is representable in type OtherT.
8504 // Negative values are out of range.
8505 if (ConstantSigned) {
8506 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8507 return;
8508 } else { // !ConstantSigned
8509 if (OtherWidth >= Value.getActiveBits())
8510 return;
8511 }
Richard Trieu560910c2012-11-14 22:50:24 +00008512 }
Richard Trieu0f097742014-04-04 04:13:47 +00008513 } else { // !CommonSigned
8514 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008515 if (OtherWidth >= Value.getActiveBits())
8516 return;
Craig Toppercf360162014-06-18 05:13:11 +00008517 } else { // OtherSigned
8518 assert(!ConstantSigned &&
8519 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008520 // Check to see if the constant is representable in OtherT.
8521 if (OtherWidth > Value.getActiveBits())
8522 return;
8523 // Check to see if the constant is equivalent to a negative value
8524 // cast to CommonT.
8525 if (S.Context.getIntWidth(ConstantT) ==
8526 S.Context.getIntWidth(CommonT) &&
8527 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8528 return;
8529 // The constant value rests between values that OtherT can represent
8530 // after conversion. Relational comparison still works, but equality
8531 // comparisons will be tautological.
8532 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008533 }
8534 }
Richard Trieu0f097742014-04-04 04:13:47 +00008535
8536 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8537
8538 if (op == BO_EQ || op == BO_NE) {
8539 IsTrue = op == BO_NE;
8540 } else if (EqualityOnly) {
8541 return;
8542 } else if (RhsConstant) {
8543 if (op == BO_GT || op == BO_GE)
8544 IsTrue = !PositiveConstant;
8545 else // op == BO_LT || op == BO_LE
8546 IsTrue = PositiveConstant;
8547 } else {
8548 if (op == BO_LT || op == BO_LE)
8549 IsTrue = !PositiveConstant;
8550 else // op == BO_GT || op == BO_GE
8551 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008552 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008553 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008554 // Other isKnownToHaveBooleanValue
8555 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8556 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8557 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8558
8559 static const struct LinkedConditions {
8560 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8561 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8562 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8563 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8564 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8565 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8566
8567 } TruthTable = {
8568 // Constant on LHS. | Constant on RHS. |
8569 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8570 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8571 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8572 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8573 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8574 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8575 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8576 };
8577
8578 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8579
8580 enum ConstantValue ConstVal = Zero;
8581 if (Value.isUnsigned() || Value.isNonNegative()) {
8582 if (Value == 0) {
8583 LiteralOrBoolConstant =
8584 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8585 ConstVal = Zero;
8586 } else if (Value == 1) {
8587 LiteralOrBoolConstant =
8588 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8589 ConstVal = One;
8590 } else {
8591 LiteralOrBoolConstant = LiteralConstant;
8592 ConstVal = GT_One;
8593 }
8594 } else {
8595 ConstVal = LT_Zero;
8596 }
8597
8598 CompareBoolWithConstantResult CmpRes;
8599
8600 switch (op) {
8601 case BO_LT:
8602 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8603 break;
8604 case BO_GT:
8605 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8606 break;
8607 case BO_LE:
8608 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8609 break;
8610 case BO_GE:
8611 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8612 break;
8613 case BO_EQ:
8614 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8615 break;
8616 case BO_NE:
8617 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8618 break;
8619 default:
8620 CmpRes = Unkwn;
8621 break;
8622 }
8623
8624 if (CmpRes == AFals) {
8625 IsTrue = false;
8626 } else if (CmpRes == ATrue) {
8627 IsTrue = true;
8628 } else {
8629 return;
8630 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008631 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008632
8633 // If this is a comparison to an enum constant, include that
8634 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008635 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008636 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8637 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8638
8639 SmallString<64> PrettySourceValue;
8640 llvm::raw_svector_ostream OS(PrettySourceValue);
8641 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008642 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008643 else
8644 OS << Value;
8645
Richard Trieu0f097742014-04-04 04:13:47 +00008646 S.DiagRuntimeBehavior(
8647 E->getOperatorLoc(), E,
8648 S.PDiag(diag::warn_out_of_range_compare)
8649 << OS.str() << LiteralOrBoolConstant
8650 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8651 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008652}
8653
John McCallcc7e5bf2010-05-06 08:58:33 +00008654/// Analyze the operands of the given comparison. Implements the
8655/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008656void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008657 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8658 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008659}
John McCall263a48b2010-01-04 23:31:57 +00008660
John McCallca01b222010-01-04 23:21:16 +00008661/// \brief Implements -Wsign-compare.
8662///
Richard Trieu82402a02011-09-15 21:56:47 +00008663/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008664void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008665 // The type the comparison is being performed in.
8666 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008667
8668 // Only analyze comparison operators where both sides have been converted to
8669 // the same type.
8670 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8671 return AnalyzeImpConvsInComparison(S, E);
8672
8673 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008674 if (E->isValueDependent())
8675 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008676
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008677 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8678 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008679
8680 bool IsComparisonConstant = false;
8681
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008682 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008683 // of 'true' or 'false'.
8684 if (T->isIntegralType(S.Context)) {
8685 llvm::APSInt RHSValue;
8686 bool IsRHSIntegralLiteral =
8687 RHS->isIntegerConstantExpr(RHSValue, S.Context);
8688 llvm::APSInt LHSValue;
8689 bool IsLHSIntegralLiteral =
8690 LHS->isIntegerConstantExpr(LHSValue, S.Context);
8691 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8692 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8693 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8694 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8695 else
8696 IsComparisonConstant =
8697 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008698 } else if (!T->hasUnsignedIntegerRepresentation())
8699 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008700
John McCallcc7e5bf2010-05-06 08:58:33 +00008701 // We don't do anything special if this isn't an unsigned integral
8702 // comparison: we're only interested in integral comparisons, and
8703 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00008704 //
8705 // We also don't care about value-dependent expressions or expressions
8706 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008707 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00008708 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008709
John McCallcc7e5bf2010-05-06 08:58:33 +00008710 // Check to see if one of the (unmodified) operands is of different
8711 // signedness.
8712 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008713 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8714 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008715 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008716 signedOperand = LHS;
8717 unsignedOperand = RHS;
8718 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8719 signedOperand = RHS;
8720 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008721 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008722 CheckTrivialUnsignedComparison(S, E);
8723 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008724 }
8725
John McCallcc7e5bf2010-05-06 08:58:33 +00008726 // Otherwise, calculate the effective range of the signed operand.
8727 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008728
John McCallcc7e5bf2010-05-06 08:58:33 +00008729 // Go ahead and analyze implicit conversions in the operands. Note
8730 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008731 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8732 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008733
John McCallcc7e5bf2010-05-06 08:58:33 +00008734 // If the signed range is non-negative, -Wsign-compare won't fire,
8735 // but we should still check for comparisons which are always true
8736 // or false.
8737 if (signedRange.NonNegative)
8738 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008739
8740 // For (in)equality comparisons, if the unsigned operand is a
8741 // constant which cannot collide with a overflowed signed operand,
8742 // then reinterpreting the signed operand as unsigned will not
8743 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008744 if (E->isEqualityOp()) {
8745 unsigned comparisonWidth = S.Context.getIntWidth(T);
8746 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008747
John McCallcc7e5bf2010-05-06 08:58:33 +00008748 // We should never be unable to prove that the unsigned operand is
8749 // non-negative.
8750 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8751
8752 if (unsignedRange.Width < comparisonWidth)
8753 return;
8754 }
8755
Douglas Gregorbfb4a212012-05-01 01:53:49 +00008756 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8757 S.PDiag(diag::warn_mixed_sign_comparison)
8758 << LHS->getType() << RHS->getType()
8759 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00008760}
8761
John McCall1f425642010-11-11 03:21:53 +00008762/// Analyzes an attempt to assign the given value to a bitfield.
8763///
8764/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008765bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8766 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00008767 assert(Bitfield->isBitField());
8768 if (Bitfield->isInvalidDecl())
8769 return false;
8770
John McCalldeebbcf2010-11-11 05:33:51 +00008771 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00008772 QualType BitfieldType = Bitfield->getType();
8773 if (BitfieldType->isBooleanType())
8774 return false;
8775
8776 if (BitfieldType->isEnumeralType()) {
8777 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8778 // If the underlying enum type was not explicitly specified as an unsigned
8779 // type and the enum contain only positive values, MSVC++ will cause an
8780 // inconsistency by storing this as a signed type.
8781 if (S.getLangOpts().CPlusPlus11 &&
8782 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8783 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8784 BitfieldEnumDecl->getNumNegativeBits() == 0) {
8785 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8786 << BitfieldEnumDecl->getNameAsString();
8787 }
8788 }
8789
John McCalldeebbcf2010-11-11 05:33:51 +00008790 if (Bitfield->getType()->isBooleanType())
8791 return false;
8792
Douglas Gregor789adec2011-02-04 13:09:01 +00008793 // Ignore value- or type-dependent expressions.
8794 if (Bitfield->getBitWidth()->isValueDependent() ||
8795 Bitfield->getBitWidth()->isTypeDependent() ||
8796 Init->isValueDependent() ||
8797 Init->isTypeDependent())
8798 return false;
8799
John McCall1f425642010-11-11 03:21:53 +00008800 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00008801 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00008802
Richard Smith5fab0c92011-12-28 19:48:30 +00008803 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008804 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8805 Expr::SE_AllowSideEffects)) {
8806 // The RHS is not constant. If the RHS has an enum type, make sure the
8807 // bitfield is wide enough to hold all the values of the enum without
8808 // truncation.
8809 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8810 EnumDecl *ED = EnumTy->getDecl();
8811 bool SignedBitfield = BitfieldType->isSignedIntegerType();
8812
8813 // Enum types are implicitly signed on Windows, so check if there are any
8814 // negative enumerators to see if the enum was intended to be signed or
8815 // not.
8816 bool SignedEnum = ED->getNumNegativeBits() > 0;
8817
8818 // Check for surprising sign changes when assigning enum values to a
8819 // bitfield of different signedness. If the bitfield is signed and we
8820 // have exactly the right number of bits to store this unsigned enum,
8821 // suggest changing the enum to an unsigned type. This typically happens
8822 // on Windows where unfixed enums always use an underlying type of 'int'.
8823 unsigned DiagID = 0;
8824 if (SignedEnum && !SignedBitfield) {
8825 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8826 } else if (SignedBitfield && !SignedEnum &&
8827 ED->getNumPositiveBits() == FieldWidth) {
8828 DiagID = diag::warn_signed_bitfield_enum_conversion;
8829 }
8830
8831 if (DiagID) {
8832 S.Diag(InitLoc, DiagID) << Bitfield << ED;
8833 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
8834 SourceRange TypeRange =
8835 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
8836 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
8837 << SignedEnum << TypeRange;
8838 }
8839
8840 // Compute the required bitwidth. If the enum has negative values, we need
8841 // one more bit than the normal number of positive bits to represent the
8842 // sign bit.
8843 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
8844 ED->getNumNegativeBits())
8845 : ED->getNumPositiveBits();
8846
8847 // Check the bitwidth.
8848 if (BitsNeeded > FieldWidth) {
8849 Expr *WidthExpr = Bitfield->getBitWidth();
8850 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8851 << Bitfield << ED;
8852 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
8853 << BitsNeeded << ED << WidthExpr->getSourceRange();
8854 }
8855 }
8856
John McCall1f425642010-11-11 03:21:53 +00008857 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00008858 }
John McCall1f425642010-11-11 03:21:53 +00008859
John McCall1f425642010-11-11 03:21:53 +00008860 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00008861
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008862 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00008863 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00008864 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8865 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00008866
John McCall1f425642010-11-11 03:21:53 +00008867 if (OriginalWidth <= FieldWidth)
8868 return false;
8869
Eli Friedmanc267a322012-01-26 23:11:39 +00008870 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00008871 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00008872 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00008873
Eli Friedmanc267a322012-01-26 23:11:39 +00008874 // Check whether the stored value is equal to the original value.
8875 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00008876 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00008877 return false;
8878
Eli Friedmanc267a322012-01-26 23:11:39 +00008879 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00008880 // therefore don't strictly fit into a signed bitfield of width 1.
8881 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00008882 return false;
8883
John McCall1f425642010-11-11 03:21:53 +00008884 std::string PrettyValue = Value.toString(10);
8885 std::string PrettyTrunc = TruncatedValue.toString(10);
8886
8887 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8888 << PrettyValue << PrettyTrunc << OriginalInit->getType()
8889 << Init->getSourceRange();
8890
8891 return true;
8892}
8893
John McCalld2a53122010-11-09 23:24:47 +00008894/// Analyze the given simple or compound assignment for warning-worthy
8895/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008896void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00008897 // Just recurse on the LHS.
8898 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8899
8900 // We want to recurse on the RHS as normal unless we're assigning to
8901 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00008902 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00008903 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00008904 E->getOperatorLoc())) {
8905 // Recurse, ignoring any implicit conversions on the RHS.
8906 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8907 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00008908 }
8909 }
8910
8911 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8912}
8913
John McCall263a48b2010-01-04 23:31:57 +00008914/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008915void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8916 SourceLocation CContext, unsigned diag,
8917 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008918 if (pruneControlFlow) {
8919 S.DiagRuntimeBehavior(E->getExprLoc(), E,
8920 S.PDiag(diag)
8921 << SourceType << T << E->getSourceRange()
8922 << SourceRange(CContext));
8923 return;
8924 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00008925 S.Diag(E->getExprLoc(), diag)
8926 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8927}
8928
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008929/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008930void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8931 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00008932 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00008933}
8934
Richard Trieube234c32016-04-21 21:04:55 +00008935
8936/// Diagnose an implicit cast from a floating point value to an integer value.
8937void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8938
8939 SourceLocation CContext) {
8940 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00008941 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00008942
8943 Expr *InnerE = E->IgnoreParenImpCasts();
8944 // We also want to warn on, e.g., "int i = -1.234"
8945 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8946 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8947 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8948
8949 const bool IsLiteral =
8950 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8951
8952 llvm::APFloat Value(0.0);
8953 bool IsConstant =
8954 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8955 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00008956 return DiagnoseImpCast(S, E, T, CContext,
8957 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00008958 }
8959
Chandler Carruth016ef402011-04-10 08:36:24 +00008960 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00008961
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00008962 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8963 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00008964 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8965 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00008966 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00008967 if (IsLiteral) return;
8968 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8969 PruneWarnings);
8970 }
8971
8972 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00008973 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00008974 // Warn on floating point literal to integer.
8975 DiagID = diag::warn_impcast_literal_float_to_integer;
8976 } else if (IntegerValue == 0) {
8977 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
8978 return DiagnoseImpCast(S, E, T, CContext,
8979 diag::warn_impcast_float_integer, PruneWarnings);
8980 }
8981 // Warn on non-zero to zero conversion.
8982 DiagID = diag::warn_impcast_float_to_integer_zero;
8983 } else {
8984 if (IntegerValue.isUnsigned()) {
8985 if (!IntegerValue.isMaxValue()) {
8986 return DiagnoseImpCast(S, E, T, CContext,
8987 diag::warn_impcast_float_integer, PruneWarnings);
8988 }
8989 } else { // IntegerValue.isSigned()
8990 if (!IntegerValue.isMaxSignedValue() &&
8991 !IntegerValue.isMinSignedValue()) {
8992 return DiagnoseImpCast(S, E, T, CContext,
8993 diag::warn_impcast_float_integer, PruneWarnings);
8994 }
8995 }
8996 // Warn on evaluatable floating point expression to integer conversion.
8997 DiagID = diag::warn_impcast_float_to_integer;
8998 }
Chandler Carruth016ef402011-04-10 08:36:24 +00008999
Eli Friedman07185912013-08-29 23:44:43 +00009000 // FIXME: Force the precision of the source value down so we don't print
9001 // digits which are usually useless (we don't really care here if we
9002 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9003 // would automatically print the shortest representation, but it's a bit
9004 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009005 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009006 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9007 precision = (precision * 59 + 195) / 196;
9008 Value.toString(PrettySourceValue, precision);
9009
David Blaikie9b88cc02012-05-15 17:18:27 +00009010 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009011 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009012 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009013 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009014 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009015
Richard Trieube234c32016-04-21 21:04:55 +00009016 if (PruneWarnings) {
9017 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9018 S.PDiag(DiagID)
9019 << E->getType() << T.getUnqualifiedType()
9020 << PrettySourceValue << PrettyTargetValue
9021 << E->getSourceRange() << SourceRange(CContext));
9022 } else {
9023 S.Diag(E->getExprLoc(), DiagID)
9024 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9025 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9026 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009027}
9028
John McCall18a2c2c2010-11-09 22:22:12 +00009029std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9030 if (!Range.Width) return "0";
9031
9032 llvm::APSInt ValueInRange = Value;
9033 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009034 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009035 return ValueInRange.toString(10);
9036}
9037
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009038bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009039 if (!isa<ImplicitCastExpr>(Ex))
9040 return false;
9041
9042 Expr *InnerE = Ex->IgnoreParenImpCasts();
9043 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9044 const Type *Source =
9045 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9046 if (Target->isDependentType())
9047 return false;
9048
9049 const BuiltinType *FloatCandidateBT =
9050 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9051 const Type *BoolCandidateType = ToBool ? Target : Source;
9052
9053 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9054 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9055}
9056
9057void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9058 SourceLocation CC) {
9059 unsigned NumArgs = TheCall->getNumArgs();
9060 for (unsigned i = 0; i < NumArgs; ++i) {
9061 Expr *CurrA = TheCall->getArg(i);
9062 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9063 continue;
9064
9065 bool IsSwapped = ((i > 0) &&
9066 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9067 IsSwapped |= ((i < (NumArgs - 1)) &&
9068 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9069 if (IsSwapped) {
9070 // Warn on this floating-point to bool conversion.
9071 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9072 CurrA->getType(), CC,
9073 diag::warn_impcast_floating_point_to_bool);
9074 }
9075 }
9076}
9077
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009078void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009079 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9080 E->getExprLoc()))
9081 return;
9082
Richard Trieu09d6b802016-01-08 23:35:06 +00009083 // Don't warn on functions which have return type nullptr_t.
9084 if (isa<CallExpr>(E))
9085 return;
9086
Richard Trieu5b993502014-10-15 03:42:06 +00009087 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9088 const Expr::NullPointerConstantKind NullKind =
9089 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9090 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9091 return;
9092
9093 // Return if target type is a safe conversion.
9094 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9095 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9096 return;
9097
9098 SourceLocation Loc = E->getSourceRange().getBegin();
9099
Richard Trieu0a5e1662016-02-13 00:58:53 +00009100 // Venture through the macro stacks to get to the source of macro arguments.
9101 // The new location is a better location than the complete location that was
9102 // passed in.
9103 while (S.SourceMgr.isMacroArgExpansion(Loc))
9104 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9105
9106 while (S.SourceMgr.isMacroArgExpansion(CC))
9107 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9108
Richard Trieu5b993502014-10-15 03:42:06 +00009109 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009110 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9111 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9112 Loc, S.SourceMgr, S.getLangOpts());
9113 if (MacroName == "NULL")
9114 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009115 }
9116
9117 // Only warn if the null and context location are in the same macro expansion.
9118 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9119 return;
9120
9121 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9122 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9123 << FixItHint::CreateReplacement(Loc,
9124 S.getFixItZeroLiteralForType(T, Loc));
9125}
9126
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009127void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9128 ObjCArrayLiteral *ArrayLiteral);
9129void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9130 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009131
9132/// Check a single element within a collection literal against the
9133/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009134void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9135 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009136 // Skip a bitcast to 'id' or qualified 'id'.
9137 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9138 if (ICE->getCastKind() == CK_BitCast &&
9139 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9140 Element = ICE->getSubExpr();
9141 }
9142
9143 QualType ElementType = Element->getType();
9144 ExprResult ElementResult(Element);
9145 if (ElementType->getAs<ObjCObjectPointerType>() &&
9146 S.CheckSingleAssignmentConstraints(TargetElementType,
9147 ElementResult,
9148 false, false)
9149 != Sema::Compatible) {
9150 S.Diag(Element->getLocStart(),
9151 diag::warn_objc_collection_literal_element)
9152 << ElementType << ElementKind << TargetElementType
9153 << Element->getSourceRange();
9154 }
9155
9156 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9157 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9158 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9159 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9160}
9161
9162/// Check an Objective-C array literal being converted to the given
9163/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009164void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9165 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009166 if (!S.NSArrayDecl)
9167 return;
9168
9169 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9170 if (!TargetObjCPtr)
9171 return;
9172
9173 if (TargetObjCPtr->isUnspecialized() ||
9174 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9175 != S.NSArrayDecl->getCanonicalDecl())
9176 return;
9177
9178 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9179 if (TypeArgs.size() != 1)
9180 return;
9181
9182 QualType TargetElementType = TypeArgs[0];
9183 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9184 checkObjCCollectionLiteralElement(S, TargetElementType,
9185 ArrayLiteral->getElement(I),
9186 0);
9187 }
9188}
9189
9190/// Check an Objective-C dictionary literal being converted to the given
9191/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009192void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9193 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009194 if (!S.NSDictionaryDecl)
9195 return;
9196
9197 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9198 if (!TargetObjCPtr)
9199 return;
9200
9201 if (TargetObjCPtr->isUnspecialized() ||
9202 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9203 != S.NSDictionaryDecl->getCanonicalDecl())
9204 return;
9205
9206 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9207 if (TypeArgs.size() != 2)
9208 return;
9209
9210 QualType TargetKeyType = TypeArgs[0];
9211 QualType TargetObjectType = TypeArgs[1];
9212 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9213 auto Element = DictionaryLiteral->getKeyValueElement(I);
9214 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9215 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9216 }
9217}
9218
Richard Trieufc404c72016-02-05 23:02:38 +00009219// Helper function to filter out cases for constant width constant conversion.
9220// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009221bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9222 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009223 // If initializing from a constant, and the constant starts with '0',
9224 // then it is a binary, octal, or hexadecimal. Allow these constants
9225 // to fill all the bits, even if there is a sign change.
9226 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9227 const char FirstLiteralCharacter =
9228 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9229 if (FirstLiteralCharacter == '0')
9230 return false;
9231 }
9232
9233 // If the CC location points to a '{', and the type is char, then assume
9234 // assume it is an array initialization.
9235 if (CC.isValid() && T->isCharType()) {
9236 const char FirstContextCharacter =
9237 S.getSourceManager().getCharacterData(CC)[0];
9238 if (FirstContextCharacter == '{')
9239 return false;
9240 }
9241
9242 return true;
9243}
9244
John McCallcc7e5bf2010-05-06 08:58:33 +00009245void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009246 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009247 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009248
John McCallcc7e5bf2010-05-06 08:58:33 +00009249 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9250 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9251 if (Source == Target) return;
9252 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009253
Chandler Carruthc22845a2011-07-26 05:40:03 +00009254 // If the conversion context location is invalid don't complain. We also
9255 // don't want to emit a warning if the issue occurs from the expansion of
9256 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9257 // delay this check as long as possible. Once we detect we are in that
9258 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009259 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009260 return;
9261
Richard Trieu021baa32011-09-23 20:10:00 +00009262 // Diagnose implicit casts to bool.
9263 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9264 if (isa<StringLiteral>(E))
9265 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009266 // and expressions, for instance, assert(0 && "error here"), are
9267 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009268 return DiagnoseImpCast(S, E, T, CC,
9269 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009270 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9271 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9272 // This covers the literal expressions that evaluate to Objective-C
9273 // objects.
9274 return DiagnoseImpCast(S, E, T, CC,
9275 diag::warn_impcast_objective_c_literal_to_bool);
9276 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009277 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9278 // Warn on pointer to bool conversion that is always true.
9279 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9280 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009281 }
Richard Trieu021baa32011-09-23 20:10:00 +00009282 }
John McCall263a48b2010-01-04 23:31:57 +00009283
Douglas Gregor5054cb02015-07-07 03:58:22 +00009284 // Check implicit casts from Objective-C collection literals to specialized
9285 // collection types, e.g., NSArray<NSString *> *.
9286 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9287 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9288 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9289 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9290
John McCall263a48b2010-01-04 23:31:57 +00009291 // Strip vector types.
9292 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009293 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009294 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009295 return;
John McCallacf0ee52010-10-08 02:01:28 +00009296 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009297 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009298
9299 // If the vector cast is cast between two vectors of the same size, it is
9300 // a bitcast, not a conversion.
9301 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9302 return;
John McCall263a48b2010-01-04 23:31:57 +00009303
9304 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9305 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9306 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009307 if (auto VecTy = dyn_cast<VectorType>(Target))
9308 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009309
9310 // Strip complex types.
9311 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009312 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009313 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009314 return;
9315
John McCallacf0ee52010-10-08 02:01:28 +00009316 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009317 }
John McCall263a48b2010-01-04 23:31:57 +00009318
9319 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9320 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9321 }
9322
9323 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9324 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9325
9326 // If the source is floating point...
9327 if (SourceBT && SourceBT->isFloatingPoint()) {
9328 // ...and the target is floating point...
9329 if (TargetBT && TargetBT->isFloatingPoint()) {
9330 // ...then warn if we're dropping FP rank.
9331
9332 // Builtin FP kinds are ordered by increasing FP rank.
9333 if (SourceBT->getKind() > TargetBT->getKind()) {
9334 // Don't warn about float constants that are precisely
9335 // representable in the target type.
9336 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009337 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009338 // Value might be a float, a float vector, or a float complex.
9339 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009340 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9341 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009342 return;
9343 }
9344
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009345 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009346 return;
9347
John McCallacf0ee52010-10-08 02:01:28 +00009348 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009349 }
9350 // ... or possibly if we're increasing rank, too
9351 else if (TargetBT->getKind() > SourceBT->getKind()) {
9352 if (S.SourceMgr.isInSystemMacro(CC))
9353 return;
9354
9355 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009356 }
9357 return;
9358 }
9359
Richard Trieube234c32016-04-21 21:04:55 +00009360 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009361 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009362 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009363 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009364
Richard Trieube234c32016-04-21 21:04:55 +00009365 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009366 }
John McCall263a48b2010-01-04 23:31:57 +00009367
Richard Smith54894fd2015-12-30 01:06:52 +00009368 // Detect the case where a call result is converted from floating-point to
9369 // to bool, and the final argument to the call is converted from bool, to
9370 // discover this typo:
9371 //
9372 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9373 //
9374 // FIXME: This is an incredibly special case; is there some more general
9375 // way to detect this class of misplaced-parentheses bug?
9376 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009377 // Check last argument of function call to see if it is an
9378 // implicit cast from a type matching the type the result
9379 // is being cast to.
9380 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009381 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009382 Expr *LastA = CEx->getArg(NumArgs - 1);
9383 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009384 if (isa<ImplicitCastExpr>(LastA) &&
9385 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009386 // Warn on this floating-point to bool conversion
9387 DiagnoseImpCast(S, E, T, CC,
9388 diag::warn_impcast_floating_point_to_bool);
9389 }
9390 }
9391 }
John McCall263a48b2010-01-04 23:31:57 +00009392 return;
9393 }
9394
Richard Trieu5b993502014-10-15 03:42:06 +00009395 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009396
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009397 S.DiscardMisalignedMemberAddress(Target, E);
9398
David Blaikie9366d2b2012-06-19 21:19:06 +00009399 if (!Source->isIntegerType() || !Target->isIntegerType())
9400 return;
9401
David Blaikie7555b6a2012-05-15 16:56:36 +00009402 // TODO: remove this early return once the false positives for constant->bool
9403 // in templates, macros, etc, are reduced or removed.
9404 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9405 return;
9406
John McCallcc7e5bf2010-05-06 08:58:33 +00009407 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009408 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009409
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009410 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009411 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009412 // TODO: this should happen for bitfield stores, too.
9413 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009414 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009415 if (S.SourceMgr.isInSystemMacro(CC))
9416 return;
9417
John McCall18a2c2c2010-11-09 22:22:12 +00009418 std::string PrettySourceValue = Value.toString(10);
9419 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009420
Ted Kremenek33ba9952011-10-22 02:37:33 +00009421 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9422 S.PDiag(diag::warn_impcast_integer_precision_constant)
9423 << PrettySourceValue << PrettyTargetValue
9424 << E->getType() << T << E->getSourceRange()
9425 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009426 return;
9427 }
9428
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009429 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9430 if (S.SourceMgr.isInSystemMacro(CC))
9431 return;
9432
David Blaikie9455da02012-04-12 22:40:54 +00009433 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009434 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9435 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009436 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009437 }
9438
Richard Trieudcb55572016-01-29 23:51:16 +00009439 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9440 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9441 // Warn when doing a signed to signed conversion, warn if the positive
9442 // source value is exactly the width of the target type, which will
9443 // cause a negative value to be stored.
9444
9445 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009446 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9447 !S.SourceMgr.isInSystemMacro(CC)) {
9448 if (isSameWidthConstantConversion(S, E, T, CC)) {
9449 std::string PrettySourceValue = Value.toString(10);
9450 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009451
Richard Trieufc404c72016-02-05 23:02:38 +00009452 S.DiagRuntimeBehavior(
9453 E->getExprLoc(), E,
9454 S.PDiag(diag::warn_impcast_integer_precision_constant)
9455 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9456 << E->getSourceRange() << clang::SourceRange(CC));
9457 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009458 }
9459 }
Richard Trieufc404c72016-02-05 23:02:38 +00009460
Richard Trieudcb55572016-01-29 23:51:16 +00009461 // Fall through for non-constants to give a sign conversion warning.
9462 }
9463
John McCallcc7e5bf2010-05-06 08:58:33 +00009464 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9465 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9466 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009467 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009468 return;
9469
John McCallcc7e5bf2010-05-06 08:58:33 +00009470 unsigned DiagID = diag::warn_impcast_integer_sign;
9471
9472 // Traditionally, gcc has warned about this under -Wsign-compare.
9473 // We also want to warn about it in -Wconversion.
9474 // So if -Wconversion is off, use a completely identical diagnostic
9475 // in the sign-compare group.
9476 // The conditional-checking code will
9477 if (ICContext) {
9478 DiagID = diag::warn_impcast_integer_sign_conditional;
9479 *ICContext = true;
9480 }
9481
John McCallacf0ee52010-10-08 02:01:28 +00009482 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009483 }
9484
Douglas Gregora78f1932011-02-22 02:45:07 +00009485 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009486 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9487 // type, to give us better diagnostics.
9488 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009489 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009490 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9491 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9492 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9493 SourceType = S.Context.getTypeDeclType(Enum);
9494 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9495 }
9496 }
9497
Douglas Gregora78f1932011-02-22 02:45:07 +00009498 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9499 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009500 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9501 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009502 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009503 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009504 return;
9505
Douglas Gregor364f7db2011-03-12 00:14:31 +00009506 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009507 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009508 }
John McCall263a48b2010-01-04 23:31:57 +00009509}
9510
David Blaikie18e9ac72012-05-15 21:57:38 +00009511void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9512 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009513
9514void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009515 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009516 E = E->IgnoreParenImpCasts();
9517
9518 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009519 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009520
John McCallacf0ee52010-10-08 02:01:28 +00009521 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009522 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009523 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009524}
9525
David Blaikie18e9ac72012-05-15 21:57:38 +00009526void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9527 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009528 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009529
9530 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009531 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9532 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009533
9534 // If -Wconversion would have warned about either of the candidates
9535 // for a signedness conversion to the context type...
9536 if (!Suspicious) return;
9537
9538 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009539 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009540 return;
9541
John McCallcc7e5bf2010-05-06 08:58:33 +00009542 // ...then check whether it would have warned about either of the
9543 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009544 if (E->getType() == T) return;
9545
9546 Suspicious = false;
9547 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9548 E->getType(), CC, &Suspicious);
9549 if (!Suspicious)
9550 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009551 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009552}
9553
Richard Trieu65724892014-11-15 06:37:39 +00009554/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9555/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009556void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009557 if (S.getLangOpts().Bool)
9558 return;
9559 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9560}
9561
John McCallcc7e5bf2010-05-06 08:58:33 +00009562/// AnalyzeImplicitConversions - Find and report any interesting
9563/// implicit conversions in the given expression. There are a couple
9564/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009565void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009566 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009567 Expr *E = OrigE->IgnoreParenImpCasts();
9568
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009569 if (E->isTypeDependent() || E->isValueDependent())
9570 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009571
John McCallcc7e5bf2010-05-06 08:58:33 +00009572 // For conditional operators, we analyze the arguments as if they
9573 // were being fed directly into the output.
9574 if (isa<ConditionalOperator>(E)) {
9575 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009576 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009577 return;
9578 }
9579
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009580 // Check implicit argument conversions for function calls.
9581 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9582 CheckImplicitArgumentConversions(S, Call, CC);
9583
John McCallcc7e5bf2010-05-06 08:58:33 +00009584 // Go ahead and check any implicit conversions we might have skipped.
9585 // The non-canonical typecheck is just an optimization;
9586 // CheckImplicitConversion will filter out dead implicit conversions.
9587 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009588 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009589
9590 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009591
9592 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9593 // The bound subexpressions in a PseudoObjectExpr are not reachable
9594 // as transitive children.
9595 // FIXME: Use a more uniform representation for this.
9596 for (auto *SE : POE->semantics())
9597 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9598 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009599 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009600
John McCallcc7e5bf2010-05-06 08:58:33 +00009601 // Skip past explicit casts.
9602 if (isa<ExplicitCastExpr>(E)) {
9603 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009604 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009605 }
9606
John McCalld2a53122010-11-09 23:24:47 +00009607 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9608 // Do a somewhat different check with comparison operators.
9609 if (BO->isComparisonOp())
9610 return AnalyzeComparison(S, BO);
9611
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009612 // And with simple assignments.
9613 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009614 return AnalyzeAssignment(S, BO);
9615 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009616
9617 // These break the otherwise-useful invariant below. Fortunately,
9618 // we don't really need to recurse into them, because any internal
9619 // expressions should have been analyzed already when they were
9620 // built into statements.
9621 if (isa<StmtExpr>(E)) return;
9622
9623 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009624 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009625
9626 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009627 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009628 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009629 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009630 for (Stmt *SubStmt : E->children()) {
9631 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009632 if (!ChildExpr)
9633 continue;
9634
Richard Trieu955231d2014-01-25 01:10:35 +00009635 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009636 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009637 // Ignore checking string literals that are in logical and operators.
9638 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009639 continue;
9640 AnalyzeImplicitConversions(S, ChildExpr, CC);
9641 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009642
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009643 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009644 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9645 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009646 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009647
9648 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9649 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009650 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009651 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009652
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009653 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9654 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009655 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009656}
9657
9658} // end anonymous namespace
9659
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009660/// Diagnose integer type and any valid implicit convertion to it.
9661static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9662 // Taking into account implicit conversions,
9663 // allow any integer.
9664 if (!E->getType()->isIntegerType()) {
9665 S.Diag(E->getLocStart(),
9666 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9667 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009668 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009669 // Potentially emit standard warnings for implicit conversions if enabled
9670 // using -Wconversion.
9671 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9672 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009673}
9674
Richard Trieuc1888e02014-06-28 23:25:37 +00009675// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9676// Returns true when emitting a warning about taking the address of a reference.
9677static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009678 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009679 E = E->IgnoreParenImpCasts();
9680
9681 const FunctionDecl *FD = nullptr;
9682
9683 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9684 if (!DRE->getDecl()->getType()->isReferenceType())
9685 return false;
9686 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9687 if (!M->getMemberDecl()->getType()->isReferenceType())
9688 return false;
9689 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009690 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009691 return false;
9692 FD = Call->getDirectCallee();
9693 } else {
9694 return false;
9695 }
9696
9697 SemaRef.Diag(E->getExprLoc(), PD);
9698
9699 // If possible, point to location of function.
9700 if (FD) {
9701 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9702 }
9703
9704 return true;
9705}
9706
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009707// Returns true if the SourceLocation is expanded from any macro body.
9708// Returns false if the SourceLocation is invalid, is from not in a macro
9709// expansion, or is from expanded from a top-level macro argument.
9710static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9711 if (Loc.isInvalid())
9712 return false;
9713
9714 while (Loc.isMacroID()) {
9715 if (SM.isMacroBodyExpansion(Loc))
9716 return true;
9717 Loc = SM.getImmediateMacroCallerLoc(Loc);
9718 }
9719
9720 return false;
9721}
9722
Richard Trieu3bb8b562014-02-26 02:36:06 +00009723/// \brief Diagnose pointers that are always non-null.
9724/// \param E the expression containing the pointer
9725/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9726/// compared to a null pointer
9727/// \param IsEqual True when the comparison is equal to a null pointer
9728/// \param Range Extra SourceRange to highlight in the diagnostic
9729void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9730 Expr::NullPointerConstantKind NullKind,
9731 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009732 if (!E)
9733 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009734
9735 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009736 if (E->getExprLoc().isMacroID()) {
9737 const SourceManager &SM = getSourceManager();
9738 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9739 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009740 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009741 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009742 E = E->IgnoreImpCasts();
9743
9744 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9745
Richard Trieuf7432752014-06-06 21:39:26 +00009746 if (isa<CXXThisExpr>(E)) {
9747 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9748 : diag::warn_this_bool_conversion;
9749 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9750 return;
9751 }
9752
Richard Trieu3bb8b562014-02-26 02:36:06 +00009753 bool IsAddressOf = false;
9754
9755 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9756 if (UO->getOpcode() != UO_AddrOf)
9757 return;
9758 IsAddressOf = true;
9759 E = UO->getSubExpr();
9760 }
9761
Richard Trieuc1888e02014-06-28 23:25:37 +00009762 if (IsAddressOf) {
9763 unsigned DiagID = IsCompare
9764 ? diag::warn_address_of_reference_null_compare
9765 : diag::warn_address_of_reference_bool_conversion;
9766 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9767 << IsEqual;
9768 if (CheckForReference(*this, E, PD)) {
9769 return;
9770 }
9771 }
9772
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009773 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9774 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +00009775 std::string Str;
9776 llvm::raw_string_ostream S(Str);
9777 E->printPretty(S, nullptr, getPrintingPolicy());
9778 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9779 : diag::warn_cast_nonnull_to_bool;
9780 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9781 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009782 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +00009783 };
9784
9785 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9786 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9787 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009788 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9789 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009790 return;
9791 }
9792 }
9793 }
9794
Richard Trieu3bb8b562014-02-26 02:36:06 +00009795 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00009796 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009797 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9798 D = R->getDecl();
9799 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9800 D = M->getMemberDecl();
9801 }
9802
9803 // Weak Decls can be null.
9804 if (!D || D->isWeak())
9805 return;
George Burgess IV850269a2015-12-08 22:02:00 +00009806
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009807 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00009808 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9809 if (getCurFunction() &&
9810 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009811 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9812 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +00009813 return;
9814 }
9815
9816 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +00009817 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +00009818 assert(ParamIter != FD->param_end());
9819 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9820
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009821 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9822 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009823 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +00009824 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009825 }
George Burgess IV850269a2015-12-08 22:02:00 +00009826
9827 for (unsigned ArgNo : NonNull->args()) {
9828 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +00009829 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009830 return;
9831 }
George Burgess IV850269a2015-12-08 22:02:00 +00009832 }
9833 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00009834 }
9835 }
George Burgess IV850269a2015-12-08 22:02:00 +00009836 }
9837
Richard Trieu3bb8b562014-02-26 02:36:06 +00009838 QualType T = D->getType();
9839 const bool IsArray = T->isArrayType();
9840 const bool IsFunction = T->isFunctionType();
9841
Richard Trieuc1888e02014-06-28 23:25:37 +00009842 // Address of function is used to silence the function warning.
9843 if (IsAddressOf && IsFunction) {
9844 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009845 }
9846
9847 // Found nothing.
9848 if (!IsAddressOf && !IsFunction && !IsArray)
9849 return;
9850
9851 // Pretty print the expression for the diagnostic.
9852 std::string Str;
9853 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00009854 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00009855
9856 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9857 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00009858 enum {
9859 AddressOf,
9860 FunctionPointer,
9861 ArrayPointer
9862 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009863 if (IsAddressOf)
9864 DiagType = AddressOf;
9865 else if (IsFunction)
9866 DiagType = FunctionPointer;
9867 else if (IsArray)
9868 DiagType = ArrayPointer;
9869 else
9870 llvm_unreachable("Could not determine diagnostic.");
9871 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9872 << Range << IsEqual;
9873
9874 if (!IsFunction)
9875 return;
9876
9877 // Suggest '&' to silence the function warning.
9878 Diag(E->getExprLoc(), diag::note_function_warning_silence)
9879 << FixItHint::CreateInsertion(E->getLocStart(), "&");
9880
9881 // Check to see if '()' fixit should be emitted.
9882 QualType ReturnType;
9883 UnresolvedSet<4> NonTemplateOverloads;
9884 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9885 if (ReturnType.isNull())
9886 return;
9887
9888 if (IsCompare) {
9889 // There are two cases here. If there is null constant, the only suggest
9890 // for a pointer return type. If the null is 0, then suggest if the return
9891 // type is a pointer or an integer type.
9892 if (!ReturnType->isPointerType()) {
9893 if (NullKind == Expr::NPCK_ZeroExpression ||
9894 NullKind == Expr::NPCK_ZeroLiteral) {
9895 if (!ReturnType->isIntegerType())
9896 return;
9897 } else {
9898 return;
9899 }
9900 }
9901 } else { // !IsCompare
9902 // For function to bool, only suggest if the function pointer has bool
9903 // return type.
9904 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9905 return;
9906 }
9907 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00009908 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00009909}
9910
John McCallcc7e5bf2010-05-06 08:58:33 +00009911/// Diagnoses "dangerous" implicit conversions within the given
9912/// expression (which is a full expression). Implements -Wconversion
9913/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009914///
9915/// \param CC the "context" location of the implicit conversion, i.e.
9916/// the most location of the syntactic entity requiring the implicit
9917/// conversion
9918void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009919 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00009920 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00009921 return;
9922
9923 // Don't diagnose for value- or type-dependent expressions.
9924 if (E->isTypeDependent() || E->isValueDependent())
9925 return;
9926
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009927 // Check for array bounds violations in cases where the check isn't triggered
9928 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9929 // ArraySubscriptExpr is on the RHS of a variable initialization.
9930 CheckArrayAccess(E);
9931
John McCallacf0ee52010-10-08 02:01:28 +00009932 // This is not the right CC for (e.g.) a variable initialization.
9933 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009934}
9935
Richard Trieu65724892014-11-15 06:37:39 +00009936/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9937/// Input argument E is a logical expression.
9938void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9939 ::CheckBoolLikeConversion(*this, E, CC);
9940}
9941
Richard Smith9f7df0c2017-06-26 23:19:32 +00009942/// Diagnose when expression is an integer constant expression and its evaluation
9943/// results in integer overflow
9944void Sema::CheckForIntOverflow (Expr *E) {
9945 // Use a work list to deal with nested struct initializers.
9946 SmallVector<Expr *, 2> Exprs(1, E);
9947
9948 do {
9949 Expr *E = Exprs.pop_back_val();
9950
9951 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9952 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9953 continue;
9954 }
9955
9956 if (auto InitList = dyn_cast<InitListExpr>(E))
9957 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9958
9959 if (isa<ObjCBoxedExpr>(E))
9960 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9961 } while (!Exprs.empty());
9962}
9963
Richard Smithc406cb72013-01-17 01:17:56 +00009964namespace {
9965/// \brief Visitor for expressions which looks for unsequenced operations on the
9966/// same object.
9967class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00009968 typedef EvaluatedExprVisitor<SequenceChecker> Base;
9969
Richard Smithc406cb72013-01-17 01:17:56 +00009970 /// \brief A tree of sequenced regions within an expression. Two regions are
9971 /// unsequenced if one is an ancestor or a descendent of the other. When we
9972 /// finish processing an expression with sequencing, such as a comma
9973 /// expression, we fold its tree nodes into its parent, since they are
9974 /// unsequenced with respect to nodes we will visit later.
9975 class SequenceTree {
9976 struct Value {
9977 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9978 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +00009979 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +00009980 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00009981 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00009982
9983 public:
9984 /// \brief A region within an expression which may be sequenced with respect
9985 /// to some other region.
9986 class Seq {
9987 explicit Seq(unsigned N) : Index(N) {}
9988 unsigned Index;
9989 friend class SequenceTree;
9990 public:
9991 Seq() : Index(0) {}
9992 };
9993
9994 SequenceTree() { Values.push_back(Value(0)); }
9995 Seq root() const { return Seq(0); }
9996
9997 /// \brief Create a new sequence of operations, which is an unsequenced
9998 /// subset of \p Parent. This sequence of operations is sequenced with
9999 /// respect to other children of \p Parent.
10000 Seq allocate(Seq Parent) {
10001 Values.push_back(Value(Parent.Index));
10002 return Seq(Values.size() - 1);
10003 }
10004
10005 /// \brief Merge a sequence of operations into its parent.
10006 void merge(Seq S) {
10007 Values[S.Index].Merged = true;
10008 }
10009
10010 /// \brief Determine whether two operations are unsequenced. This operation
10011 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10012 /// should have been merged into its parent as appropriate.
10013 bool isUnsequenced(Seq Cur, Seq Old) {
10014 unsigned C = representative(Cur.Index);
10015 unsigned Target = representative(Old.Index);
10016 while (C >= Target) {
10017 if (C == Target)
10018 return true;
10019 C = Values[C].Parent;
10020 }
10021 return false;
10022 }
10023
10024 private:
10025 /// \brief Pick a representative for a sequence.
10026 unsigned representative(unsigned K) {
10027 if (Values[K].Merged)
10028 // Perform path compression as we go.
10029 return Values[K].Parent = representative(Values[K].Parent);
10030 return K;
10031 }
10032 };
10033
10034 /// An object for which we can track unsequenced uses.
10035 typedef NamedDecl *Object;
10036
10037 /// Different flavors of object usage which we track. We only track the
10038 /// least-sequenced usage of each kind.
10039 enum UsageKind {
10040 /// A read of an object. Multiple unsequenced reads are OK.
10041 UK_Use,
10042 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010043 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010044 UK_ModAsValue,
10045 /// A modification of an object which is not sequenced before the value
10046 /// computation of the expression, such as n++.
10047 UK_ModAsSideEffect,
10048
10049 UK_Count = UK_ModAsSideEffect + 1
10050 };
10051
10052 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010053 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010054 Expr *Use;
10055 SequenceTree::Seq Seq;
10056 };
10057
10058 struct UsageInfo {
10059 UsageInfo() : Diagnosed(false) {}
10060 Usage Uses[UK_Count];
10061 /// Have we issued a diagnostic for this variable already?
10062 bool Diagnosed;
10063 };
10064 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10065
10066 Sema &SemaRef;
10067 /// Sequenced regions within the expression.
10068 SequenceTree Tree;
10069 /// Declaration modifications and references which we have seen.
10070 UsageInfoMap UsageMap;
10071 /// The region we are currently within.
10072 SequenceTree::Seq Region;
10073 /// Filled in with declarations which were modified as a side-effect
10074 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010075 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010076 /// Expressions to check later. We defer checking these to reduce
10077 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010078 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010079
10080 /// RAII object wrapping the visitation of a sequenced subexpression of an
10081 /// expression. At the end of this process, the side-effects of the evaluation
10082 /// become sequenced with respect to the value computation of the result, so
10083 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10084 /// UK_ModAsValue.
10085 struct SequencedSubexpression {
10086 SequencedSubexpression(SequenceChecker &Self)
10087 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10088 Self.ModAsSideEffect = &ModAsSideEffect;
10089 }
10090 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010091 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10092 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010093 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010094 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10095 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010096 }
10097 Self.ModAsSideEffect = OldModAsSideEffect;
10098 }
10099
10100 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010101 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10102 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010103 };
10104
Richard Smith40238f02013-06-20 22:21:56 +000010105 /// RAII object wrapping the visitation of a subexpression which we might
10106 /// choose to evaluate as a constant. If any subexpression is evaluated and
10107 /// found to be non-constant, this allows us to suppress the evaluation of
10108 /// the outer expression.
10109 class EvaluationTracker {
10110 public:
10111 EvaluationTracker(SequenceChecker &Self)
10112 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10113 Self.EvalTracker = this;
10114 }
10115 ~EvaluationTracker() {
10116 Self.EvalTracker = Prev;
10117 if (Prev)
10118 Prev->EvalOK &= EvalOK;
10119 }
10120
10121 bool evaluate(const Expr *E, bool &Result) {
10122 if (!EvalOK || E->isValueDependent())
10123 return false;
10124 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10125 return EvalOK;
10126 }
10127
10128 private:
10129 SequenceChecker &Self;
10130 EvaluationTracker *Prev;
10131 bool EvalOK;
10132 } *EvalTracker;
10133
Richard Smithc406cb72013-01-17 01:17:56 +000010134 /// \brief Find the object which is produced by the specified expression,
10135 /// if any.
10136 Object getObject(Expr *E, bool Mod) const {
10137 E = E->IgnoreParenCasts();
10138 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10139 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10140 return getObject(UO->getSubExpr(), Mod);
10141 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10142 if (BO->getOpcode() == BO_Comma)
10143 return getObject(BO->getRHS(), Mod);
10144 if (Mod && BO->isAssignmentOp())
10145 return getObject(BO->getLHS(), Mod);
10146 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10147 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10148 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10149 return ME->getMemberDecl();
10150 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10151 // FIXME: If this is a reference, map through to its value.
10152 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010153 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010154 }
10155
10156 /// \brief Note that an object was modified or used by an expression.
10157 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10158 Usage &U = UI.Uses[UK];
10159 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10160 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10161 ModAsSideEffect->push_back(std::make_pair(O, U));
10162 U.Use = Ref;
10163 U.Seq = Region;
10164 }
10165 }
10166 /// \brief Check whether a modification or use conflicts with a prior usage.
10167 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10168 bool IsModMod) {
10169 if (UI.Diagnosed)
10170 return;
10171
10172 const Usage &U = UI.Uses[OtherKind];
10173 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10174 return;
10175
10176 Expr *Mod = U.Use;
10177 Expr *ModOrUse = Ref;
10178 if (OtherKind == UK_Use)
10179 std::swap(Mod, ModOrUse);
10180
10181 SemaRef.Diag(Mod->getExprLoc(),
10182 IsModMod ? diag::warn_unsequenced_mod_mod
10183 : diag::warn_unsequenced_mod_use)
10184 << O << SourceRange(ModOrUse->getExprLoc());
10185 UI.Diagnosed = true;
10186 }
10187
10188 void notePreUse(Object O, Expr *Use) {
10189 UsageInfo &U = UsageMap[O];
10190 // Uses conflict with other modifications.
10191 checkUsage(O, U, Use, UK_ModAsValue, false);
10192 }
10193 void notePostUse(Object O, Expr *Use) {
10194 UsageInfo &U = UsageMap[O];
10195 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10196 addUsage(U, O, Use, UK_Use);
10197 }
10198
10199 void notePreMod(Object O, Expr *Mod) {
10200 UsageInfo &U = UsageMap[O];
10201 // Modifications conflict with other modifications and with uses.
10202 checkUsage(O, U, Mod, UK_ModAsValue, true);
10203 checkUsage(O, U, Mod, UK_Use, false);
10204 }
10205 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10206 UsageInfo &U = UsageMap[O];
10207 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10208 addUsage(U, O, Use, UK);
10209 }
10210
10211public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010212 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010213 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10214 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010215 Visit(E);
10216 }
10217
10218 void VisitStmt(Stmt *S) {
10219 // Skip all statements which aren't expressions for now.
10220 }
10221
10222 void VisitExpr(Expr *E) {
10223 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010224 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010225 }
10226
10227 void VisitCastExpr(CastExpr *E) {
10228 Object O = Object();
10229 if (E->getCastKind() == CK_LValueToRValue)
10230 O = getObject(E->getSubExpr(), false);
10231
10232 if (O)
10233 notePreUse(O, E);
10234 VisitExpr(E);
10235 if (O)
10236 notePostUse(O, E);
10237 }
10238
10239 void VisitBinComma(BinaryOperator *BO) {
10240 // C++11 [expr.comma]p1:
10241 // Every value computation and side effect associated with the left
10242 // expression is sequenced before every value computation and side
10243 // effect associated with the right expression.
10244 SequenceTree::Seq LHS = Tree.allocate(Region);
10245 SequenceTree::Seq RHS = Tree.allocate(Region);
10246 SequenceTree::Seq OldRegion = Region;
10247
10248 {
10249 SequencedSubexpression SeqLHS(*this);
10250 Region = LHS;
10251 Visit(BO->getLHS());
10252 }
10253
10254 Region = RHS;
10255 Visit(BO->getRHS());
10256
10257 Region = OldRegion;
10258
10259 // Forget that LHS and RHS are sequenced. They are both unsequenced
10260 // with respect to other stuff.
10261 Tree.merge(LHS);
10262 Tree.merge(RHS);
10263 }
10264
10265 void VisitBinAssign(BinaryOperator *BO) {
10266 // The modification is sequenced after the value computation of the LHS
10267 // and RHS, so check it before inspecting the operands and update the
10268 // map afterwards.
10269 Object O = getObject(BO->getLHS(), true);
10270 if (!O)
10271 return VisitExpr(BO);
10272
10273 notePreMod(O, BO);
10274
10275 // C++11 [expr.ass]p7:
10276 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10277 // only once.
10278 //
10279 // Therefore, for a compound assignment operator, O is considered used
10280 // everywhere except within the evaluation of E1 itself.
10281 if (isa<CompoundAssignOperator>(BO))
10282 notePreUse(O, BO);
10283
10284 Visit(BO->getLHS());
10285
10286 if (isa<CompoundAssignOperator>(BO))
10287 notePostUse(O, BO);
10288
10289 Visit(BO->getRHS());
10290
Richard Smith83e37bee2013-06-26 23:16:51 +000010291 // C++11 [expr.ass]p1:
10292 // the assignment is sequenced [...] before the value computation of the
10293 // assignment expression.
10294 // C11 6.5.16/3 has no such rule.
10295 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10296 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010297 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010298
Richard Smithc406cb72013-01-17 01:17:56 +000010299 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10300 VisitBinAssign(CAO);
10301 }
10302
10303 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10304 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10305 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10306 Object O = getObject(UO->getSubExpr(), true);
10307 if (!O)
10308 return VisitExpr(UO);
10309
10310 notePreMod(O, UO);
10311 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010312 // C++11 [expr.pre.incr]p1:
10313 // the expression ++x is equivalent to x+=1
10314 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10315 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010316 }
10317
10318 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10319 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10320 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10321 Object O = getObject(UO->getSubExpr(), true);
10322 if (!O)
10323 return VisitExpr(UO);
10324
10325 notePreMod(O, UO);
10326 Visit(UO->getSubExpr());
10327 notePostMod(O, UO, UK_ModAsSideEffect);
10328 }
10329
10330 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10331 void VisitBinLOr(BinaryOperator *BO) {
10332 // The side-effects of the LHS of an '&&' are sequenced before the
10333 // value computation of the RHS, and hence before the value computation
10334 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10335 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010336 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010337 {
10338 SequencedSubexpression Sequenced(*this);
10339 Visit(BO->getLHS());
10340 }
10341
10342 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010343 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010344 if (!Result)
10345 Visit(BO->getRHS());
10346 } else {
10347 // Check for unsequenced operations in the RHS, treating it as an
10348 // entirely separate evaluation.
10349 //
10350 // FIXME: If there are operations in the RHS which are unsequenced
10351 // with respect to operations outside the RHS, and those operations
10352 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010353 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010354 }
Richard Smithc406cb72013-01-17 01:17:56 +000010355 }
10356 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010357 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010358 {
10359 SequencedSubexpression Sequenced(*this);
10360 Visit(BO->getLHS());
10361 }
10362
10363 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010364 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010365 if (Result)
10366 Visit(BO->getRHS());
10367 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010368 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010369 }
Richard Smithc406cb72013-01-17 01:17:56 +000010370 }
10371
10372 // Only visit the condition, unless we can be sure which subexpression will
10373 // be chosen.
10374 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010375 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010376 {
10377 SequencedSubexpression Sequenced(*this);
10378 Visit(CO->getCond());
10379 }
Richard Smithc406cb72013-01-17 01:17:56 +000010380
10381 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010382 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010383 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010384 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010385 WorkList.push_back(CO->getTrueExpr());
10386 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010387 }
Richard Smithc406cb72013-01-17 01:17:56 +000010388 }
10389
Richard Smithe3dbfe02013-06-30 10:40:20 +000010390 void VisitCallExpr(CallExpr *CE) {
10391 // C++11 [intro.execution]p15:
10392 // When calling a function [...], every value computation and side effect
10393 // associated with any argument expression, or with the postfix expression
10394 // designating the called function, is sequenced before execution of every
10395 // expression or statement in the body of the function [and thus before
10396 // the value computation of its result].
10397 SequencedSubexpression Sequenced(*this);
10398 Base::VisitCallExpr(CE);
10399
10400 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10401 }
10402
Richard Smithc406cb72013-01-17 01:17:56 +000010403 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010404 // This is a call, so all subexpressions are sequenced before the result.
10405 SequencedSubexpression Sequenced(*this);
10406
Richard Smithc406cb72013-01-17 01:17:56 +000010407 if (!CCE->isListInitialization())
10408 return VisitExpr(CCE);
10409
10410 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010411 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010412 SequenceTree::Seq Parent = Region;
10413 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10414 E = CCE->arg_end();
10415 I != E; ++I) {
10416 Region = Tree.allocate(Parent);
10417 Elts.push_back(Region);
10418 Visit(*I);
10419 }
10420
10421 // Forget that the initializers are sequenced.
10422 Region = Parent;
10423 for (unsigned I = 0; I < Elts.size(); ++I)
10424 Tree.merge(Elts[I]);
10425 }
10426
10427 void VisitInitListExpr(InitListExpr *ILE) {
10428 if (!SemaRef.getLangOpts().CPlusPlus11)
10429 return VisitExpr(ILE);
10430
10431 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010432 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010433 SequenceTree::Seq Parent = Region;
10434 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10435 Expr *E = ILE->getInit(I);
10436 if (!E) continue;
10437 Region = Tree.allocate(Parent);
10438 Elts.push_back(Region);
10439 Visit(E);
10440 }
10441
10442 // Forget that the initializers are sequenced.
10443 Region = Parent;
10444 for (unsigned I = 0; I < Elts.size(); ++I)
10445 Tree.merge(Elts[I]);
10446 }
10447};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010448} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010449
10450void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010451 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010452 WorkList.push_back(E);
10453 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010454 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010455 SequenceChecker(*this, Item, WorkList);
10456 }
Richard Smithc406cb72013-01-17 01:17:56 +000010457}
10458
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010459void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10460 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010461 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010462 if (!E->isInstantiationDependent())
10463 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010464 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010465 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010466 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010467}
10468
John McCall1f425642010-11-11 03:21:53 +000010469void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10470 FieldDecl *BitField,
10471 Expr *Init) {
10472 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10473}
10474
David Majnemer61a5bbf2015-04-07 22:08:51 +000010475static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10476 SourceLocation Loc) {
10477 if (!PType->isVariablyModifiedType())
10478 return;
10479 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10480 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10481 return;
10482 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010483 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10484 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10485 return;
10486 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010487 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10488 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10489 return;
10490 }
10491
10492 const ArrayType *AT = S.Context.getAsArrayType(PType);
10493 if (!AT)
10494 return;
10495
10496 if (AT->getSizeModifier() != ArrayType::Star) {
10497 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10498 return;
10499 }
10500
10501 S.Diag(Loc, diag::err_array_star_in_function_definition);
10502}
10503
Mike Stump0c2ec772010-01-21 03:59:47 +000010504/// CheckParmsForFunctionDef - Check that the parameters of the given
10505/// function are appropriate for the definition of a function. This
10506/// takes care of any checks that cannot be performed on the
10507/// declaration itself, e.g., that the types of each of the function
10508/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010509bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010510 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010511 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010512 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010513 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10514 // function declarator that is part of a function definition of
10515 // that function shall not have incomplete type.
10516 //
10517 // This is also C++ [dcl.fct]p6.
10518 if (!Param->isInvalidDecl() &&
10519 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010520 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010521 Param->setInvalidDecl();
10522 HasInvalidParm = true;
10523 }
10524
10525 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10526 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010527 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010528 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010529 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010530 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010531 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010532
10533 // C99 6.7.5.3p12:
10534 // If the function declarator is not part of a definition of that
10535 // function, parameters may have incomplete type and may use the [*]
10536 // notation in their sequences of declarator specifiers to specify
10537 // variable length array types.
10538 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010539 // FIXME: This diagnostic should point the '[*]' if source-location
10540 // information is added for it.
10541 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010542
10543 // MSVC destroys objects passed by value in the callee. Therefore a
10544 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010545 // object's destructor. However, we don't perform any direct access check
10546 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010547 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10548 .getCXXABI()
10549 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010550 if (!Param->isInvalidDecl()) {
10551 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10552 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10553 if (!ClassDecl->isInvalidDecl() &&
10554 !ClassDecl->hasIrrelevantDestructor() &&
10555 !ClassDecl->isDependentContext()) {
10556 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10557 MarkFunctionReferenced(Param->getLocation(), Destructor);
10558 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10559 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010560 }
10561 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010562 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010563
10564 // Parameters with the pass_object_size attribute only need to be marked
10565 // constant at function definitions. Because we lack information about
10566 // whether we're on a declaration or definition when we're instantiating the
10567 // attribute, we need to check for constness here.
10568 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10569 if (!Param->getType().isConstQualified())
10570 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10571 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010572 }
10573
10574 return HasInvalidParm;
10575}
John McCall2b5c1b22010-08-12 21:44:57 +000010576
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010577/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10578/// or MemberExpr.
10579static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10580 ASTContext &Context) {
10581 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10582 return Context.getDeclAlign(DRE->getDecl());
10583
10584 if (const auto *ME = dyn_cast<MemberExpr>(E))
10585 return Context.getDeclAlign(ME->getMemberDecl());
10586
10587 return TypeAlign;
10588}
10589
John McCall2b5c1b22010-08-12 21:44:57 +000010590/// CheckCastAlign - Implements -Wcast-align, which warns when a
10591/// pointer cast increases the alignment requirements.
10592void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10593 // This is actually a lot of work to potentially be doing on every
10594 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010595 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010596 return;
10597
10598 // Ignore dependent types.
10599 if (T->isDependentType() || Op->getType()->isDependentType())
10600 return;
10601
10602 // Require that the destination be a pointer type.
10603 const PointerType *DestPtr = T->getAs<PointerType>();
10604 if (!DestPtr) return;
10605
10606 // If the destination has alignment 1, we're done.
10607 QualType DestPointee = DestPtr->getPointeeType();
10608 if (DestPointee->isIncompleteType()) return;
10609 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10610 if (DestAlign.isOne()) return;
10611
10612 // Require that the source be a pointer type.
10613 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10614 if (!SrcPtr) return;
10615 QualType SrcPointee = SrcPtr->getPointeeType();
10616
10617 // Whitelist casts from cv void*. We already implicitly
10618 // whitelisted casts to cv void*, since they have alignment 1.
10619 // Also whitelist casts involving incomplete types, which implicitly
10620 // includes 'void'.
10621 if (SrcPointee->isIncompleteType()) return;
10622
10623 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010624
10625 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10626 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10627 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10628 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10629 if (UO->getOpcode() == UO_AddrOf)
10630 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10631 }
10632
John McCall2b5c1b22010-08-12 21:44:57 +000010633 if (SrcAlign >= DestAlign) return;
10634
10635 Diag(TRange.getBegin(), diag::warn_cast_align)
10636 << Op->getType() << T
10637 << static_cast<unsigned>(SrcAlign.getQuantity())
10638 << static_cast<unsigned>(DestAlign.getQuantity())
10639 << TRange << Op->getSourceRange();
10640}
10641
Chandler Carruth28389f02011-08-05 09:10:50 +000010642/// \brief Check whether this array fits the idiom of a size-one tail padded
10643/// array member of a struct.
10644///
10645/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10646/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010647static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010648 const NamedDecl *ND) {
10649 if (Size != 1 || !ND) return false;
10650
10651 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10652 if (!FD) return false;
10653
10654 // Don't consider sizes resulting from macro expansions or template argument
10655 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010656
10657 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010658 while (TInfo) {
10659 TypeLoc TL = TInfo->getTypeLoc();
10660 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010661 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10662 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010663 TInfo = TDL->getTypeSourceInfo();
10664 continue;
10665 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010666 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10667 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010668 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10669 return false;
10670 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010671 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010672 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010673
10674 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010675 if (!RD) return false;
10676 if (RD->isUnion()) return false;
10677 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10678 if (!CRD->isStandardLayout()) return false;
10679 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010680
Benjamin Kramer8c543672011-08-06 03:04:42 +000010681 // See if this is the last field decl in the record.
10682 const Decl *D = FD;
10683 while ((D = D->getNextDeclInContext()))
10684 if (isa<FieldDecl>(D))
10685 return false;
10686 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010687}
10688
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010689void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010690 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010691 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010692 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010693 if (IndexExpr->isValueDependent())
10694 return;
10695
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010696 const Type *EffectiveType =
10697 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010698 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010699 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010700 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010701 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010702 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010703
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010704 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010705 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010706 return;
Richard Smith13f67182011-12-16 19:31:14 +000010707 if (IndexNegated)
10708 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010709
Craig Topperc3ec1492014-05-26 06:22:03 +000010710 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010711 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10712 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010713 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010714 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010715
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010716 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010717 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010718 if (!size.isStrictlyPositive())
10719 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010720
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010721 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010722 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010723 // Make sure we're comparing apples to apples when comparing index to size
10724 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10725 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010726 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010727 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010728 if (ptrarith_typesize != array_typesize) {
10729 // There's a cast to a different size type involved
10730 uint64_t ratio = array_typesize / ptrarith_typesize;
10731 // TODO: Be smarter about handling cases where array_typesize is not a
10732 // multiple of ptrarith_typesize
10733 if (ptrarith_typesize * ratio == array_typesize)
10734 size *= llvm::APInt(size.getBitWidth(), ratio);
10735 }
10736 }
10737
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010738 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010739 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010740 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010741 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010742
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010743 // For array subscripting the index must be less than size, but for pointer
10744 // arithmetic also allow the index (offset) to be equal to size since
10745 // computing the next address after the end of the array is legal and
10746 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010747 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010748 return;
10749
10750 // Also don't warn for arrays of size 1 which are members of some
10751 // structure. These are often used to approximate flexible arrays in C89
10752 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010753 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000010754 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010755
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010756 // Suppress the warning if the subscript expression (as identified by the
10757 // ']' location) and the index expression are both from macro expansions
10758 // within a system header.
10759 if (ASE) {
10760 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10761 ASE->getRBracketLoc());
10762 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10763 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10764 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000010765 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010766 return;
10767 }
10768 }
10769
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010770 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010771 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010772 DiagID = diag::warn_array_index_exceeds_bounds;
10773
10774 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10775 PDiag(DiagID) << index.toString(10, true)
10776 << size.toString(10, true)
10777 << (unsigned)size.getLimitedValue(~0U)
10778 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010779 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010780 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010781 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010782 DiagID = diag::warn_ptr_arith_precedes_bounds;
10783 if (index.isNegative()) index = -index;
10784 }
10785
10786 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10787 PDiag(DiagID) << index.toString(10, true)
10788 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000010789 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000010790
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000010791 if (!ND) {
10792 // Try harder to find a NamedDecl to point at in the note.
10793 while (const ArraySubscriptExpr *ASE =
10794 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10795 BaseExpr = ASE->getBase()->IgnoreParenCasts();
10796 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10797 ND = dyn_cast<NamedDecl>(DRE->getDecl());
10798 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10799 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10800 }
10801
Chandler Carruth1af88f12011-02-17 21:10:52 +000010802 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010803 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10804 PDiag(diag::note_array_index_out_of_bounds)
10805 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000010806}
10807
Ted Kremenekdf26df72011-03-01 18:41:00 +000010808void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010809 int AllowOnePastEnd = 0;
10810 while (expr) {
10811 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000010812 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010813 case Stmt::ArraySubscriptExprClass: {
10814 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010815 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010816 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000010817 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010818 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010819 case Stmt::OMPArraySectionExprClass: {
10820 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10821 if (ASE->getLowerBound())
10822 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10823 /*ASE=*/nullptr, AllowOnePastEnd > 0);
10824 return;
10825 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010826 case Stmt::UnaryOperatorClass: {
10827 // Only unwrap the * and & unary operators
10828 const UnaryOperator *UO = cast<UnaryOperator>(expr);
10829 expr = UO->getSubExpr();
10830 switch (UO->getOpcode()) {
10831 case UO_AddrOf:
10832 AllowOnePastEnd++;
10833 break;
10834 case UO_Deref:
10835 AllowOnePastEnd--;
10836 break;
10837 default:
10838 return;
10839 }
10840 break;
10841 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010842 case Stmt::ConditionalOperatorClass: {
10843 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10844 if (const Expr *lhs = cond->getLHS())
10845 CheckArrayAccess(lhs);
10846 if (const Expr *rhs = cond->getRHS())
10847 CheckArrayAccess(rhs);
10848 return;
10849 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000010850 case Stmt::CXXOperatorCallExprClass: {
10851 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
10852 for (const auto *Arg : OCE->arguments())
10853 CheckArrayAccess(Arg);
10854 return;
10855 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010856 default:
10857 return;
10858 }
Peter Collingbourne91147592011-04-15 00:35:48 +000010859 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000010860}
John McCall31168b02011-06-15 23:02:42 +000010861
10862//===--- CHECK: Objective-C retain cycles ----------------------------------//
10863
10864namespace {
10865 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000010866 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000010867 VarDecl *Variable;
10868 SourceRange Range;
10869 SourceLocation Loc;
10870 bool Indirect;
10871
10872 void setLocsFrom(Expr *e) {
10873 Loc = e->getExprLoc();
10874 Range = e->getSourceRange();
10875 }
10876 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010877} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000010878
10879/// Consider whether capturing the given variable can possibly lead to
10880/// a retain cycle.
10881static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000010882 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000010883 // lifetime. In MRR, it's captured strongly if the variable is
10884 // __block and has an appropriate type.
10885 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10886 return false;
10887
10888 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000010889 if (ref)
10890 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000010891 return true;
10892}
10893
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010894static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000010895 while (true) {
10896 e = e->IgnoreParens();
10897 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10898 switch (cast->getCastKind()) {
10899 case CK_BitCast:
10900 case CK_LValueBitCast:
10901 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000010902 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000010903 e = cast->getSubExpr();
10904 continue;
10905
John McCall31168b02011-06-15 23:02:42 +000010906 default:
10907 return false;
10908 }
10909 }
10910
10911 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10912 ObjCIvarDecl *ivar = ref->getDecl();
10913 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10914 return false;
10915
10916 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010917 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000010918 return false;
10919
10920 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10921 owner.Indirect = true;
10922 return true;
10923 }
10924
10925 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10926 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10927 if (!var) return false;
10928 return considerVariable(var, ref, owner);
10929 }
10930
John McCall31168b02011-06-15 23:02:42 +000010931 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10932 if (member->isArrow()) return false;
10933
10934 // Don't count this as an indirect ownership.
10935 e = member->getBase();
10936 continue;
10937 }
10938
John McCallfe96e0b2011-11-06 09:01:30 +000010939 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10940 // Only pay attention to pseudo-objects on property references.
10941 ObjCPropertyRefExpr *pre
10942 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10943 ->IgnoreParens());
10944 if (!pre) return false;
10945 if (pre->isImplicitProperty()) return false;
10946 ObjCPropertyDecl *property = pre->getExplicitProperty();
10947 if (!property->isRetaining() &&
10948 !(property->getPropertyIvarDecl() &&
10949 property->getPropertyIvarDecl()->getType()
10950 .getObjCLifetime() == Qualifiers::OCL_Strong))
10951 return false;
10952
10953 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000010954 if (pre->isSuperReceiver()) {
10955 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10956 if (!owner.Variable)
10957 return false;
10958 owner.Loc = pre->getLocation();
10959 owner.Range = pre->getSourceRange();
10960 return true;
10961 }
John McCallfe96e0b2011-11-06 09:01:30 +000010962 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10963 ->getSourceExpr());
10964 continue;
10965 }
10966
John McCall31168b02011-06-15 23:02:42 +000010967 // Array ivars?
10968
10969 return false;
10970 }
10971}
10972
10973namespace {
10974 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10975 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10976 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010977 Context(Context), Variable(variable), Capturer(nullptr),
10978 VarWillBeReased(false) {}
10979 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000010980 VarDecl *Variable;
10981 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000010982 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000010983
10984 void VisitDeclRefExpr(DeclRefExpr *ref) {
10985 if (ref->getDecl() == Variable && !Capturer)
10986 Capturer = ref;
10987 }
10988
John McCall31168b02011-06-15 23:02:42 +000010989 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10990 if (Capturer) return;
10991 Visit(ref->getBase());
10992 if (Capturer && ref->isFreeIvar())
10993 Capturer = ref;
10994 }
10995
10996 void VisitBlockExpr(BlockExpr *block) {
10997 // Look inside nested blocks
10998 if (block->getBlockDecl()->capturesVariable(Variable))
10999 Visit(block->getBlockDecl()->getBody());
11000 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011001
11002 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11003 if (Capturer) return;
11004 if (OVE->getSourceExpr())
11005 Visit(OVE->getSourceExpr());
11006 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011007 void VisitBinaryOperator(BinaryOperator *BinOp) {
11008 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11009 return;
11010 Expr *LHS = BinOp->getLHS();
11011 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11012 if (DRE->getDecl() != Variable)
11013 return;
11014 if (Expr *RHS = BinOp->getRHS()) {
11015 RHS = RHS->IgnoreParenCasts();
11016 llvm::APSInt Value;
11017 VarWillBeReased =
11018 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11019 }
11020 }
11021 }
John McCall31168b02011-06-15 23:02:42 +000011022 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011023} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011024
11025/// Check whether the given argument is a block which captures a
11026/// variable.
11027static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11028 assert(owner.Variable && owner.Loc.isValid());
11029
11030 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011031
11032 // Look through [^{...} copy] and Block_copy(^{...}).
11033 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11034 Selector Cmd = ME->getSelector();
11035 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11036 e = ME->getInstanceReceiver();
11037 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011038 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011039 e = e->IgnoreParenCasts();
11040 }
11041 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11042 if (CE->getNumArgs() == 1) {
11043 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011044 if (Fn) {
11045 const IdentifierInfo *FnI = Fn->getIdentifier();
11046 if (FnI && FnI->isStr("_Block_copy")) {
11047 e = CE->getArg(0)->IgnoreParenCasts();
11048 }
11049 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011050 }
11051 }
11052
John McCall31168b02011-06-15 23:02:42 +000011053 BlockExpr *block = dyn_cast<BlockExpr>(e);
11054 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011055 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011056
11057 FindCaptureVisitor visitor(S.Context, owner.Variable);
11058 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011059 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011060}
11061
11062static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11063 RetainCycleOwner &owner) {
11064 assert(capturer);
11065 assert(owner.Variable && owner.Loc.isValid());
11066
11067 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11068 << owner.Variable << capturer->getSourceRange();
11069 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11070 << owner.Indirect << owner.Range;
11071}
11072
11073/// Check for a keyword selector that starts with the word 'add' or
11074/// 'set'.
11075static bool isSetterLikeSelector(Selector sel) {
11076 if (sel.isUnarySelector()) return false;
11077
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011078 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011079 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011080 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011081 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011082 else if (str.startswith("add")) {
11083 // Specially whitelist 'addOperationWithBlock:'.
11084 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11085 return false;
11086 str = str.substr(3);
11087 }
John McCall31168b02011-06-15 23:02:42 +000011088 else
11089 return false;
11090
11091 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011092 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011093}
11094
Benjamin Kramer3a743452015-03-09 15:03:32 +000011095static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11096 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011097 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11098 Message->getReceiverInterface(),
11099 NSAPI::ClassId_NSMutableArray);
11100 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011101 return None;
11102 }
11103
11104 Selector Sel = Message->getSelector();
11105
11106 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11107 S.NSAPIObj->getNSArrayMethodKind(Sel);
11108 if (!MKOpt) {
11109 return None;
11110 }
11111
11112 NSAPI::NSArrayMethodKind MK = *MKOpt;
11113
11114 switch (MK) {
11115 case NSAPI::NSMutableArr_addObject:
11116 case NSAPI::NSMutableArr_insertObjectAtIndex:
11117 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11118 return 0;
11119 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11120 return 1;
11121
11122 default:
11123 return None;
11124 }
11125
11126 return None;
11127}
11128
11129static
11130Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11131 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011132 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11133 Message->getReceiverInterface(),
11134 NSAPI::ClassId_NSMutableDictionary);
11135 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011136 return None;
11137 }
11138
11139 Selector Sel = Message->getSelector();
11140
11141 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11142 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11143 if (!MKOpt) {
11144 return None;
11145 }
11146
11147 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11148
11149 switch (MK) {
11150 case NSAPI::NSMutableDict_setObjectForKey:
11151 case NSAPI::NSMutableDict_setValueForKey:
11152 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11153 return 0;
11154
11155 default:
11156 return None;
11157 }
11158
11159 return None;
11160}
11161
11162static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011163 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11164 Message->getReceiverInterface(),
11165 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011166
Alex Denisov5dfac812015-08-06 04:51:14 +000011167 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11168 Message->getReceiverInterface(),
11169 NSAPI::ClassId_NSMutableOrderedSet);
11170 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011171 return None;
11172 }
11173
11174 Selector Sel = Message->getSelector();
11175
11176 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11177 if (!MKOpt) {
11178 return None;
11179 }
11180
11181 NSAPI::NSSetMethodKind MK = *MKOpt;
11182
11183 switch (MK) {
11184 case NSAPI::NSMutableSet_addObject:
11185 case NSAPI::NSOrderedSet_setObjectAtIndex:
11186 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11187 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11188 return 0;
11189 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11190 return 1;
11191 }
11192
11193 return None;
11194}
11195
11196void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11197 if (!Message->isInstanceMessage()) {
11198 return;
11199 }
11200
11201 Optional<int> ArgOpt;
11202
11203 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11204 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11205 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11206 return;
11207 }
11208
11209 int ArgIndex = *ArgOpt;
11210
Alex Denisove1d882c2015-03-04 17:55:52 +000011211 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11212 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11213 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11214 }
11215
Alex Denisov5dfac812015-08-06 04:51:14 +000011216 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011217 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011218 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011219 Diag(Message->getSourceRange().getBegin(),
11220 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011221 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011222 }
11223 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011224 } else {
11225 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11226
11227 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11228 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11229 }
11230
11231 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11232 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11233 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11234 ValueDecl *Decl = ReceiverRE->getDecl();
11235 Diag(Message->getSourceRange().getBegin(),
11236 diag::warn_objc_circular_container)
11237 << Decl->getName() << Decl->getName();
11238 if (!ArgRE->isObjCSelfExpr()) {
11239 Diag(Decl->getLocation(),
11240 diag::note_objc_circular_container_declared_here)
11241 << Decl->getName();
11242 }
11243 }
11244 }
11245 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11246 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11247 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11248 ObjCIvarDecl *Decl = IvarRE->getDecl();
11249 Diag(Message->getSourceRange().getBegin(),
11250 diag::warn_objc_circular_container)
11251 << Decl->getName() << Decl->getName();
11252 Diag(Decl->getLocation(),
11253 diag::note_objc_circular_container_declared_here)
11254 << Decl->getName();
11255 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011256 }
11257 }
11258 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011259}
11260
John McCall31168b02011-06-15 23:02:42 +000011261/// Check a message send to see if it's likely to cause a retain cycle.
11262void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11263 // Only check instance methods whose selector looks like a setter.
11264 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11265 return;
11266
11267 // Try to find a variable that the receiver is strongly owned by.
11268 RetainCycleOwner owner;
11269 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011270 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011271 return;
11272 } else {
11273 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11274 owner.Variable = getCurMethodDecl()->getSelfDecl();
11275 owner.Loc = msg->getSuperLoc();
11276 owner.Range = msg->getSuperLoc();
11277 }
11278
11279 // Check whether the receiver is captured by any of the arguments.
11280 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11281 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11282 return diagnoseRetainCycle(*this, capturer, owner);
11283}
11284
11285/// Check a property assign to see if it's likely to cause a retain cycle.
11286void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11287 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011288 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011289 return;
11290
11291 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11292 diagnoseRetainCycle(*this, capturer, owner);
11293}
11294
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011295void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11296 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011297 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011298 return;
11299
11300 // Because we don't have an expression for the variable, we have to set the
11301 // location explicitly here.
11302 Owner.Loc = Var->getLocation();
11303 Owner.Range = Var->getSourceRange();
11304
11305 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11306 diagnoseRetainCycle(*this, Capturer, Owner);
11307}
11308
Ted Kremenek9304da92012-12-21 08:04:28 +000011309static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11310 Expr *RHS, bool isProperty) {
11311 // Check if RHS is an Objective-C object literal, which also can get
11312 // immediately zapped in a weak reference. Note that we explicitly
11313 // allow ObjCStringLiterals, since those are designed to never really die.
11314 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011315
Ted Kremenek64873352012-12-21 22:46:35 +000011316 // This enum needs to match with the 'select' in
11317 // warn_objc_arc_literal_assign (off-by-1).
11318 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11319 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11320 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011321
11322 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011323 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011324 << (isProperty ? 0 : 1)
11325 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011326
11327 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011328}
11329
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011330static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11331 Qualifiers::ObjCLifetime LT,
11332 Expr *RHS, bool isProperty) {
11333 // Strip off any implicit cast added to get to the one ARC-specific.
11334 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11335 if (cast->getCastKind() == CK_ARCConsumeObject) {
11336 S.Diag(Loc, diag::warn_arc_retained_assign)
11337 << (LT == Qualifiers::OCL_ExplicitNone)
11338 << (isProperty ? 0 : 1)
11339 << RHS->getSourceRange();
11340 return true;
11341 }
11342 RHS = cast->getSubExpr();
11343 }
11344
11345 if (LT == Qualifiers::OCL_Weak &&
11346 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11347 return true;
11348
11349 return false;
11350}
11351
Ted Kremenekb36234d2012-12-21 08:04:20 +000011352bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11353 QualType LHS, Expr *RHS) {
11354 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11355
11356 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11357 return false;
11358
11359 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11360 return true;
11361
11362 return false;
11363}
11364
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011365void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11366 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011367 QualType LHSType;
11368 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011369 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011370 ObjCPropertyRefExpr *PRE
11371 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11372 if (PRE && !PRE->isImplicitProperty()) {
11373 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11374 if (PD)
11375 LHSType = PD->getType();
11376 }
11377
11378 if (LHSType.isNull())
11379 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011380
11381 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11382
11383 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011384 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011385 getCurFunction()->markSafeWeakUse(LHS);
11386 }
11387
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011388 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11389 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011390
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011391 // FIXME. Check for other life times.
11392 if (LT != Qualifiers::OCL_None)
11393 return;
11394
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011395 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011396 if (PRE->isImplicitProperty())
11397 return;
11398 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11399 if (!PD)
11400 return;
11401
Bill Wendling44426052012-12-20 19:22:21 +000011402 unsigned Attributes = PD->getPropertyAttributes();
11403 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011404 // when 'assign' attribute was not explicitly specified
11405 // by user, ignore it and rely on property type itself
11406 // for lifetime info.
11407 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11408 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11409 LHSType->isObjCRetainableType())
11410 return;
11411
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011412 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011413 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011414 Diag(Loc, diag::warn_arc_retained_property_assign)
11415 << RHS->getSourceRange();
11416 return;
11417 }
11418 RHS = cast->getSubExpr();
11419 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011420 }
Bill Wendling44426052012-12-20 19:22:21 +000011421 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011422 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11423 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011424 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011425 }
11426}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011427
11428//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11429
11430namespace {
11431bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11432 SourceLocation StmtLoc,
11433 const NullStmt *Body) {
11434 // Do not warn if the body is a macro that expands to nothing, e.g:
11435 //
11436 // #define CALL(x)
11437 // if (condition)
11438 // CALL(0);
11439 //
11440 if (Body->hasLeadingEmptyMacro())
11441 return false;
11442
11443 // Get line numbers of statement and body.
11444 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011445 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011446 &StmtLineInvalid);
11447 if (StmtLineInvalid)
11448 return false;
11449
11450 bool BodyLineInvalid;
11451 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11452 &BodyLineInvalid);
11453 if (BodyLineInvalid)
11454 return false;
11455
11456 // Warn if null statement and body are on the same line.
11457 if (StmtLine != BodyLine)
11458 return false;
11459
11460 return true;
11461}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011462} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011463
11464void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11465 const Stmt *Body,
11466 unsigned DiagID) {
11467 // Since this is a syntactic check, don't emit diagnostic for template
11468 // instantiations, this just adds noise.
11469 if (CurrentInstantiationScope)
11470 return;
11471
11472 // The body should be a null statement.
11473 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11474 if (!NBody)
11475 return;
11476
11477 // Do the usual checks.
11478 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11479 return;
11480
11481 Diag(NBody->getSemiLoc(), DiagID);
11482 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11483}
11484
11485void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11486 const Stmt *PossibleBody) {
11487 assert(!CurrentInstantiationScope); // Ensured by caller
11488
11489 SourceLocation StmtLoc;
11490 const Stmt *Body;
11491 unsigned DiagID;
11492 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11493 StmtLoc = FS->getRParenLoc();
11494 Body = FS->getBody();
11495 DiagID = diag::warn_empty_for_body;
11496 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11497 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11498 Body = WS->getBody();
11499 DiagID = diag::warn_empty_while_body;
11500 } else
11501 return; // Neither `for' nor `while'.
11502
11503 // The body should be a null statement.
11504 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11505 if (!NBody)
11506 return;
11507
11508 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011509 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011510 return;
11511
11512 // Do the usual checks.
11513 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11514 return;
11515
11516 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11517 // noise level low, emit diagnostics only if for/while is followed by a
11518 // CompoundStmt, e.g.:
11519 // for (int i = 0; i < n; i++);
11520 // {
11521 // a(i);
11522 // }
11523 // or if for/while is followed by a statement with more indentation
11524 // than for/while itself:
11525 // for (int i = 0; i < n; i++);
11526 // a(i);
11527 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11528 if (!ProbableTypo) {
11529 bool BodyColInvalid;
11530 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11531 PossibleBody->getLocStart(),
11532 &BodyColInvalid);
11533 if (BodyColInvalid)
11534 return;
11535
11536 bool StmtColInvalid;
11537 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11538 S->getLocStart(),
11539 &StmtColInvalid);
11540 if (StmtColInvalid)
11541 return;
11542
11543 if (BodyCol > StmtCol)
11544 ProbableTypo = true;
11545 }
11546
11547 if (ProbableTypo) {
11548 Diag(NBody->getSemiLoc(), DiagID);
11549 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11550 }
11551}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011552
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011553//===--- CHECK: Warn on self move with std::move. -------------------------===//
11554
11555/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11556void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11557 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011558 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11559 return;
11560
Richard Smith51ec0cf2017-02-21 01:17:38 +000011561 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011562 return;
11563
11564 // Strip parens and casts away.
11565 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11566 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11567
11568 // Check for a call expression
11569 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11570 if (!CE || CE->getNumArgs() != 1)
11571 return;
11572
11573 // Check for a call to std::move
11574 const FunctionDecl *FD = CE->getDirectCallee();
11575 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11576 !FD->getIdentifier()->isStr("move"))
11577 return;
11578
11579 // Get argument from std::move
11580 RHSExpr = CE->getArg(0);
11581
11582 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11583 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11584
11585 // Two DeclRefExpr's, check that the decls are the same.
11586 if (LHSDeclRef && RHSDeclRef) {
11587 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11588 return;
11589 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11590 RHSDeclRef->getDecl()->getCanonicalDecl())
11591 return;
11592
11593 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11594 << LHSExpr->getSourceRange()
11595 << RHSExpr->getSourceRange();
11596 return;
11597 }
11598
11599 // Member variables require a different approach to check for self moves.
11600 // MemberExpr's are the same if every nested MemberExpr refers to the same
11601 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11602 // the base Expr's are CXXThisExpr's.
11603 const Expr *LHSBase = LHSExpr;
11604 const Expr *RHSBase = RHSExpr;
11605 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11606 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11607 if (!LHSME || !RHSME)
11608 return;
11609
11610 while (LHSME && RHSME) {
11611 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11612 RHSME->getMemberDecl()->getCanonicalDecl())
11613 return;
11614
11615 LHSBase = LHSME->getBase();
11616 RHSBase = RHSME->getBase();
11617 LHSME = dyn_cast<MemberExpr>(LHSBase);
11618 RHSME = dyn_cast<MemberExpr>(RHSBase);
11619 }
11620
11621 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11622 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11623 if (LHSDeclRef && RHSDeclRef) {
11624 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11625 return;
11626 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11627 RHSDeclRef->getDecl()->getCanonicalDecl())
11628 return;
11629
11630 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11631 << LHSExpr->getSourceRange()
11632 << RHSExpr->getSourceRange();
11633 return;
11634 }
11635
11636 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11637 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11638 << LHSExpr->getSourceRange()
11639 << RHSExpr->getSourceRange();
11640}
11641
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011642//===--- Layout compatibility ----------------------------------------------//
11643
11644namespace {
11645
11646bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11647
11648/// \brief Check if two enumeration types are layout-compatible.
11649bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11650 // C++11 [dcl.enum] p8:
11651 // Two enumeration types are layout-compatible if they have the same
11652 // underlying type.
11653 return ED1->isComplete() && ED2->isComplete() &&
11654 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11655}
11656
11657/// \brief Check if two fields are layout-compatible.
11658bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11659 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11660 return false;
11661
11662 if (Field1->isBitField() != Field2->isBitField())
11663 return false;
11664
11665 if (Field1->isBitField()) {
11666 // Make sure that the bit-fields are the same length.
11667 unsigned Bits1 = Field1->getBitWidthValue(C);
11668 unsigned Bits2 = Field2->getBitWidthValue(C);
11669
11670 if (Bits1 != Bits2)
11671 return false;
11672 }
11673
11674 return true;
11675}
11676
11677/// \brief Check if two standard-layout structs are layout-compatible.
11678/// (C++11 [class.mem] p17)
11679bool isLayoutCompatibleStruct(ASTContext &C,
11680 RecordDecl *RD1,
11681 RecordDecl *RD2) {
11682 // If both records are C++ classes, check that base classes match.
11683 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11684 // If one of records is a CXXRecordDecl we are in C++ mode,
11685 // thus the other one is a CXXRecordDecl, too.
11686 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11687 // Check number of base classes.
11688 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11689 return false;
11690
11691 // Check the base classes.
11692 for (CXXRecordDecl::base_class_const_iterator
11693 Base1 = D1CXX->bases_begin(),
11694 BaseEnd1 = D1CXX->bases_end(),
11695 Base2 = D2CXX->bases_begin();
11696 Base1 != BaseEnd1;
11697 ++Base1, ++Base2) {
11698 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11699 return false;
11700 }
11701 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11702 // If only RD2 is a C++ class, it should have zero base classes.
11703 if (D2CXX->getNumBases() > 0)
11704 return false;
11705 }
11706
11707 // Check the fields.
11708 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11709 Field2End = RD2->field_end(),
11710 Field1 = RD1->field_begin(),
11711 Field1End = RD1->field_end();
11712 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11713 if (!isLayoutCompatible(C, *Field1, *Field2))
11714 return false;
11715 }
11716 if (Field1 != Field1End || Field2 != Field2End)
11717 return false;
11718
11719 return true;
11720}
11721
11722/// \brief Check if two standard-layout unions are layout-compatible.
11723/// (C++11 [class.mem] p18)
11724bool isLayoutCompatibleUnion(ASTContext &C,
11725 RecordDecl *RD1,
11726 RecordDecl *RD2) {
11727 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011728 for (auto *Field2 : RD2->fields())
11729 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011730
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011731 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011732 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11733 I = UnmatchedFields.begin(),
11734 E = UnmatchedFields.end();
11735
11736 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011737 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011738 bool Result = UnmatchedFields.erase(*I);
11739 (void) Result;
11740 assert(Result);
11741 break;
11742 }
11743 }
11744 if (I == E)
11745 return false;
11746 }
11747
11748 return UnmatchedFields.empty();
11749}
11750
11751bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11752 if (RD1->isUnion() != RD2->isUnion())
11753 return false;
11754
11755 if (RD1->isUnion())
11756 return isLayoutCompatibleUnion(C, RD1, RD2);
11757 else
11758 return isLayoutCompatibleStruct(C, RD1, RD2);
11759}
11760
11761/// \brief Check if two types are layout-compatible in C++11 sense.
11762bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11763 if (T1.isNull() || T2.isNull())
11764 return false;
11765
11766 // C++11 [basic.types] p11:
11767 // If two types T1 and T2 are the same type, then T1 and T2 are
11768 // layout-compatible types.
11769 if (C.hasSameType(T1, T2))
11770 return true;
11771
11772 T1 = T1.getCanonicalType().getUnqualifiedType();
11773 T2 = T2.getCanonicalType().getUnqualifiedType();
11774
11775 const Type::TypeClass TC1 = T1->getTypeClass();
11776 const Type::TypeClass TC2 = T2->getTypeClass();
11777
11778 if (TC1 != TC2)
11779 return false;
11780
11781 if (TC1 == Type::Enum) {
11782 return isLayoutCompatible(C,
11783 cast<EnumType>(T1)->getDecl(),
11784 cast<EnumType>(T2)->getDecl());
11785 } else if (TC1 == Type::Record) {
11786 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11787 return false;
11788
11789 return isLayoutCompatible(C,
11790 cast<RecordType>(T1)->getDecl(),
11791 cast<RecordType>(T2)->getDecl());
11792 }
11793
11794 return false;
11795}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011796} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011797
11798//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11799
11800namespace {
11801/// \brief Given a type tag expression find the type tag itself.
11802///
11803/// \param TypeExpr Type tag expression, as it appears in user's code.
11804///
11805/// \param VD Declaration of an identifier that appears in a type tag.
11806///
11807/// \param MagicValue Type tag magic value.
11808bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11809 const ValueDecl **VD, uint64_t *MagicValue) {
11810 while(true) {
11811 if (!TypeExpr)
11812 return false;
11813
11814 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11815
11816 switch (TypeExpr->getStmtClass()) {
11817 case Stmt::UnaryOperatorClass: {
11818 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11819 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11820 TypeExpr = UO->getSubExpr();
11821 continue;
11822 }
11823 return false;
11824 }
11825
11826 case Stmt::DeclRefExprClass: {
11827 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11828 *VD = DRE->getDecl();
11829 return true;
11830 }
11831
11832 case Stmt::IntegerLiteralClass: {
11833 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11834 llvm::APInt MagicValueAPInt = IL->getValue();
11835 if (MagicValueAPInt.getActiveBits() <= 64) {
11836 *MagicValue = MagicValueAPInt.getZExtValue();
11837 return true;
11838 } else
11839 return false;
11840 }
11841
11842 case Stmt::BinaryConditionalOperatorClass:
11843 case Stmt::ConditionalOperatorClass: {
11844 const AbstractConditionalOperator *ACO =
11845 cast<AbstractConditionalOperator>(TypeExpr);
11846 bool Result;
11847 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11848 if (Result)
11849 TypeExpr = ACO->getTrueExpr();
11850 else
11851 TypeExpr = ACO->getFalseExpr();
11852 continue;
11853 }
11854 return false;
11855 }
11856
11857 case Stmt::BinaryOperatorClass: {
11858 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11859 if (BO->getOpcode() == BO_Comma) {
11860 TypeExpr = BO->getRHS();
11861 continue;
11862 }
11863 return false;
11864 }
11865
11866 default:
11867 return false;
11868 }
11869 }
11870}
11871
11872/// \brief Retrieve the C type corresponding to type tag TypeExpr.
11873///
11874/// \param TypeExpr Expression that specifies a type tag.
11875///
11876/// \param MagicValues Registered magic values.
11877///
11878/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11879/// kind.
11880///
11881/// \param TypeInfo Information about the corresponding C type.
11882///
11883/// \returns true if the corresponding C type was found.
11884bool GetMatchingCType(
11885 const IdentifierInfo *ArgumentKind,
11886 const Expr *TypeExpr, const ASTContext &Ctx,
11887 const llvm::DenseMap<Sema::TypeTagMagicValue,
11888 Sema::TypeTagData> *MagicValues,
11889 bool &FoundWrongKind,
11890 Sema::TypeTagData &TypeInfo) {
11891 FoundWrongKind = false;
11892
11893 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000011894 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011895
11896 uint64_t MagicValue;
11897
11898 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11899 return false;
11900
11901 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000011902 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011903 if (I->getArgumentKind() != ArgumentKind) {
11904 FoundWrongKind = true;
11905 return false;
11906 }
11907 TypeInfo.Type = I->getMatchingCType();
11908 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11909 TypeInfo.MustBeNull = I->getMustBeNull();
11910 return true;
11911 }
11912 return false;
11913 }
11914
11915 if (!MagicValues)
11916 return false;
11917
11918 llvm::DenseMap<Sema::TypeTagMagicValue,
11919 Sema::TypeTagData>::const_iterator I =
11920 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11921 if (I == MagicValues->end())
11922 return false;
11923
11924 TypeInfo = I->second;
11925 return true;
11926}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011927} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011928
11929void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11930 uint64_t MagicValue, QualType Type,
11931 bool LayoutCompatible,
11932 bool MustBeNull) {
11933 if (!TypeTagForDatatypeMagicValues)
11934 TypeTagForDatatypeMagicValues.reset(
11935 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11936
11937 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11938 (*TypeTagForDatatypeMagicValues)[Magic] =
11939 TypeTagData(Type, LayoutCompatible, MustBeNull);
11940}
11941
11942namespace {
11943bool IsSameCharType(QualType T1, QualType T2) {
11944 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11945 if (!BT1)
11946 return false;
11947
11948 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11949 if (!BT2)
11950 return false;
11951
11952 BuiltinType::Kind T1Kind = BT1->getKind();
11953 BuiltinType::Kind T2Kind = BT2->getKind();
11954
11955 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11956 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11957 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11958 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11959}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011960} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011961
11962void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11963 const Expr * const *ExprArgs) {
11964 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11965 bool IsPointerAttr = Attr->getIsPointer();
11966
11967 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11968 bool FoundWrongKind;
11969 TypeTagData TypeInfo;
11970 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11971 TypeTagForDatatypeMagicValues.get(),
11972 FoundWrongKind, TypeInfo)) {
11973 if (FoundWrongKind)
11974 Diag(TypeTagExpr->getExprLoc(),
11975 diag::warn_type_tag_for_datatype_wrong_kind)
11976 << TypeTagExpr->getSourceRange();
11977 return;
11978 }
11979
11980 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11981 if (IsPointerAttr) {
11982 // Skip implicit cast of pointer to `void *' (as a function argument).
11983 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000011984 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000011985 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011986 ArgumentExpr = ICE->getSubExpr();
11987 }
11988 QualType ArgumentType = ArgumentExpr->getType();
11989
11990 // Passing a `void*' pointer shouldn't trigger a warning.
11991 if (IsPointerAttr && ArgumentType->isVoidPointerType())
11992 return;
11993
11994 if (TypeInfo.MustBeNull) {
11995 // Type tag with matching void type requires a null pointer.
11996 if (!ArgumentExpr->isNullPointerConstant(Context,
11997 Expr::NPC_ValueDependentIsNotNull)) {
11998 Diag(ArgumentExpr->getExprLoc(),
11999 diag::warn_type_safety_null_pointer_required)
12000 << ArgumentKind->getName()
12001 << ArgumentExpr->getSourceRange()
12002 << TypeTagExpr->getSourceRange();
12003 }
12004 return;
12005 }
12006
12007 QualType RequiredType = TypeInfo.Type;
12008 if (IsPointerAttr)
12009 RequiredType = Context.getPointerType(RequiredType);
12010
12011 bool mismatch = false;
12012 if (!TypeInfo.LayoutCompatible) {
12013 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12014
12015 // C++11 [basic.fundamental] p1:
12016 // Plain char, signed char, and unsigned char are three distinct types.
12017 //
12018 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12019 // char' depending on the current char signedness mode.
12020 if (mismatch)
12021 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12022 RequiredType->getPointeeType())) ||
12023 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12024 mismatch = false;
12025 } else
12026 if (IsPointerAttr)
12027 mismatch = !isLayoutCompatible(Context,
12028 ArgumentType->getPointeeType(),
12029 RequiredType->getPointeeType());
12030 else
12031 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12032
12033 if (mismatch)
12034 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012035 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012036 << TypeInfo.LayoutCompatible << RequiredType
12037 << ArgumentExpr->getSourceRange()
12038 << TypeTagExpr->getSourceRange();
12039}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012040
12041void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12042 CharUnits Alignment) {
12043 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12044}
12045
12046void Sema::DiagnoseMisalignedMembers() {
12047 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012048 const NamedDecl *ND = m.RD;
12049 if (ND->getName().empty()) {
12050 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12051 ND = TD;
12052 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012053 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012054 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012055 }
12056 MisalignedMembers.clear();
12057}
12058
12059void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012060 E = E->IgnoreParens();
12061 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012062 return;
12063 if (isa<UnaryOperator>(E) &&
12064 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12065 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12066 if (isa<MemberExpr>(Op)) {
12067 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12068 MisalignedMember(Op));
12069 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012070 (T->isIntegerType() ||
12071 (T->isPointerType() &&
12072 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012073 MisalignedMembers.erase(MA);
12074 }
12075 }
12076}
12077
12078void Sema::RefersToMemberWithReducedAlignment(
12079 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012080 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12081 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012082 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012083 if (!ME)
12084 return;
12085
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012086 // No need to check expressions with an __unaligned-qualified type.
12087 if (E->getType().getQualifiers().hasUnaligned())
12088 return;
12089
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012090 // For a chain of MemberExpr like "a.b.c.d" this list
12091 // will keep FieldDecl's like [d, c, b].
12092 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12093 const MemberExpr *TopME = nullptr;
12094 bool AnyIsPacked = false;
12095 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012096 QualType BaseType = ME->getBase()->getType();
12097 if (ME->isArrow())
12098 BaseType = BaseType->getPointeeType();
12099 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012100 if (RD->isInvalidDecl())
12101 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012102
12103 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012104 auto *FD = dyn_cast<FieldDecl>(MD);
12105 // We do not care about non-data members.
12106 if (!FD || FD->isInvalidDecl())
12107 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012108
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012109 AnyIsPacked =
12110 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12111 ReverseMemberChain.push_back(FD);
12112
12113 TopME = ME;
12114 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12115 } while (ME);
12116 assert(TopME && "We did not compute a topmost MemberExpr!");
12117
12118 // Not the scope of this diagnostic.
12119 if (!AnyIsPacked)
12120 return;
12121
12122 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12123 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12124 // TODO: The innermost base of the member expression may be too complicated.
12125 // For now, just disregard these cases. This is left for future
12126 // improvement.
12127 if (!DRE && !isa<CXXThisExpr>(TopBase))
12128 return;
12129
12130 // Alignment expected by the whole expression.
12131 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12132
12133 // No need to do anything else with this case.
12134 if (ExpectedAlignment.isOne())
12135 return;
12136
12137 // Synthesize offset of the whole access.
12138 CharUnits Offset;
12139 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12140 I++) {
12141 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12142 }
12143
12144 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12145 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12146 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12147
12148 // The base expression of the innermost MemberExpr may give
12149 // stronger guarantees than the class containing the member.
12150 if (DRE && !TopME->isArrow()) {
12151 const ValueDecl *VD = DRE->getDecl();
12152 if (!VD->getType()->isReferenceType())
12153 CompleteObjectAlignment =
12154 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12155 }
12156
12157 // Check if the synthesized offset fulfills the alignment.
12158 if (Offset % ExpectedAlignment != 0 ||
12159 // It may fulfill the offset it but the effective alignment may still be
12160 // lower than the expected expression alignment.
12161 CompleteObjectAlignment < ExpectedAlignment) {
12162 // If this happens, we want to determine a sensible culprit of this.
12163 // Intuitively, watching the chain of member expressions from right to
12164 // left, we start with the required alignment (as required by the field
12165 // type) but some packed attribute in that chain has reduced the alignment.
12166 // It may happen that another packed structure increases it again. But if
12167 // we are here such increase has not been enough. So pointing the first
12168 // FieldDecl that either is packed or else its RecordDecl is,
12169 // seems reasonable.
12170 FieldDecl *FD = nullptr;
12171 CharUnits Alignment;
12172 for (FieldDecl *FDI : ReverseMemberChain) {
12173 if (FDI->hasAttr<PackedAttr>() ||
12174 FDI->getParent()->hasAttr<PackedAttr>()) {
12175 FD = FDI;
12176 Alignment = std::min(
12177 Context.getTypeAlignInChars(FD->getType()),
12178 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12179 break;
12180 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012181 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012182 assert(FD && "We did not find a packed FieldDecl!");
12183 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012184 }
12185}
12186
12187void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12188 using namespace std::placeholders;
12189 RefersToMemberWithReducedAlignment(
12190 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12191 _2, _3, _4));
12192}
12193