blob: 79263f1e3ac1b2dc47467e74e26801366218e6e2 [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"
Yaxun Liu39195062017-08-04 18:16:31 +000028#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000036#include "clang/Sema/SemaInternal.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000038#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/ADT/SmallString.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000040#include "llvm/Support/ConvertUTF.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000041#include "llvm/Support/Format.h"
42#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1ced5092016-02-12 22:53:10 +000044
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000050 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000052}
53
John McCallbebede42011-02-26 05:39:39 +000054/// Checks that a call expression's argument count is the desired number.
55/// This is useful when doing custom type-checking. Returns true on error.
56static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57 unsigned argCount = call->getNumArgs();
58 if (argCount == desiredArgCount) return false;
59
60 if (argCount < desiredArgCount)
61 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62 << 0 /*function call*/ << desiredArgCount << argCount
63 << call->getSourceRange();
64
65 // Highlight all the excess arguments.
66 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67 call->getArg(argCount - 1)->getLocEnd());
68
69 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70 << 0 /*function call*/ << desiredArgCount << argCount
71 << call->getArg(1)->getSourceRange();
72}
73
Julien Lerouge4a5b4442012-04-28 17:39:16 +000074/// Check that the first argument to __builtin_annotation is an integer
75/// and the second argument is a non-wide string literal.
76static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77 if (checkArgCount(S, TheCall, 2))
78 return true;
79
80 // First argument should be an integer.
81 Expr *ValArg = TheCall->getArg(0);
82 QualType Ty = ValArg->getType();
83 if (!Ty->isIntegerType()) {
84 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000086 return true;
87 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000088
89 // Second argument should be a constant string.
90 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92 if (!Literal || !Literal->isAscii()) {
93 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94 << StrArg->getSourceRange();
95 return true;
96 }
97
98 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000099 return false;
100}
101
Reid Kleckner30701ed2017-09-05 20:27:35 +0000102static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
103 // We need at least one argument.
104 if (TheCall->getNumArgs() < 1) {
105 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
106 << 0 << 1 << TheCall->getNumArgs()
107 << TheCall->getCallee()->getSourceRange();
108 return true;
109 }
110
111 // All arguments should be wide string literals.
112 for (Expr *Arg : TheCall->arguments()) {
113 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
114 if (!Literal || !Literal->isWide()) {
115 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
116 << Arg->getSourceRange();
117 return true;
118 }
119 }
120
121 return false;
122}
123
Richard Smith6cbd65d2013-07-11 02:27:57 +0000124/// Check that the argument to __builtin_addressof is a glvalue, and set the
125/// result type to the corresponding pointer type.
126static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
127 if (checkArgCount(S, TheCall, 1))
128 return true;
129
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000130 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000131 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
132 if (ResultType.isNull())
133 return true;
134
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000135 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000136 TheCall->setType(ResultType);
137 return false;
138}
139
John McCall03107a42015-10-29 20:48:01 +0000140static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
141 if (checkArgCount(S, TheCall, 3))
142 return true;
143
144 // First two arguments should be integers.
145 for (unsigned I = 0; I < 2; ++I) {
146 Expr *Arg = TheCall->getArg(I);
147 QualType Ty = Arg->getType();
148 if (!Ty->isIntegerType()) {
149 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
150 << Ty << Arg->getSourceRange();
151 return true;
152 }
153 }
154
155 // Third argument should be a pointer to a non-const integer.
156 // IRGen correctly handles volatile, restrict, and address spaces, and
157 // the other qualifiers aren't possible.
158 {
159 Expr *Arg = TheCall->getArg(2);
160 QualType Ty = Arg->getType();
161 const auto *PtrTy = Ty->getAs<PointerType>();
162 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
163 !PtrTy->getPointeeType().isConstQualified())) {
164 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
165 << Ty << Arg->getSourceRange();
166 return true;
167 }
168 }
169
170 return false;
171}
172
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000173static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
174 CallExpr *TheCall, unsigned SizeIdx,
175 unsigned DstSizeIdx) {
176 if (TheCall->getNumArgs() <= SizeIdx ||
177 TheCall->getNumArgs() <= DstSizeIdx)
178 return;
179
180 const Expr *SizeArg = TheCall->getArg(SizeIdx);
181 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
182
183 llvm::APSInt Size, DstSize;
184
185 // find out if both sizes are known at compile time
186 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
187 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
188 return;
189
190 if (Size.ule(DstSize))
191 return;
192
193 // confirmed overflow so generate the diagnostic.
194 IdentifierInfo *FnName = FDecl->getIdentifier();
195 SourceLocation SL = TheCall->getLocStart();
196 SourceRange SR = TheCall->getSourceRange();
197
198 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
199}
200
Peter Collingbournef7706832014-12-12 23:41:25 +0000201static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
202 if (checkArgCount(S, BuiltinCall, 2))
203 return true;
204
205 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
206 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
207 Expr *Call = BuiltinCall->getArg(0);
208 Expr *Chain = BuiltinCall->getArg(1);
209
210 if (Call->getStmtClass() != Stmt::CallExprClass) {
211 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
212 << Call->getSourceRange();
213 return true;
214 }
215
216 auto CE = cast<CallExpr>(Call);
217 if (CE->getCallee()->getType()->isBlockPointerType()) {
218 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
219 << Call->getSourceRange();
220 return true;
221 }
222
223 const Decl *TargetDecl = CE->getCalleeDecl();
224 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
225 if (FD->getBuiltinID()) {
226 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
227 << Call->getSourceRange();
228 return true;
229 }
230
231 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
232 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
233 << Call->getSourceRange();
234 return true;
235 }
236
237 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
238 if (ChainResult.isInvalid())
239 return true;
240 if (!ChainResult.get()->getType()->isPointerType()) {
241 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
242 << Chain->getSourceRange();
243 return true;
244 }
245
David Majnemerced8bdf2015-02-25 17:36:15 +0000246 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000247 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
248 QualType BuiltinTy = S.Context.getFunctionType(
249 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
250 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
251
252 Builtin =
253 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
254
255 BuiltinCall->setType(CE->getType());
256 BuiltinCall->setValueKind(CE->getValueKind());
257 BuiltinCall->setObjectKind(CE->getObjectKind());
258 BuiltinCall->setCallee(Builtin);
259 BuiltinCall->setArg(1, ChainResult.get());
260
261 return false;
262}
263
Reid Kleckner1d59f992015-01-22 01:36:17 +0000264static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
265 Scope::ScopeFlags NeededScopeFlags,
266 unsigned DiagID) {
267 // Scopes aren't available during instantiation. Fortunately, builtin
268 // functions cannot be template args so they cannot be formed through template
269 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000270 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000271 return false;
272
273 Scope *S = SemaRef.getCurScope();
274 while (S && !S->isSEHExceptScope())
275 S = S->getParent();
276 if (!S || !(S->getFlags() & NeededScopeFlags)) {
277 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
278 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
279 << DRE->getDecl()->getIdentifier();
280 return true;
281 }
282
283 return false;
284}
285
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000286static inline bool isBlockPointer(Expr *Arg) {
287 return Arg->getType()->isBlockPointerType();
288}
289
290/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
291/// void*, which is a requirement of device side enqueue.
292static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
293 const BlockPointerType *BPT =
294 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
295 ArrayRef<QualType> Params =
296 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
297 unsigned ArgCounter = 0;
298 bool IllegalParams = false;
299 // Iterate through the block parameters until either one is found that is not
300 // a local void*, or the block is valid.
301 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
302 I != E; ++I, ++ArgCounter) {
303 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
304 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
305 LangAS::opencl_local) {
306 // Get the location of the error. If a block literal has been passed
307 // (BlockExpr) then we can point straight to the offending argument,
308 // else we just point to the variable reference.
309 SourceLocation ErrorLoc;
310 if (isa<BlockExpr>(BlockArg)) {
311 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
312 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
313 } else if (isa<DeclRefExpr>(BlockArg)) {
314 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
315 }
316 S.Diag(ErrorLoc,
317 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
318 IllegalParams = true;
319 }
320 }
321
322 return IllegalParams;
323}
324
Joey Gouly84ae3362017-07-31 15:15:59 +0000325static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
326 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
327 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
328 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
329 return true;
330 }
331 return false;
332}
333
Joey Goulyfa76b492017-08-01 13:27:09 +0000334static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
335 if (checkArgCount(S, TheCall, 2))
336 return true;
337
338 if (checkOpenCLSubgroupExt(S, TheCall))
339 return true;
340
341 // First argument is an ndrange_t type.
342 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000343 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000344 S.Diag(NDRangeArg->getLocStart(),
345 diag::err_opencl_builtin_expected_type)
346 << TheCall->getDirectCallee() << "'ndrange_t'";
347 return true;
348 }
349
350 Expr *BlockArg = TheCall->getArg(1);
351 if (!isBlockPointer(BlockArg)) {
352 S.Diag(BlockArg->getLocStart(),
353 diag::err_opencl_builtin_expected_type)
354 << TheCall->getDirectCallee() << "block";
355 return true;
356 }
357 return checkOpenCLBlockArgs(S, BlockArg);
358}
359
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000360/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
361/// get_kernel_work_group_size
362/// and get_kernel_preferred_work_group_size_multiple builtin functions.
363static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
364 if (checkArgCount(S, TheCall, 1))
365 return true;
366
367 Expr *BlockArg = TheCall->getArg(0);
368 if (!isBlockPointer(BlockArg)) {
369 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000370 diag::err_opencl_builtin_expected_type)
371 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000372 return true;
373 }
374 return checkOpenCLBlockArgs(S, BlockArg);
375}
376
Simon Pilgrim2c518802017-03-30 14:13:19 +0000377/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000378static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379 const QualType &IntType);
380
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000381static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000382 unsigned Start, unsigned End) {
383 bool IllegalParams = false;
384 for (unsigned I = Start; I <= End; ++I)
385 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
386 S.Context.getSizeType());
387 return IllegalParams;
388}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000389
390/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
391/// 'local void*' parameter of passed block.
392static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
393 Expr *BlockArg,
394 unsigned NumNonVarArgs) {
395 const BlockPointerType *BPT =
396 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
397 unsigned NumBlockParams =
398 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
399 unsigned TotalNumArgs = TheCall->getNumArgs();
400
401 // For each argument passed to the block, a corresponding uint needs to
402 // be passed to describe the size of the local memory.
403 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
404 S.Diag(TheCall->getLocStart(),
405 diag::err_opencl_enqueue_kernel_local_size_args);
406 return true;
407 }
408
409 // Check that the sizes of the local memory are specified by integers.
410 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
411 TotalNumArgs - 1);
412}
413
414/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
415/// overload formats specified in Table 6.13.17.1.
416/// int enqueue_kernel(queue_t queue,
417/// kernel_enqueue_flags_t flags,
418/// const ndrange_t ndrange,
419/// void (^block)(void))
420/// int enqueue_kernel(queue_t queue,
421/// kernel_enqueue_flags_t flags,
422/// const ndrange_t ndrange,
423/// uint num_events_in_wait_list,
424/// clk_event_t *event_wait_list,
425/// clk_event_t *event_ret,
426/// void (^block)(void))
427/// int enqueue_kernel(queue_t queue,
428/// kernel_enqueue_flags_t flags,
429/// const ndrange_t ndrange,
430/// void (^block)(local void*, ...),
431/// uint size0, ...)
432/// int enqueue_kernel(queue_t queue,
433/// kernel_enqueue_flags_t flags,
434/// const ndrange_t ndrange,
435/// uint num_events_in_wait_list,
436/// clk_event_t *event_wait_list,
437/// clk_event_t *event_ret,
438/// void (^block)(local void*, ...),
439/// uint size0, ...)
440static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
441 unsigned NumArgs = TheCall->getNumArgs();
442
443 if (NumArgs < 4) {
444 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
445 return true;
446 }
447
448 Expr *Arg0 = TheCall->getArg(0);
449 Expr *Arg1 = TheCall->getArg(1);
450 Expr *Arg2 = TheCall->getArg(2);
451 Expr *Arg3 = TheCall->getArg(3);
452
453 // First argument always needs to be a queue_t type.
454 if (!Arg0->getType()->isQueueT()) {
455 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000456 diag::err_opencl_builtin_expected_type)
457 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000458 return true;
459 }
460
461 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
462 if (!Arg1->getType()->isIntegerType()) {
463 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000464 diag::err_opencl_builtin_expected_type)
465 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000466 return true;
467 }
468
469 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000470 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000471 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000472 diag::err_opencl_builtin_expected_type)
473 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000474 return true;
475 }
476
477 // With four arguments, there is only one form that the function could be
478 // called in: no events and no variable arguments.
479 if (NumArgs == 4) {
480 // check that the last argument is the right block type.
481 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000482 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
483 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000484 return true;
485 }
486 // we have a block type, check the prototype
487 const BlockPointerType *BPT =
488 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
489 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
490 S.Diag(Arg3->getLocStart(),
491 diag::err_opencl_enqueue_kernel_blocks_no_args);
492 return true;
493 }
494 return false;
495 }
496 // we can have block + varargs.
497 if (isBlockPointer(Arg3))
498 return (checkOpenCLBlockArgs(S, Arg3) ||
499 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
500 // last two cases with either exactly 7 args or 7 args and varargs.
501 if (NumArgs >= 7) {
502 // check common block argument.
503 Expr *Arg6 = TheCall->getArg(6);
504 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000505 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
506 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000507 return true;
508 }
509 if (checkOpenCLBlockArgs(S, Arg6))
510 return true;
511
512 // Forth argument has to be any integer type.
513 if (!Arg3->getType()->isIntegerType()) {
514 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000515 diag::err_opencl_builtin_expected_type)
516 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000517 return true;
518 }
519 // check remaining common arguments.
520 Expr *Arg4 = TheCall->getArg(4);
521 Expr *Arg5 = TheCall->getArg(5);
522
Anastasia Stulova2b461202016-11-14 15:34:01 +0000523 // Fifth argument is always passed as a pointer to clk_event_t.
524 if (!Arg4->isNullPointerConstant(S.Context,
525 Expr::NPC_ValueDependentIsNotNull) &&
526 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000528 diag::err_opencl_builtin_expected_type)
529 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000530 << S.Context.getPointerType(S.Context.OCLClkEventTy);
531 return true;
532 }
533
Anastasia Stulova2b461202016-11-14 15:34:01 +0000534 // Sixth argument is always passed as a pointer to clk_event_t.
535 if (!Arg5->isNullPointerConstant(S.Context,
536 Expr::NPC_ValueDependentIsNotNull) &&
537 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000538 Arg5->getType()->getPointeeType()->isClkEventT())) {
539 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000540 diag::err_opencl_builtin_expected_type)
541 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000542 << S.Context.getPointerType(S.Context.OCLClkEventTy);
543 return true;
544 }
545
546 if (NumArgs == 7)
547 return false;
548
549 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
550 }
551
552 // None of the specific case has been detected, give generic error
553 S.Diag(TheCall->getLocStart(),
554 diag::err_opencl_enqueue_kernel_incorrect_args);
555 return true;
556}
557
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000558/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000559static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000560 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000561}
562
563/// Returns true if pipe element type is different from the pointer.
564static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
565 const Expr *Arg0 = Call->getArg(0);
566 // First argument type should always be pipe.
567 if (!Arg0->getType()->isPipeType()) {
568 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000569 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000570 return true;
571 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000572 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000573 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
574 // Validates the access qualifier is compatible with the call.
575 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
576 // read_only and write_only, and assumed to be read_only if no qualifier is
577 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000578 switch (Call->getDirectCallee()->getBuiltinID()) {
579 case Builtin::BIread_pipe:
580 case Builtin::BIreserve_read_pipe:
581 case Builtin::BIcommit_read_pipe:
582 case Builtin::BIwork_group_reserve_read_pipe:
583 case Builtin::BIsub_group_reserve_read_pipe:
584 case Builtin::BIwork_group_commit_read_pipe:
585 case Builtin::BIsub_group_commit_read_pipe:
586 if (!(!AccessQual || AccessQual->isReadOnly())) {
587 S.Diag(Arg0->getLocStart(),
588 diag::err_opencl_builtin_pipe_invalid_access_modifier)
589 << "read_only" << Arg0->getSourceRange();
590 return true;
591 }
592 break;
593 case Builtin::BIwrite_pipe:
594 case Builtin::BIreserve_write_pipe:
595 case Builtin::BIcommit_write_pipe:
596 case Builtin::BIwork_group_reserve_write_pipe:
597 case Builtin::BIsub_group_reserve_write_pipe:
598 case Builtin::BIwork_group_commit_write_pipe:
599 case Builtin::BIsub_group_commit_write_pipe:
600 if (!(AccessQual && AccessQual->isWriteOnly())) {
601 S.Diag(Arg0->getLocStart(),
602 diag::err_opencl_builtin_pipe_invalid_access_modifier)
603 << "write_only" << Arg0->getSourceRange();
604 return true;
605 }
606 break;
607 default:
608 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000609 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000610 return false;
611}
612
613/// Returns true if pipe element type is different from the pointer.
614static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
615 const Expr *Arg0 = Call->getArg(0);
616 const Expr *ArgIdx = Call->getArg(Idx);
617 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000618 const QualType EltTy = PipeTy->getElementType();
619 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000620 // The Idx argument should be a pointer and the type of the pointer and
621 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000622 if (!ArgTy ||
623 !S.Context.hasSameType(
624 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000625 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000626 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000627 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000628 return true;
629 }
630 return false;
631}
632
633// \brief Performs semantic analysis for the read/write_pipe call.
634// \param S Reference to the semantic analyzer.
635// \param Call A pointer to the builtin call.
636// \return True if a semantic error has been found, false otherwise.
637static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000638 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
639 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000640 switch (Call->getNumArgs()) {
641 case 2: {
642 if (checkOpenCLPipeArg(S, Call))
643 return true;
644 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000645 // read/write_pipe(pipe T, T*).
646 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000647 if (checkOpenCLPipePacketType(S, Call, 1))
648 return true;
649 } break;
650
651 case 4: {
652 if (checkOpenCLPipeArg(S, Call))
653 return true;
654 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000655 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
656 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000657 if (!Call->getArg(1)->getType()->isReserveIDT()) {
658 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000659 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000660 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000661 return true;
662 }
663
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000664 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000665 const Expr *Arg2 = Call->getArg(2);
666 if (!Arg2->getType()->isIntegerType() &&
667 !Arg2->getType()->isUnsignedIntegerType()) {
668 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000669 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000670 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000671 return true;
672 }
673
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000674 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 if (checkOpenCLPipePacketType(S, Call, 3))
676 return true;
677 } break;
678 default:
679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000680 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683
684 return false;
685}
686
687// \brief Performs a semantic analysis on the {work_group_/sub_group_
688// /_}reserve_{read/write}_pipe
689// \param S Reference to the semantic analyzer.
690// \param Call The call to the builtin function to be analyzed.
691// \return True if a semantic error was found, false otherwise.
692static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
693 if (checkArgCount(S, Call, 2))
694 return true;
695
696 if (checkOpenCLPipeArg(S, Call))
697 return true;
698
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (!Call->getArg(1)->getType()->isIntegerType() &&
701 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
702 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000703 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000704 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000705 return true;
706 }
707
Joey Gouly922ca232017-08-09 14:52:47 +0000708 // Since return type of reserve_read/write_pipe built-in function is
709 // reserve_id_t, which is not defined in the builtin def file , we used int
710 // as return type and need to override the return type of these functions.
711 Call->setType(S.Context.OCLReserveIDTy);
712
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 return false;
714}
715
716// \brief Performs a semantic analysis on {work_group_/sub_group_
717// /_}commit_{read/write}_pipe
718// \param S Reference to the semantic analyzer.
719// \param Call The call to the builtin function to be analyzed.
720// \return True if a semantic error was found, false otherwise.
721static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
722 if (checkArgCount(S, Call, 2))
723 return true;
724
725 if (checkOpenCLPipeArg(S, Call))
726 return true;
727
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000729 if (!Call->getArg(1)->getType()->isReserveIDT()) {
730 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000731 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000732 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000733 return true;
734 }
735
736 return false;
737}
738
739// \brief Performs a semantic analysis on the call to built-in Pipe
740// Query Functions.
741// \param S Reference to the semantic analyzer.
742// \param Call The call to the builtin function to be analyzed.
743// \return True if a semantic error was found, false otherwise.
744static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
745 if (checkArgCount(S, Call, 1))
746 return true;
747
748 if (!Call->getArg(0)->getType()->isPipeType()) {
749 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000750 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000751 return true;
752 }
753
754 return false;
755}
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000756// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000757// \brief Performs semantic analysis for the to_global/local/private call.
758// \param S Reference to the semantic analyzer.
759// \param BuiltinID ID of the builtin function.
760// \param Call A pointer to the builtin call.
761// \return True if a semantic error has been found, false otherwise.
762static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
763 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000764 if (Call->getNumArgs() != 1) {
765 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
766 << Call->getDirectCallee() << Call->getSourceRange();
767 return true;
768 }
769
770 auto RT = Call->getArg(0)->getType();
771 if (!RT->isPointerType() || RT->getPointeeType()
772 .getAddressSpace() == LangAS::opencl_constant) {
773 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
774 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
775 return true;
776 }
777
778 RT = RT->getPointeeType();
779 auto Qual = RT.getQualifiers();
780 switch (BuiltinID) {
781 case Builtin::BIto_global:
782 Qual.setAddressSpace(LangAS::opencl_global);
783 break;
784 case Builtin::BIto_local:
785 Qual.setAddressSpace(LangAS::opencl_local);
786 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000787 case Builtin::BIto_private:
788 Qual.setAddressSpace(LangAS::opencl_private);
789 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000790 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000791 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000792 }
793 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
794 RT.getUnqualifiedType(), Qual)));
795
796 return false;
797}
798
John McCalldadc5752010-08-24 06:29:42 +0000799ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000800Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
801 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000802 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000803
Chris Lattner3be167f2010-10-01 23:23:24 +0000804 // Find out if any arguments are required to be integer constant expressions.
805 unsigned ICEArguments = 0;
806 ASTContext::GetBuiltinTypeError Error;
807 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
808 if (Error != ASTContext::GE_None)
809 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
810
811 // If any arguments are required to be ICE's, check and diagnose.
812 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
813 // Skip arguments not required to be ICE's.
814 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
815
816 llvm::APSInt Result;
817 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
818 return true;
819 ICEArguments &= ~(1 << ArgNo);
820 }
821
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000822 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000823 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000824 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000825 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000826 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000827 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000829 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000830 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000831 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000832 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000833 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000834 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000835 case Builtin::BI__va_start: {
836 switch (Context.getTargetInfo().getTriple().getArch()) {
837 case llvm::Triple::arm:
838 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000839 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000840 return ExprError();
841 break;
842 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000843 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000844 return ExprError();
845 break;
846 }
847 break;
848 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000849 case Builtin::BI__builtin_isgreater:
850 case Builtin::BI__builtin_isgreaterequal:
851 case Builtin::BI__builtin_isless:
852 case Builtin::BI__builtin_islessequal:
853 case Builtin::BI__builtin_islessgreater:
854 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000855 if (SemaBuiltinUnorderedCompare(TheCall))
856 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000857 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000858 case Builtin::BI__builtin_fpclassify:
859 if (SemaBuiltinFPClassification(TheCall, 6))
860 return ExprError();
861 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000862 case Builtin::BI__builtin_isfinite:
863 case Builtin::BI__builtin_isinf:
864 case Builtin::BI__builtin_isinf_sign:
865 case Builtin::BI__builtin_isnan:
866 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000867 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000868 return ExprError();
869 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000870 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000871 return SemaBuiltinShuffleVector(TheCall);
872 // TheCall will be freed by the smart pointer here, but that's fine, since
873 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000874 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000875 if (SemaBuiltinPrefetch(TheCall))
876 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000877 break;
David Majnemer51169932016-10-31 05:37:48 +0000878 case Builtin::BI__builtin_alloca_with_align:
879 if (SemaBuiltinAllocaWithAlign(TheCall))
880 return ExprError();
881 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000882 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000883 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000884 if (SemaBuiltinAssume(TheCall))
885 return ExprError();
886 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000887 case Builtin::BI__builtin_assume_aligned:
888 if (SemaBuiltinAssumeAligned(TheCall))
889 return ExprError();
890 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000891 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000892 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000893 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000894 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000895 case Builtin::BI__builtin_longjmp:
896 if (SemaBuiltinLongjmp(TheCall))
897 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000898 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000899 case Builtin::BI__builtin_setjmp:
900 if (SemaBuiltinSetjmp(TheCall))
901 return ExprError();
902 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000903 case Builtin::BI_setjmp:
904 case Builtin::BI_setjmpex:
905 if (checkArgCount(*this, TheCall, 1))
906 return true;
907 break;
John McCallbebede42011-02-26 05:39:39 +0000908
909 case Builtin::BI__builtin_classify_type:
910 if (checkArgCount(*this, TheCall, 1)) return true;
911 TheCall->setType(Context.IntTy);
912 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000913 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000914 if (checkArgCount(*this, TheCall, 1)) return true;
915 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000916 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000917 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000918 case Builtin::BI__sync_fetch_and_add_1:
919 case Builtin::BI__sync_fetch_and_add_2:
920 case Builtin::BI__sync_fetch_and_add_4:
921 case Builtin::BI__sync_fetch_and_add_8:
922 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000923 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000924 case Builtin::BI__sync_fetch_and_sub_1:
925 case Builtin::BI__sync_fetch_and_sub_2:
926 case Builtin::BI__sync_fetch_and_sub_4:
927 case Builtin::BI__sync_fetch_and_sub_8:
928 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000929 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000930 case Builtin::BI__sync_fetch_and_or_1:
931 case Builtin::BI__sync_fetch_and_or_2:
932 case Builtin::BI__sync_fetch_and_or_4:
933 case Builtin::BI__sync_fetch_and_or_8:
934 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000935 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000936 case Builtin::BI__sync_fetch_and_and_1:
937 case Builtin::BI__sync_fetch_and_and_2:
938 case Builtin::BI__sync_fetch_and_and_4:
939 case Builtin::BI__sync_fetch_and_and_8:
940 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000941 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000942 case Builtin::BI__sync_fetch_and_xor_1:
943 case Builtin::BI__sync_fetch_and_xor_2:
944 case Builtin::BI__sync_fetch_and_xor_4:
945 case Builtin::BI__sync_fetch_and_xor_8:
946 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000947 case Builtin::BI__sync_fetch_and_nand:
948 case Builtin::BI__sync_fetch_and_nand_1:
949 case Builtin::BI__sync_fetch_and_nand_2:
950 case Builtin::BI__sync_fetch_and_nand_4:
951 case Builtin::BI__sync_fetch_and_nand_8:
952 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000953 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000954 case Builtin::BI__sync_add_and_fetch_1:
955 case Builtin::BI__sync_add_and_fetch_2:
956 case Builtin::BI__sync_add_and_fetch_4:
957 case Builtin::BI__sync_add_and_fetch_8:
958 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000959 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000960 case Builtin::BI__sync_sub_and_fetch_1:
961 case Builtin::BI__sync_sub_and_fetch_2:
962 case Builtin::BI__sync_sub_and_fetch_4:
963 case Builtin::BI__sync_sub_and_fetch_8:
964 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000965 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000966 case Builtin::BI__sync_and_and_fetch_1:
967 case Builtin::BI__sync_and_and_fetch_2:
968 case Builtin::BI__sync_and_and_fetch_4:
969 case Builtin::BI__sync_and_and_fetch_8:
970 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000971 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000972 case Builtin::BI__sync_or_and_fetch_1:
973 case Builtin::BI__sync_or_and_fetch_2:
974 case Builtin::BI__sync_or_and_fetch_4:
975 case Builtin::BI__sync_or_and_fetch_8:
976 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000977 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000978 case Builtin::BI__sync_xor_and_fetch_1:
979 case Builtin::BI__sync_xor_and_fetch_2:
980 case Builtin::BI__sync_xor_and_fetch_4:
981 case Builtin::BI__sync_xor_and_fetch_8:
982 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000983 case Builtin::BI__sync_nand_and_fetch:
984 case Builtin::BI__sync_nand_and_fetch_1:
985 case Builtin::BI__sync_nand_and_fetch_2:
986 case Builtin::BI__sync_nand_and_fetch_4:
987 case Builtin::BI__sync_nand_and_fetch_8:
988 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000989 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000990 case Builtin::BI__sync_val_compare_and_swap_1:
991 case Builtin::BI__sync_val_compare_and_swap_2:
992 case Builtin::BI__sync_val_compare_and_swap_4:
993 case Builtin::BI__sync_val_compare_and_swap_8:
994 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000995 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000996 case Builtin::BI__sync_bool_compare_and_swap_1:
997 case Builtin::BI__sync_bool_compare_and_swap_2:
998 case Builtin::BI__sync_bool_compare_and_swap_4:
999 case Builtin::BI__sync_bool_compare_and_swap_8:
1000 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001001 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001002 case Builtin::BI__sync_lock_test_and_set_1:
1003 case Builtin::BI__sync_lock_test_and_set_2:
1004 case Builtin::BI__sync_lock_test_and_set_4:
1005 case Builtin::BI__sync_lock_test_and_set_8:
1006 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001007 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001008 case Builtin::BI__sync_lock_release_1:
1009 case Builtin::BI__sync_lock_release_2:
1010 case Builtin::BI__sync_lock_release_4:
1011 case Builtin::BI__sync_lock_release_8:
1012 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001013 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001014 case Builtin::BI__sync_swap_1:
1015 case Builtin::BI__sync_swap_2:
1016 case Builtin::BI__sync_swap_4:
1017 case Builtin::BI__sync_swap_8:
1018 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001019 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001020 case Builtin::BI__builtin_nontemporal_load:
1021 case Builtin::BI__builtin_nontemporal_store:
1022 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001023#define BUILTIN(ID, TYPE, ATTRS)
1024#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1025 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001026 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001027#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001028 case Builtin::BI__annotation:
1029 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1030 return ExprError();
1031 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001032 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001033 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001034 return ExprError();
1035 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001036 case Builtin::BI__builtin_addressof:
1037 if (SemaBuiltinAddressof(*this, TheCall))
1038 return ExprError();
1039 break;
John McCall03107a42015-10-29 20:48:01 +00001040 case Builtin::BI__builtin_add_overflow:
1041 case Builtin::BI__builtin_sub_overflow:
1042 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001043 if (SemaBuiltinOverflow(*this, TheCall))
1044 return ExprError();
1045 break;
Richard Smith760520b2014-06-03 23:27:44 +00001046 case Builtin::BI__builtin_operator_new:
1047 case Builtin::BI__builtin_operator_delete:
1048 if (!getLangOpts().CPlusPlus) {
1049 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1050 << (BuiltinID == Builtin::BI__builtin_operator_new
1051 ? "__builtin_operator_new"
1052 : "__builtin_operator_delete")
1053 << "C++";
1054 return ExprError();
1055 }
1056 // CodeGen assumes it can find the global new and delete to call,
1057 // so ensure that they are declared.
1058 DeclareGlobalNewDelete();
1059 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001060
1061 // check secure string manipulation functions where overflows
1062 // are detectable at compile time
1063 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001064 case Builtin::BI__builtin___memmove_chk:
1065 case Builtin::BI__builtin___memset_chk:
1066 case Builtin::BI__builtin___strlcat_chk:
1067 case Builtin::BI__builtin___strlcpy_chk:
1068 case Builtin::BI__builtin___strncat_chk:
1069 case Builtin::BI__builtin___strncpy_chk:
1070 case Builtin::BI__builtin___stpncpy_chk:
1071 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1072 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001073 case Builtin::BI__builtin___memccpy_chk:
1074 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1075 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001076 case Builtin::BI__builtin___snprintf_chk:
1077 case Builtin::BI__builtin___vsnprintf_chk:
1078 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1079 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001080 case Builtin::BI__builtin_call_with_static_chain:
1081 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1082 return ExprError();
1083 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001084 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001085 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001086 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1087 diag::err_seh___except_block))
1088 return ExprError();
1089 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001090 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001091 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001092 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1093 diag::err_seh___except_filter))
1094 return ExprError();
1095 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001096 case Builtin::BI__GetExceptionInfo:
1097 if (checkArgCount(*this, TheCall, 1))
1098 return ExprError();
1099
1100 if (CheckCXXThrowOperand(
1101 TheCall->getLocStart(),
1102 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1103 TheCall))
1104 return ExprError();
1105
1106 TheCall->setType(Context.VoidPtrTy);
1107 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001108 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001109 case Builtin::BIread_pipe:
1110 case Builtin::BIwrite_pipe:
1111 // Since those two functions are declared with var args, we need a semantic
1112 // check for the argument.
1113 if (SemaBuiltinRWPipe(*this, TheCall))
1114 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001115 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001116 break;
1117 case Builtin::BIreserve_read_pipe:
1118 case Builtin::BIreserve_write_pipe:
1119 case Builtin::BIwork_group_reserve_read_pipe:
1120 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001121 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1122 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001123 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001124 case Builtin::BIsub_group_reserve_read_pipe:
1125 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001126 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1127 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001128 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001129 break;
1130 case Builtin::BIcommit_read_pipe:
1131 case Builtin::BIcommit_write_pipe:
1132 case Builtin::BIwork_group_commit_read_pipe:
1133 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001134 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1135 return ExprError();
1136 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001137 case Builtin::BIsub_group_commit_read_pipe:
1138 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001139 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1140 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001141 return ExprError();
1142 break;
1143 case Builtin::BIget_pipe_num_packets:
1144 case Builtin::BIget_pipe_max_packets:
1145 if (SemaBuiltinPipePackets(*this, TheCall))
1146 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001147 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001148 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001149 case Builtin::BIto_global:
1150 case Builtin::BIto_local:
1151 case Builtin::BIto_private:
1152 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1153 return ExprError();
1154 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001155 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1156 case Builtin::BIenqueue_kernel:
1157 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1158 return ExprError();
1159 break;
1160 case Builtin::BIget_kernel_work_group_size:
1161 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1162 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1163 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001164 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001165 break;
1166 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1167 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1168 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1169 return ExprError();
1170 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001171 case Builtin::BI__builtin_os_log_format:
1172 case Builtin::BI__builtin_os_log_format_buffer_size:
1173 if (SemaBuiltinOSLogFormat(TheCall)) {
1174 return ExprError();
1175 }
1176 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001177 }
Richard Smith760520b2014-06-03 23:27:44 +00001178
Nate Begeman4904e322010-06-08 02:47:44 +00001179 // Since the target specific builtins for each arch overlap, only check those
1180 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001181 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001182 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001183 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001184 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001185 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001186 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001187 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1188 return ExprError();
1189 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001190 case llvm::Triple::aarch64:
1191 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001192 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001193 return ExprError();
1194 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001195 case llvm::Triple::mips:
1196 case llvm::Triple::mipsel:
1197 case llvm::Triple::mips64:
1198 case llvm::Triple::mips64el:
1199 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1200 return ExprError();
1201 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001202 case llvm::Triple::systemz:
1203 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1204 return ExprError();
1205 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001206 case llvm::Triple::x86:
1207 case llvm::Triple::x86_64:
1208 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1209 return ExprError();
1210 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001211 case llvm::Triple::ppc:
1212 case llvm::Triple::ppc64:
1213 case llvm::Triple::ppc64le:
1214 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1215 return ExprError();
1216 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001217 default:
1218 break;
1219 }
1220 }
1221
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001222 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001223}
1224
Nate Begeman91e1fea2010-06-14 05:21:25 +00001225// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001226static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001227 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001228 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001229 switch (Type.getEltType()) {
1230 case NeonTypeFlags::Int8:
1231 case NeonTypeFlags::Poly8:
1232 return shift ? 7 : (8 << IsQuad) - 1;
1233 case NeonTypeFlags::Int16:
1234 case NeonTypeFlags::Poly16:
1235 return shift ? 15 : (4 << IsQuad) - 1;
1236 case NeonTypeFlags::Int32:
1237 return shift ? 31 : (2 << IsQuad) - 1;
1238 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001239 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001240 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001241 case NeonTypeFlags::Poly128:
1242 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001243 case NeonTypeFlags::Float16:
1244 assert(!shift && "cannot shift float types!");
1245 return (4 << IsQuad) - 1;
1246 case NeonTypeFlags::Float32:
1247 assert(!shift && "cannot shift float types!");
1248 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001249 case NeonTypeFlags::Float64:
1250 assert(!shift && "cannot shift float types!");
1251 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001252 }
David Blaikie8a40f702012-01-17 06:56:22 +00001253 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001254}
1255
Bob Wilsone4d77232011-11-08 05:04:11 +00001256/// getNeonEltType - Return the QualType corresponding to the elements of
1257/// the vector type specified by the NeonTypeFlags. This is used to check
1258/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001259static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001260 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001261 switch (Flags.getEltType()) {
1262 case NeonTypeFlags::Int8:
1263 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1264 case NeonTypeFlags::Int16:
1265 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1266 case NeonTypeFlags::Int32:
1267 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1268 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001269 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001270 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1271 else
1272 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1273 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001274 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001275 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001276 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001277 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001278 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001279 if (IsInt64Long)
1280 return Context.UnsignedLongTy;
1281 else
1282 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001283 case NeonTypeFlags::Poly128:
1284 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001285 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001286 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001287 case NeonTypeFlags::Float32:
1288 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001289 case NeonTypeFlags::Float64:
1290 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001291 }
David Blaikie8a40f702012-01-17 06:56:22 +00001292 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001293}
1294
Tim Northover12670412014-02-19 10:37:05 +00001295bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001296 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001297 uint64_t mask = 0;
1298 unsigned TV = 0;
1299 int PtrArgNum = -1;
1300 bool HasConstPtr = false;
1301 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001302#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001303#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001304#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001305 }
1306
1307 // For NEON intrinsics which are overloaded on vector element type, validate
1308 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001309 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001310 if (mask) {
1311 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1312 return true;
1313
1314 TV = Result.getLimitedValue(64);
1315 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1316 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001317 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001318 }
1319
1320 if (PtrArgNum >= 0) {
1321 // Check that pointer arguments have the specified type.
1322 Expr *Arg = TheCall->getArg(PtrArgNum);
1323 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1324 Arg = ICE->getSubExpr();
1325 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1326 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001327
Tim Northovera2ee4332014-03-29 15:09:45 +00001328 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001329 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1330 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001331 bool IsInt64Long =
1332 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1333 QualType EltTy =
1334 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001335 if (HasConstPtr)
1336 EltTy = EltTy.withConst();
1337 QualType LHSTy = Context.getPointerType(EltTy);
1338 AssignConvertType ConvTy;
1339 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1340 if (RHS.isInvalid())
1341 return true;
1342 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1343 RHS.get(), AA_Assigning))
1344 return true;
1345 }
1346
1347 // For NEON intrinsics which take an immediate value as part of the
1348 // instruction, range check them here.
1349 unsigned i = 0, l = 0, u = 0;
1350 switch (BuiltinID) {
1351 default:
1352 return false;
Tim Northover12670412014-02-19 10:37:05 +00001353#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001354#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001355#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001356 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001357
Richard Sandiford28940af2014-04-16 08:47:51 +00001358 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001359}
1360
Tim Northovera2ee4332014-03-29 15:09:45 +00001361bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1362 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001363 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001364 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001365 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001366 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001367 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001368 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1369 BuiltinID == AArch64::BI__builtin_arm_strex ||
1370 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001371 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001372 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001373 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1374 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1375 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001376
1377 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1378
1379 // Ensure that we have the proper number of arguments.
1380 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1381 return true;
1382
1383 // Inspect the pointer argument of the atomic builtin. This should always be
1384 // a pointer type, whose element is an integral scalar or pointer type.
1385 // Because it is a pointer type, we don't have to worry about any implicit
1386 // casts here.
1387 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1388 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1389 if (PointerArgRes.isInvalid())
1390 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001391 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001392
1393 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1394 if (!pointerType) {
1395 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1396 << PointerArg->getType() << PointerArg->getSourceRange();
1397 return true;
1398 }
1399
1400 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1401 // task is to insert the appropriate casts into the AST. First work out just
1402 // what the appropriate type is.
1403 QualType ValType = pointerType->getPointeeType();
1404 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1405 if (IsLdrex)
1406 AddrType.addConst();
1407
1408 // Issue a warning if the cast is dodgy.
1409 CastKind CastNeeded = CK_NoOp;
1410 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1411 CastNeeded = CK_BitCast;
1412 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1413 << PointerArg->getType()
1414 << Context.getPointerType(AddrType)
1415 << AA_Passing << PointerArg->getSourceRange();
1416 }
1417
1418 // Finally, do the cast and replace the argument with the corrected version.
1419 AddrType = Context.getPointerType(AddrType);
1420 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1421 if (PointerArgRes.isInvalid())
1422 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001423 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001424
1425 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1426
1427 // In general, we allow ints, floats and pointers to be loaded and stored.
1428 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1429 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1430 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1431 << PointerArg->getType() << PointerArg->getSourceRange();
1432 return true;
1433 }
1434
1435 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001436 if (Context.getTypeSize(ValType) > MaxWidth) {
1437 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001438 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1439 << PointerArg->getType() << PointerArg->getSourceRange();
1440 return true;
1441 }
1442
1443 switch (ValType.getObjCLifetime()) {
1444 case Qualifiers::OCL_None:
1445 case Qualifiers::OCL_ExplicitNone:
1446 // okay
1447 break;
1448
1449 case Qualifiers::OCL_Weak:
1450 case Qualifiers::OCL_Strong:
1451 case Qualifiers::OCL_Autoreleasing:
1452 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1453 << ValType << PointerArg->getSourceRange();
1454 return true;
1455 }
1456
Tim Northover6aacd492013-07-16 09:47:53 +00001457 if (IsLdrex) {
1458 TheCall->setType(ValType);
1459 return false;
1460 }
1461
1462 // Initialize the argument to be stored.
1463 ExprResult ValArg = TheCall->getArg(0);
1464 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1465 Context, ValType, /*consume*/ false);
1466 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1467 if (ValArg.isInvalid())
1468 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001469 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001470
1471 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1472 // but the custom checker bypasses all default analysis.
1473 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001474 return false;
1475}
1476
Nate Begeman4904e322010-06-08 02:47:44 +00001477bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001478 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001479 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1480 BuiltinID == ARM::BI__builtin_arm_strex ||
1481 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001482 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001483 }
1484
Yi Kong26d104a2014-08-13 19:18:14 +00001485 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1486 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1487 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1488 }
1489
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001490 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1491 BuiltinID == ARM::BI__builtin_arm_wsr64)
1492 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1493
1494 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1495 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1496 BuiltinID == ARM::BI__builtin_arm_wsr ||
1497 BuiltinID == ARM::BI__builtin_arm_wsrp)
1498 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1499
Tim Northover12670412014-02-19 10:37:05 +00001500 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1501 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001502
Yi Kong4efadfb2014-07-03 16:01:25 +00001503 // For intrinsics which take an immediate value as part of the instruction,
1504 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001505 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001506 switch (BuiltinID) {
1507 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001508 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1509 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001510 case ARM::BI__builtin_arm_vcvtr_f:
1511 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001512 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001513 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001514 case ARM::BI__builtin_arm_isb:
1515 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001516 }
Nate Begemand773fe62010-06-13 04:47:52 +00001517
Nate Begemanf568b072010-08-03 21:32:34 +00001518 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001519 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001520}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001521
Tim Northover573cbee2014-05-24 12:52:07 +00001522bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001523 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001524 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001525 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1526 BuiltinID == AArch64::BI__builtin_arm_strex ||
1527 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001528 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1529 }
1530
Yi Konga5548432014-08-13 19:18:20 +00001531 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1532 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1533 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1534 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1535 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1536 }
1537
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001538 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1539 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001540 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001541
1542 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1543 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1544 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1545 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1546 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1547
Tim Northovera2ee4332014-03-29 15:09:45 +00001548 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1549 return true;
1550
Yi Kong19a29ac2014-07-17 10:52:06 +00001551 // For intrinsics which take an immediate value as part of the instruction,
1552 // range check them here.
1553 unsigned i = 0, l = 0, u = 0;
1554 switch (BuiltinID) {
1555 default: return false;
1556 case AArch64::BI__builtin_arm_dmb:
1557 case AArch64::BI__builtin_arm_dsb:
1558 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1559 }
1560
Yi Kong19a29ac2014-07-17 10:52:06 +00001561 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001562}
1563
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001564// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1565// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1566// ordering for DSP is unspecified. MSA is ordered by the data format used
1567// by the underlying instruction i.e., df/m, df/n and then by size.
1568//
1569// FIXME: The size tests here should instead be tablegen'd along with the
1570// definitions from include/clang/Basic/BuiltinsMips.def.
1571// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1572// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001573bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001574 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001575 switch (BuiltinID) {
1576 default: return false;
1577 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1578 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001579 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1580 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1581 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1582 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1583 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001584 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1585 // df/m field.
1586 // These intrinsics take an unsigned 3 bit immediate.
1587 case Mips::BI__builtin_msa_bclri_b:
1588 case Mips::BI__builtin_msa_bnegi_b:
1589 case Mips::BI__builtin_msa_bseti_b:
1590 case Mips::BI__builtin_msa_sat_s_b:
1591 case Mips::BI__builtin_msa_sat_u_b:
1592 case Mips::BI__builtin_msa_slli_b:
1593 case Mips::BI__builtin_msa_srai_b:
1594 case Mips::BI__builtin_msa_srari_b:
1595 case Mips::BI__builtin_msa_srli_b:
1596 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1597 case Mips::BI__builtin_msa_binsli_b:
1598 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1599 // These intrinsics take an unsigned 4 bit immediate.
1600 case Mips::BI__builtin_msa_bclri_h:
1601 case Mips::BI__builtin_msa_bnegi_h:
1602 case Mips::BI__builtin_msa_bseti_h:
1603 case Mips::BI__builtin_msa_sat_s_h:
1604 case Mips::BI__builtin_msa_sat_u_h:
1605 case Mips::BI__builtin_msa_slli_h:
1606 case Mips::BI__builtin_msa_srai_h:
1607 case Mips::BI__builtin_msa_srari_h:
1608 case Mips::BI__builtin_msa_srli_h:
1609 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1610 case Mips::BI__builtin_msa_binsli_h:
1611 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1612 // These intrinsics take an unsigned 5 bit immedate.
1613 // The first block of intrinsics actually have an unsigned 5 bit field,
1614 // not a df/n field.
1615 case Mips::BI__builtin_msa_clei_u_b:
1616 case Mips::BI__builtin_msa_clei_u_h:
1617 case Mips::BI__builtin_msa_clei_u_w:
1618 case Mips::BI__builtin_msa_clei_u_d:
1619 case Mips::BI__builtin_msa_clti_u_b:
1620 case Mips::BI__builtin_msa_clti_u_h:
1621 case Mips::BI__builtin_msa_clti_u_w:
1622 case Mips::BI__builtin_msa_clti_u_d:
1623 case Mips::BI__builtin_msa_maxi_u_b:
1624 case Mips::BI__builtin_msa_maxi_u_h:
1625 case Mips::BI__builtin_msa_maxi_u_w:
1626 case Mips::BI__builtin_msa_maxi_u_d:
1627 case Mips::BI__builtin_msa_mini_u_b:
1628 case Mips::BI__builtin_msa_mini_u_h:
1629 case Mips::BI__builtin_msa_mini_u_w:
1630 case Mips::BI__builtin_msa_mini_u_d:
1631 case Mips::BI__builtin_msa_addvi_b:
1632 case Mips::BI__builtin_msa_addvi_h:
1633 case Mips::BI__builtin_msa_addvi_w:
1634 case Mips::BI__builtin_msa_addvi_d:
1635 case Mips::BI__builtin_msa_bclri_w:
1636 case Mips::BI__builtin_msa_bnegi_w:
1637 case Mips::BI__builtin_msa_bseti_w:
1638 case Mips::BI__builtin_msa_sat_s_w:
1639 case Mips::BI__builtin_msa_sat_u_w:
1640 case Mips::BI__builtin_msa_slli_w:
1641 case Mips::BI__builtin_msa_srai_w:
1642 case Mips::BI__builtin_msa_srari_w:
1643 case Mips::BI__builtin_msa_srli_w:
1644 case Mips::BI__builtin_msa_srlri_w:
1645 case Mips::BI__builtin_msa_subvi_b:
1646 case Mips::BI__builtin_msa_subvi_h:
1647 case Mips::BI__builtin_msa_subvi_w:
1648 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1649 case Mips::BI__builtin_msa_binsli_w:
1650 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1651 // These intrinsics take an unsigned 6 bit immediate.
1652 case Mips::BI__builtin_msa_bclri_d:
1653 case Mips::BI__builtin_msa_bnegi_d:
1654 case Mips::BI__builtin_msa_bseti_d:
1655 case Mips::BI__builtin_msa_sat_s_d:
1656 case Mips::BI__builtin_msa_sat_u_d:
1657 case Mips::BI__builtin_msa_slli_d:
1658 case Mips::BI__builtin_msa_srai_d:
1659 case Mips::BI__builtin_msa_srari_d:
1660 case Mips::BI__builtin_msa_srli_d:
1661 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1662 case Mips::BI__builtin_msa_binsli_d:
1663 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1664 // These intrinsics take a signed 5 bit immediate.
1665 case Mips::BI__builtin_msa_ceqi_b:
1666 case Mips::BI__builtin_msa_ceqi_h:
1667 case Mips::BI__builtin_msa_ceqi_w:
1668 case Mips::BI__builtin_msa_ceqi_d:
1669 case Mips::BI__builtin_msa_clti_s_b:
1670 case Mips::BI__builtin_msa_clti_s_h:
1671 case Mips::BI__builtin_msa_clti_s_w:
1672 case Mips::BI__builtin_msa_clti_s_d:
1673 case Mips::BI__builtin_msa_clei_s_b:
1674 case Mips::BI__builtin_msa_clei_s_h:
1675 case Mips::BI__builtin_msa_clei_s_w:
1676 case Mips::BI__builtin_msa_clei_s_d:
1677 case Mips::BI__builtin_msa_maxi_s_b:
1678 case Mips::BI__builtin_msa_maxi_s_h:
1679 case Mips::BI__builtin_msa_maxi_s_w:
1680 case Mips::BI__builtin_msa_maxi_s_d:
1681 case Mips::BI__builtin_msa_mini_s_b:
1682 case Mips::BI__builtin_msa_mini_s_h:
1683 case Mips::BI__builtin_msa_mini_s_w:
1684 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1685 // These intrinsics take an unsigned 8 bit immediate.
1686 case Mips::BI__builtin_msa_andi_b:
1687 case Mips::BI__builtin_msa_nori_b:
1688 case Mips::BI__builtin_msa_ori_b:
1689 case Mips::BI__builtin_msa_shf_b:
1690 case Mips::BI__builtin_msa_shf_h:
1691 case Mips::BI__builtin_msa_shf_w:
1692 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1693 case Mips::BI__builtin_msa_bseli_b:
1694 case Mips::BI__builtin_msa_bmnzi_b:
1695 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1696 // df/n format
1697 // These intrinsics take an unsigned 4 bit immediate.
1698 case Mips::BI__builtin_msa_copy_s_b:
1699 case Mips::BI__builtin_msa_copy_u_b:
1700 case Mips::BI__builtin_msa_insve_b:
1701 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001702 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1703 // These intrinsics take an unsigned 3 bit immediate.
1704 case Mips::BI__builtin_msa_copy_s_h:
1705 case Mips::BI__builtin_msa_copy_u_h:
1706 case Mips::BI__builtin_msa_insve_h:
1707 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001708 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1709 // These intrinsics take an unsigned 2 bit immediate.
1710 case Mips::BI__builtin_msa_copy_s_w:
1711 case Mips::BI__builtin_msa_copy_u_w:
1712 case Mips::BI__builtin_msa_insve_w:
1713 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001714 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1715 // These intrinsics take an unsigned 1 bit immediate.
1716 case Mips::BI__builtin_msa_copy_s_d:
1717 case Mips::BI__builtin_msa_copy_u_d:
1718 case Mips::BI__builtin_msa_insve_d:
1719 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001720 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1721 // Memory offsets and immediate loads.
1722 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001723 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001724 case Mips::BI__builtin_msa_ldi_h:
1725 case Mips::BI__builtin_msa_ldi_w:
1726 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1727 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1728 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1729 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1730 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1731 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1732 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1733 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1734 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001735 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001736
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001737 if (!m)
1738 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1739
1740 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1741 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001742}
1743
Kit Bartone50adcb2015-03-30 19:40:59 +00001744bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1745 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001746 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1747 BuiltinID == PPC::BI__builtin_divdeu ||
1748 BuiltinID == PPC::BI__builtin_bpermd;
1749 bool IsTarget64Bit = Context.getTargetInfo()
1750 .getTypeWidth(Context
1751 .getTargetInfo()
1752 .getIntPtrType()) == 64;
1753 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1754 BuiltinID == PPC::BI__builtin_divweu ||
1755 BuiltinID == PPC::BI__builtin_divde ||
1756 BuiltinID == PPC::BI__builtin_divdeu;
1757
1758 if (Is64BitBltin && !IsTarget64Bit)
1759 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1760 << TheCall->getSourceRange();
1761
1762 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1763 (BuiltinID == PPC::BI__builtin_bpermd &&
1764 !Context.getTargetInfo().hasFeature("bpermd")))
1765 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1766 << TheCall->getSourceRange();
1767
Kit Bartone50adcb2015-03-30 19:40:59 +00001768 switch (BuiltinID) {
1769 default: return false;
1770 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1771 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1772 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1773 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1774 case PPC::BI__builtin_tbegin:
1775 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1776 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1777 case PPC::BI__builtin_tabortwc:
1778 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1779 case PPC::BI__builtin_tabortwci:
1780 case PPC::BI__builtin_tabortdci:
1781 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1782 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001783 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001784 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001785 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001786 }
1787 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1788}
1789
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001790bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1791 CallExpr *TheCall) {
1792 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1793 Expr *Arg = TheCall->getArg(0);
1794 llvm::APSInt AbortCode(32);
1795 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1796 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1797 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1798 << Arg->getSourceRange();
1799 }
1800
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001801 // For intrinsics which take an immediate value as part of the instruction,
1802 // range check them here.
1803 unsigned i = 0, l = 0, u = 0;
1804 switch (BuiltinID) {
1805 default: return false;
1806 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1807 case SystemZ::BI__builtin_s390_verimb:
1808 case SystemZ::BI__builtin_s390_verimh:
1809 case SystemZ::BI__builtin_s390_verimf:
1810 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1811 case SystemZ::BI__builtin_s390_vfaeb:
1812 case SystemZ::BI__builtin_s390_vfaeh:
1813 case SystemZ::BI__builtin_s390_vfaef:
1814 case SystemZ::BI__builtin_s390_vfaebs:
1815 case SystemZ::BI__builtin_s390_vfaehs:
1816 case SystemZ::BI__builtin_s390_vfaefs:
1817 case SystemZ::BI__builtin_s390_vfaezb:
1818 case SystemZ::BI__builtin_s390_vfaezh:
1819 case SystemZ::BI__builtin_s390_vfaezf:
1820 case SystemZ::BI__builtin_s390_vfaezbs:
1821 case SystemZ::BI__builtin_s390_vfaezhs:
1822 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001823 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001824 case SystemZ::BI__builtin_s390_vfidb:
1825 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1826 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001827 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001828 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1829 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1830 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1831 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1832 case SystemZ::BI__builtin_s390_vstrcb:
1833 case SystemZ::BI__builtin_s390_vstrch:
1834 case SystemZ::BI__builtin_s390_vstrcf:
1835 case SystemZ::BI__builtin_s390_vstrczb:
1836 case SystemZ::BI__builtin_s390_vstrczh:
1837 case SystemZ::BI__builtin_s390_vstrczf:
1838 case SystemZ::BI__builtin_s390_vstrcbs:
1839 case SystemZ::BI__builtin_s390_vstrchs:
1840 case SystemZ::BI__builtin_s390_vstrcfs:
1841 case SystemZ::BI__builtin_s390_vstrczbs:
1842 case SystemZ::BI__builtin_s390_vstrczhs:
1843 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001844 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1845 case SystemZ::BI__builtin_s390_vfminsb:
1846 case SystemZ::BI__builtin_s390_vfmaxsb:
1847 case SystemZ::BI__builtin_s390_vfmindb:
1848 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001849 }
1850 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001851}
1852
Craig Topper5ba2c502015-11-07 08:08:31 +00001853/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1854/// This checks that the target supports __builtin_cpu_supports and
1855/// that the string argument is constant and valid.
1856static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1857 Expr *Arg = TheCall->getArg(0);
1858
1859 // Check if the argument is a string literal.
1860 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1861 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1862 << Arg->getSourceRange();
1863
1864 // Check the contents of the string.
1865 StringRef Feature =
1866 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1867 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1868 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1869 << Arg->getSourceRange();
1870 return false;
1871}
1872
Craig Topper699ae0c2017-08-10 20:28:30 +00001873/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1874/// This checks that the target supports __builtin_cpu_is and
1875/// that the string argument is constant and valid.
1876static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1877 Expr *Arg = TheCall->getArg(0);
1878
1879 // Check if the argument is a string literal.
1880 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1881 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1882 << Arg->getSourceRange();
1883
1884 // Check the contents of the string.
1885 StringRef Feature =
1886 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1887 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1888 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1889 << Arg->getSourceRange();
1890 return false;
1891}
1892
Craig Toppera7e253e2016-09-23 04:48:31 +00001893// Check if the rounding mode is legal.
1894bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1895 // Indicates if this instruction has rounding control or just SAE.
1896 bool HasRC = false;
1897
1898 unsigned ArgNum = 0;
1899 switch (BuiltinID) {
1900 default:
1901 return false;
1902 case X86::BI__builtin_ia32_vcvttsd2si32:
1903 case X86::BI__builtin_ia32_vcvttsd2si64:
1904 case X86::BI__builtin_ia32_vcvttsd2usi32:
1905 case X86::BI__builtin_ia32_vcvttsd2usi64:
1906 case X86::BI__builtin_ia32_vcvttss2si32:
1907 case X86::BI__builtin_ia32_vcvttss2si64:
1908 case X86::BI__builtin_ia32_vcvttss2usi32:
1909 case X86::BI__builtin_ia32_vcvttss2usi64:
1910 ArgNum = 1;
1911 break;
1912 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1913 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1914 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1915 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1916 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1917 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1918 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1919 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1920 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1921 case X86::BI__builtin_ia32_exp2pd_mask:
1922 case X86::BI__builtin_ia32_exp2ps_mask:
1923 case X86::BI__builtin_ia32_getexppd512_mask:
1924 case X86::BI__builtin_ia32_getexpps512_mask:
1925 case X86::BI__builtin_ia32_rcp28pd_mask:
1926 case X86::BI__builtin_ia32_rcp28ps_mask:
1927 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1928 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1929 case X86::BI__builtin_ia32_vcomisd:
1930 case X86::BI__builtin_ia32_vcomiss:
1931 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1932 ArgNum = 3;
1933 break;
1934 case X86::BI__builtin_ia32_cmppd512_mask:
1935 case X86::BI__builtin_ia32_cmpps512_mask:
1936 case X86::BI__builtin_ia32_cmpsd_mask:
1937 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001938 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001939 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1940 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001941 case X86::BI__builtin_ia32_maxpd512_mask:
1942 case X86::BI__builtin_ia32_maxps512_mask:
1943 case X86::BI__builtin_ia32_maxsd_round_mask:
1944 case X86::BI__builtin_ia32_maxss_round_mask:
1945 case X86::BI__builtin_ia32_minpd512_mask:
1946 case X86::BI__builtin_ia32_minps512_mask:
1947 case X86::BI__builtin_ia32_minsd_round_mask:
1948 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001949 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1950 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1951 case X86::BI__builtin_ia32_reducepd512_mask:
1952 case X86::BI__builtin_ia32_reduceps512_mask:
1953 case X86::BI__builtin_ia32_rndscalepd_mask:
1954 case X86::BI__builtin_ia32_rndscaleps_mask:
1955 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1956 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1957 ArgNum = 4;
1958 break;
1959 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001960 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001961 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001962 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001963 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001964 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001965 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00001966 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00001967 case X86::BI__builtin_ia32_rangepd512_mask:
1968 case X86::BI__builtin_ia32_rangeps512_mask:
1969 case X86::BI__builtin_ia32_rangesd128_round_mask:
1970 case X86::BI__builtin_ia32_rangess128_round_mask:
1971 case X86::BI__builtin_ia32_reducesd_mask:
1972 case X86::BI__builtin_ia32_reducess_mask:
1973 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1974 case X86::BI__builtin_ia32_rndscaless_round_mask:
1975 ArgNum = 5;
1976 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00001977 case X86::BI__builtin_ia32_vcvtsd2si64:
1978 case X86::BI__builtin_ia32_vcvtsd2si32:
1979 case X86::BI__builtin_ia32_vcvtsd2usi32:
1980 case X86::BI__builtin_ia32_vcvtsd2usi64:
1981 case X86::BI__builtin_ia32_vcvtss2si32:
1982 case X86::BI__builtin_ia32_vcvtss2si64:
1983 case X86::BI__builtin_ia32_vcvtss2usi32:
1984 case X86::BI__builtin_ia32_vcvtss2usi64:
1985 ArgNum = 1;
1986 HasRC = true;
1987 break;
Craig Topper8e066312016-11-07 07:01:09 +00001988 case X86::BI__builtin_ia32_cvtsi2sd64:
1989 case X86::BI__builtin_ia32_cvtsi2ss32:
1990 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00001991 case X86::BI__builtin_ia32_cvtusi2sd64:
1992 case X86::BI__builtin_ia32_cvtusi2ss32:
1993 case X86::BI__builtin_ia32_cvtusi2ss64:
1994 ArgNum = 2;
1995 HasRC = true;
1996 break;
1997 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1998 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1999 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2000 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2001 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2002 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2003 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2004 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2005 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2006 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2007 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002008 case X86::BI__builtin_ia32_sqrtpd512_mask:
2009 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002010 ArgNum = 3;
2011 HasRC = true;
2012 break;
2013 case X86::BI__builtin_ia32_addpd512_mask:
2014 case X86::BI__builtin_ia32_addps512_mask:
2015 case X86::BI__builtin_ia32_divpd512_mask:
2016 case X86::BI__builtin_ia32_divps512_mask:
2017 case X86::BI__builtin_ia32_mulpd512_mask:
2018 case X86::BI__builtin_ia32_mulps512_mask:
2019 case X86::BI__builtin_ia32_subpd512_mask:
2020 case X86::BI__builtin_ia32_subps512_mask:
2021 case X86::BI__builtin_ia32_addss_round_mask:
2022 case X86::BI__builtin_ia32_addsd_round_mask:
2023 case X86::BI__builtin_ia32_divss_round_mask:
2024 case X86::BI__builtin_ia32_divsd_round_mask:
2025 case X86::BI__builtin_ia32_mulss_round_mask:
2026 case X86::BI__builtin_ia32_mulsd_round_mask:
2027 case X86::BI__builtin_ia32_subss_round_mask:
2028 case X86::BI__builtin_ia32_subsd_round_mask:
2029 case X86::BI__builtin_ia32_scalefpd512_mask:
2030 case X86::BI__builtin_ia32_scalefps512_mask:
2031 case X86::BI__builtin_ia32_scalefsd_round_mask:
2032 case X86::BI__builtin_ia32_scalefss_round_mask:
2033 case X86::BI__builtin_ia32_getmantpd512_mask:
2034 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002035 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2036 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2037 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002038 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2039 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2040 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2041 case X86::BI__builtin_ia32_vfmaddps512_mask:
2042 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2043 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2044 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2045 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2046 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2047 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2048 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2049 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2050 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2051 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2052 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2053 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2054 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2055 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2056 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2057 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2058 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2059 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2060 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2061 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2062 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2063 case X86::BI__builtin_ia32_vfmaddss3_mask:
2064 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2065 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2066 ArgNum = 4;
2067 HasRC = true;
2068 break;
2069 case X86::BI__builtin_ia32_getmantsd_round_mask:
2070 case X86::BI__builtin_ia32_getmantss_round_mask:
2071 ArgNum = 5;
2072 HasRC = true;
2073 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002074 }
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 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2088 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2089 // combined with ROUND_NO_EXC.
2090 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2091 Result == 8/*ROUND_NO_EXC*/ ||
2092 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2093 return false;
2094
2095 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2096 << Arg->getSourceRange();
2097}
2098
Craig Topperdf5beb22017-03-13 17:16:50 +00002099// Check if the gather/scatter scale is legal.
2100bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2101 CallExpr *TheCall) {
2102 unsigned ArgNum = 0;
2103 switch (BuiltinID) {
2104 default:
2105 return false;
2106 case X86::BI__builtin_ia32_gatherpfdpd:
2107 case X86::BI__builtin_ia32_gatherpfdps:
2108 case X86::BI__builtin_ia32_gatherpfqpd:
2109 case X86::BI__builtin_ia32_gatherpfqps:
2110 case X86::BI__builtin_ia32_scatterpfdpd:
2111 case X86::BI__builtin_ia32_scatterpfdps:
2112 case X86::BI__builtin_ia32_scatterpfqpd:
2113 case X86::BI__builtin_ia32_scatterpfqps:
2114 ArgNum = 3;
2115 break;
2116 case X86::BI__builtin_ia32_gatherd_pd:
2117 case X86::BI__builtin_ia32_gatherd_pd256:
2118 case X86::BI__builtin_ia32_gatherq_pd:
2119 case X86::BI__builtin_ia32_gatherq_pd256:
2120 case X86::BI__builtin_ia32_gatherd_ps:
2121 case X86::BI__builtin_ia32_gatherd_ps256:
2122 case X86::BI__builtin_ia32_gatherq_ps:
2123 case X86::BI__builtin_ia32_gatherq_ps256:
2124 case X86::BI__builtin_ia32_gatherd_q:
2125 case X86::BI__builtin_ia32_gatherd_q256:
2126 case X86::BI__builtin_ia32_gatherq_q:
2127 case X86::BI__builtin_ia32_gatherq_q256:
2128 case X86::BI__builtin_ia32_gatherd_d:
2129 case X86::BI__builtin_ia32_gatherd_d256:
2130 case X86::BI__builtin_ia32_gatherq_d:
2131 case X86::BI__builtin_ia32_gatherq_d256:
2132 case X86::BI__builtin_ia32_gather3div2df:
2133 case X86::BI__builtin_ia32_gather3div2di:
2134 case X86::BI__builtin_ia32_gather3div4df:
2135 case X86::BI__builtin_ia32_gather3div4di:
2136 case X86::BI__builtin_ia32_gather3div4sf:
2137 case X86::BI__builtin_ia32_gather3div4si:
2138 case X86::BI__builtin_ia32_gather3div8sf:
2139 case X86::BI__builtin_ia32_gather3div8si:
2140 case X86::BI__builtin_ia32_gather3siv2df:
2141 case X86::BI__builtin_ia32_gather3siv2di:
2142 case X86::BI__builtin_ia32_gather3siv4df:
2143 case X86::BI__builtin_ia32_gather3siv4di:
2144 case X86::BI__builtin_ia32_gather3siv4sf:
2145 case X86::BI__builtin_ia32_gather3siv4si:
2146 case X86::BI__builtin_ia32_gather3siv8sf:
2147 case X86::BI__builtin_ia32_gather3siv8si:
2148 case X86::BI__builtin_ia32_gathersiv8df:
2149 case X86::BI__builtin_ia32_gathersiv16sf:
2150 case X86::BI__builtin_ia32_gatherdiv8df:
2151 case X86::BI__builtin_ia32_gatherdiv16sf:
2152 case X86::BI__builtin_ia32_gathersiv8di:
2153 case X86::BI__builtin_ia32_gathersiv16si:
2154 case X86::BI__builtin_ia32_gatherdiv8di:
2155 case X86::BI__builtin_ia32_gatherdiv16si:
2156 case X86::BI__builtin_ia32_scatterdiv2df:
2157 case X86::BI__builtin_ia32_scatterdiv2di:
2158 case X86::BI__builtin_ia32_scatterdiv4df:
2159 case X86::BI__builtin_ia32_scatterdiv4di:
2160 case X86::BI__builtin_ia32_scatterdiv4sf:
2161 case X86::BI__builtin_ia32_scatterdiv4si:
2162 case X86::BI__builtin_ia32_scatterdiv8sf:
2163 case X86::BI__builtin_ia32_scatterdiv8si:
2164 case X86::BI__builtin_ia32_scattersiv2df:
2165 case X86::BI__builtin_ia32_scattersiv2di:
2166 case X86::BI__builtin_ia32_scattersiv4df:
2167 case X86::BI__builtin_ia32_scattersiv4di:
2168 case X86::BI__builtin_ia32_scattersiv4sf:
2169 case X86::BI__builtin_ia32_scattersiv4si:
2170 case X86::BI__builtin_ia32_scattersiv8sf:
2171 case X86::BI__builtin_ia32_scattersiv8si:
2172 case X86::BI__builtin_ia32_scattersiv8df:
2173 case X86::BI__builtin_ia32_scattersiv16sf:
2174 case X86::BI__builtin_ia32_scatterdiv8df:
2175 case X86::BI__builtin_ia32_scatterdiv16sf:
2176 case X86::BI__builtin_ia32_scattersiv8di:
2177 case X86::BI__builtin_ia32_scattersiv16si:
2178 case X86::BI__builtin_ia32_scatterdiv8di:
2179 case X86::BI__builtin_ia32_scatterdiv16si:
2180 ArgNum = 4;
2181 break;
2182 }
2183
2184 llvm::APSInt Result;
2185
2186 // We can't check the value of a dependent argument.
2187 Expr *Arg = TheCall->getArg(ArgNum);
2188 if (Arg->isTypeDependent() || Arg->isValueDependent())
2189 return false;
2190
2191 // Check constant-ness first.
2192 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2193 return true;
2194
2195 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2196 return false;
2197
2198 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2199 << Arg->getSourceRange();
2200}
2201
Craig Topperf0ddc892016-09-23 04:48:27 +00002202bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2203 if (BuiltinID == X86::BI__builtin_cpu_supports)
2204 return SemaBuiltinCpuSupports(*this, TheCall);
2205
Craig Topper699ae0c2017-08-10 20:28:30 +00002206 if (BuiltinID == X86::BI__builtin_cpu_is)
2207 return SemaBuiltinCpuIs(*this, TheCall);
2208
Craig Toppera7e253e2016-09-23 04:48:31 +00002209 // If the intrinsic has rounding or SAE make sure its valid.
2210 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2211 return true;
2212
Craig Topperdf5beb22017-03-13 17:16:50 +00002213 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2214 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2215 return true;
2216
Craig Topperf0ddc892016-09-23 04:48:27 +00002217 // For intrinsics which take an immediate value as part of the instruction,
2218 // range check them here.
2219 int i = 0, l = 0, u = 0;
2220 switch (BuiltinID) {
2221 default:
2222 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002223 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002224 i = 1; l = 0; u = 3;
2225 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002226 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002227 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2228 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2229 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2230 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002231 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002232 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002233 case X86::BI__builtin_ia32_vpermil2pd:
2234 case X86::BI__builtin_ia32_vpermil2pd256:
2235 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002236 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002237 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002238 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002239 case X86::BI__builtin_ia32_cmpb128_mask:
2240 case X86::BI__builtin_ia32_cmpw128_mask:
2241 case X86::BI__builtin_ia32_cmpd128_mask:
2242 case X86::BI__builtin_ia32_cmpq128_mask:
2243 case X86::BI__builtin_ia32_cmpb256_mask:
2244 case X86::BI__builtin_ia32_cmpw256_mask:
2245 case X86::BI__builtin_ia32_cmpd256_mask:
2246 case X86::BI__builtin_ia32_cmpq256_mask:
2247 case X86::BI__builtin_ia32_cmpb512_mask:
2248 case X86::BI__builtin_ia32_cmpw512_mask:
2249 case X86::BI__builtin_ia32_cmpd512_mask:
2250 case X86::BI__builtin_ia32_cmpq512_mask:
2251 case X86::BI__builtin_ia32_ucmpb128_mask:
2252 case X86::BI__builtin_ia32_ucmpw128_mask:
2253 case X86::BI__builtin_ia32_ucmpd128_mask:
2254 case X86::BI__builtin_ia32_ucmpq128_mask:
2255 case X86::BI__builtin_ia32_ucmpb256_mask:
2256 case X86::BI__builtin_ia32_ucmpw256_mask:
2257 case X86::BI__builtin_ia32_ucmpd256_mask:
2258 case X86::BI__builtin_ia32_ucmpq256_mask:
2259 case X86::BI__builtin_ia32_ucmpb512_mask:
2260 case X86::BI__builtin_ia32_ucmpw512_mask:
2261 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002262 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002263 case X86::BI__builtin_ia32_vpcomub:
2264 case X86::BI__builtin_ia32_vpcomuw:
2265 case X86::BI__builtin_ia32_vpcomud:
2266 case X86::BI__builtin_ia32_vpcomuq:
2267 case X86::BI__builtin_ia32_vpcomb:
2268 case X86::BI__builtin_ia32_vpcomw:
2269 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002270 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002271 i = 2; l = 0; u = 7;
2272 break;
2273 case X86::BI__builtin_ia32_roundps:
2274 case X86::BI__builtin_ia32_roundpd:
2275 case X86::BI__builtin_ia32_roundps256:
2276 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002277 i = 1; l = 0; u = 15;
2278 break;
2279 case X86::BI__builtin_ia32_roundss:
2280 case X86::BI__builtin_ia32_roundsd:
2281 case X86::BI__builtin_ia32_rangepd128_mask:
2282 case X86::BI__builtin_ia32_rangepd256_mask:
2283 case X86::BI__builtin_ia32_rangepd512_mask:
2284 case X86::BI__builtin_ia32_rangeps128_mask:
2285 case X86::BI__builtin_ia32_rangeps256_mask:
2286 case X86::BI__builtin_ia32_rangeps512_mask:
2287 case X86::BI__builtin_ia32_getmantsd_round_mask:
2288 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002289 i = 2; l = 0; u = 15;
2290 break;
2291 case X86::BI__builtin_ia32_cmpps:
2292 case X86::BI__builtin_ia32_cmpss:
2293 case X86::BI__builtin_ia32_cmppd:
2294 case X86::BI__builtin_ia32_cmpsd:
2295 case X86::BI__builtin_ia32_cmpps256:
2296 case X86::BI__builtin_ia32_cmppd256:
2297 case X86::BI__builtin_ia32_cmpps128_mask:
2298 case X86::BI__builtin_ia32_cmppd128_mask:
2299 case X86::BI__builtin_ia32_cmpps256_mask:
2300 case X86::BI__builtin_ia32_cmppd256_mask:
2301 case X86::BI__builtin_ia32_cmpps512_mask:
2302 case X86::BI__builtin_ia32_cmppd512_mask:
2303 case X86::BI__builtin_ia32_cmpsd_mask:
2304 case X86::BI__builtin_ia32_cmpss_mask:
2305 i = 2; l = 0; u = 31;
2306 break;
2307 case X86::BI__builtin_ia32_xabort:
2308 i = 0; l = -128; u = 255;
2309 break;
2310 case X86::BI__builtin_ia32_pshufw:
2311 case X86::BI__builtin_ia32_aeskeygenassist128:
2312 i = 1; l = -128; u = 255;
2313 break;
2314 case X86::BI__builtin_ia32_vcvtps2ph:
2315 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper39c87102016-05-18 03:18:12 +00002316 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2317 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2318 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2319 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2320 case X86::BI__builtin_ia32_rndscaleps_mask:
2321 case X86::BI__builtin_ia32_rndscalepd_mask:
2322 case X86::BI__builtin_ia32_reducepd128_mask:
2323 case X86::BI__builtin_ia32_reducepd256_mask:
2324 case X86::BI__builtin_ia32_reducepd512_mask:
2325 case X86::BI__builtin_ia32_reduceps128_mask:
2326 case X86::BI__builtin_ia32_reduceps256_mask:
2327 case X86::BI__builtin_ia32_reduceps512_mask:
2328 case X86::BI__builtin_ia32_prold512_mask:
2329 case X86::BI__builtin_ia32_prolq512_mask:
2330 case X86::BI__builtin_ia32_prold128_mask:
2331 case X86::BI__builtin_ia32_prold256_mask:
2332 case X86::BI__builtin_ia32_prolq128_mask:
2333 case X86::BI__builtin_ia32_prolq256_mask:
2334 case X86::BI__builtin_ia32_prord128_mask:
2335 case X86::BI__builtin_ia32_prord256_mask:
2336 case X86::BI__builtin_ia32_prorq128_mask:
2337 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002338 case X86::BI__builtin_ia32_fpclasspd128_mask:
2339 case X86::BI__builtin_ia32_fpclasspd256_mask:
2340 case X86::BI__builtin_ia32_fpclassps128_mask:
2341 case X86::BI__builtin_ia32_fpclassps256_mask:
2342 case X86::BI__builtin_ia32_fpclassps512_mask:
2343 case X86::BI__builtin_ia32_fpclasspd512_mask:
2344 case X86::BI__builtin_ia32_fpclasssd_mask:
2345 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002346 i = 1; l = 0; u = 255;
2347 break;
2348 case X86::BI__builtin_ia32_palignr:
2349 case X86::BI__builtin_ia32_insertps128:
2350 case X86::BI__builtin_ia32_dpps:
2351 case X86::BI__builtin_ia32_dppd:
2352 case X86::BI__builtin_ia32_dpps256:
2353 case X86::BI__builtin_ia32_mpsadbw128:
2354 case X86::BI__builtin_ia32_mpsadbw256:
2355 case X86::BI__builtin_ia32_pcmpistrm128:
2356 case X86::BI__builtin_ia32_pcmpistri128:
2357 case X86::BI__builtin_ia32_pcmpistria128:
2358 case X86::BI__builtin_ia32_pcmpistric128:
2359 case X86::BI__builtin_ia32_pcmpistrio128:
2360 case X86::BI__builtin_ia32_pcmpistris128:
2361 case X86::BI__builtin_ia32_pcmpistriz128:
2362 case X86::BI__builtin_ia32_pclmulqdq128:
2363 case X86::BI__builtin_ia32_vperm2f128_pd256:
2364 case X86::BI__builtin_ia32_vperm2f128_ps256:
2365 case X86::BI__builtin_ia32_vperm2f128_si256:
2366 case X86::BI__builtin_ia32_permti256:
2367 i = 2; l = -128; u = 255;
2368 break;
2369 case X86::BI__builtin_ia32_palignr128:
2370 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002371 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002372 case X86::BI__builtin_ia32_vcomisd:
2373 case X86::BI__builtin_ia32_vcomiss:
2374 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2375 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2376 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2377 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002378 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2379 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2380 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2381 i = 2; l = 0; u = 255;
2382 break;
2383 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2384 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2385 case X86::BI__builtin_ia32_fixupimmps512_mask:
2386 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2387 case X86::BI__builtin_ia32_fixupimmsd_mask:
2388 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2389 case X86::BI__builtin_ia32_fixupimmss_mask:
2390 case X86::BI__builtin_ia32_fixupimmss_maskz:
2391 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2392 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2393 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2394 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2395 case X86::BI__builtin_ia32_fixupimmps128_mask:
2396 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2397 case X86::BI__builtin_ia32_fixupimmps256_mask:
2398 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2399 case X86::BI__builtin_ia32_pternlogd512_mask:
2400 case X86::BI__builtin_ia32_pternlogd512_maskz:
2401 case X86::BI__builtin_ia32_pternlogq512_mask:
2402 case X86::BI__builtin_ia32_pternlogq512_maskz:
2403 case X86::BI__builtin_ia32_pternlogd128_mask:
2404 case X86::BI__builtin_ia32_pternlogd128_maskz:
2405 case X86::BI__builtin_ia32_pternlogd256_mask:
2406 case X86::BI__builtin_ia32_pternlogd256_maskz:
2407 case X86::BI__builtin_ia32_pternlogq128_mask:
2408 case X86::BI__builtin_ia32_pternlogq128_maskz:
2409 case X86::BI__builtin_ia32_pternlogq256_mask:
2410 case X86::BI__builtin_ia32_pternlogq256_maskz:
2411 i = 3; l = 0; u = 255;
2412 break;
Craig Topper9625db02017-03-12 22:19:10 +00002413 case X86::BI__builtin_ia32_gatherpfdpd:
2414 case X86::BI__builtin_ia32_gatherpfdps:
2415 case X86::BI__builtin_ia32_gatherpfqpd:
2416 case X86::BI__builtin_ia32_gatherpfqps:
2417 case X86::BI__builtin_ia32_scatterpfdpd:
2418 case X86::BI__builtin_ia32_scatterpfdps:
2419 case X86::BI__builtin_ia32_scatterpfqpd:
2420 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002421 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002422 break;
Craig Topper39c87102016-05-18 03:18:12 +00002423 case X86::BI__builtin_ia32_pcmpestrm128:
2424 case X86::BI__builtin_ia32_pcmpestri128:
2425 case X86::BI__builtin_ia32_pcmpestria128:
2426 case X86::BI__builtin_ia32_pcmpestric128:
2427 case X86::BI__builtin_ia32_pcmpestrio128:
2428 case X86::BI__builtin_ia32_pcmpestris128:
2429 case X86::BI__builtin_ia32_pcmpestriz128:
2430 i = 4; l = -128; u = 255;
2431 break;
2432 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2433 case X86::BI__builtin_ia32_rndscaless_round_mask:
2434 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002435 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002436 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002437 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002438}
2439
Richard Smith55ce3522012-06-25 20:30:08 +00002440/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2441/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2442/// Returns true when the format fits the function and the FormatStringInfo has
2443/// been populated.
2444bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2445 FormatStringInfo *FSI) {
2446 FSI->HasVAListArg = Format->getFirstArg() == 0;
2447 FSI->FormatIdx = Format->getFormatIdx() - 1;
2448 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002449
Richard Smith55ce3522012-06-25 20:30:08 +00002450 // The way the format attribute works in GCC, the implicit this argument
2451 // of member functions is counted. However, it doesn't appear in our own
2452 // lists, so decrement format_idx in that case.
2453 if (IsCXXMember) {
2454 if(FSI->FormatIdx == 0)
2455 return false;
2456 --FSI->FormatIdx;
2457 if (FSI->FirstDataArg != 0)
2458 --FSI->FirstDataArg;
2459 }
2460 return true;
2461}
Mike Stump11289f42009-09-09 15:08:12 +00002462
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002463/// Checks if a the given expression evaluates to null.
2464///
2465/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002466static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002467 // If the expression has non-null type, it doesn't evaluate to null.
2468 if (auto nullability
2469 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2470 if (*nullability == NullabilityKind::NonNull)
2471 return false;
2472 }
2473
Ted Kremeneka146db32014-01-17 06:24:47 +00002474 // As a special case, transparent unions initialized with zero are
2475 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002476 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002477 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2478 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002479 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002480 if (const InitListExpr *ILE =
2481 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002482 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002483 }
2484
2485 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002486 return (!Expr->isValueDependent() &&
2487 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2488 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002489}
2490
2491static void CheckNonNullArgument(Sema &S,
2492 const Expr *ArgExpr,
2493 SourceLocation CallSiteLoc) {
2494 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002495 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2496 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002497}
2498
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002499bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2500 FormatStringInfo FSI;
2501 if ((GetFormatStringType(Format) == FST_NSString) &&
2502 getFormatStringInfo(Format, false, &FSI)) {
2503 Idx = FSI.FormatIdx;
2504 return true;
2505 }
2506 return false;
2507}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002508/// \brief Diagnose use of %s directive in an NSString which is being passed
2509/// as formatting string to formatting method.
2510static void
2511DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2512 const NamedDecl *FDecl,
2513 Expr **Args,
2514 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002515 unsigned Idx = 0;
2516 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002517 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2518 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002519 Idx = 2;
2520 Format = true;
2521 }
2522 else
2523 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2524 if (S.GetFormatNSStringIdx(I, Idx)) {
2525 Format = true;
2526 break;
2527 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002528 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002529 if (!Format || NumArgs <= Idx)
2530 return;
2531 const Expr *FormatExpr = Args[Idx];
2532 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2533 FormatExpr = CSCE->getSubExpr();
2534 const StringLiteral *FormatString;
2535 if (const ObjCStringLiteral *OSL =
2536 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2537 FormatString = OSL->getString();
2538 else
2539 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2540 if (!FormatString)
2541 return;
2542 if (S.FormatStringHasSArg(FormatString)) {
2543 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2544 << "%s" << 1 << 1;
2545 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2546 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002547 }
2548}
2549
Douglas Gregorb4866e82015-06-19 18:13:19 +00002550/// Determine whether the given type has a non-null nullability annotation.
2551static bool isNonNullType(ASTContext &ctx, QualType type) {
2552 if (auto nullability = type->getNullability(ctx))
2553 return *nullability == NullabilityKind::NonNull;
2554
2555 return false;
2556}
2557
Ted Kremenek2bc73332014-01-17 06:24:43 +00002558static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002559 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002560 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002561 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002562 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002563 assert((FDecl || Proto) && "Need a function declaration or prototype");
2564
Ted Kremenek9aedc152014-01-17 06:24:56 +00002565 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002566 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002567 if (FDecl) {
2568 // Handle the nonnull attribute on the function/method declaration itself.
2569 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2570 if (!NonNull->args_size()) {
2571 // Easy case: all pointer arguments are nonnull.
2572 for (const auto *Arg : Args)
2573 if (S.isValidPointerAttrType(Arg->getType()))
2574 CheckNonNullArgument(S, Arg, CallSiteLoc);
2575 return;
2576 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002577
Douglas Gregorb4866e82015-06-19 18:13:19 +00002578 for (unsigned Val : NonNull->args()) {
2579 if (Val >= Args.size())
2580 continue;
2581 if (NonNullArgs.empty())
2582 NonNullArgs.resize(Args.size());
2583 NonNullArgs.set(Val);
2584 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002585 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002586 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002587
Douglas Gregorb4866e82015-06-19 18:13:19 +00002588 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2589 // Handle the nonnull attribute on the parameters of the
2590 // function/method.
2591 ArrayRef<ParmVarDecl*> parms;
2592 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2593 parms = FD->parameters();
2594 else
2595 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2596
2597 unsigned ParamIndex = 0;
2598 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2599 I != E; ++I, ++ParamIndex) {
2600 const ParmVarDecl *PVD = *I;
2601 if (PVD->hasAttr<NonNullAttr>() ||
2602 isNonNullType(S.Context, PVD->getType())) {
2603 if (NonNullArgs.empty())
2604 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002605
Douglas Gregorb4866e82015-06-19 18:13:19 +00002606 NonNullArgs.set(ParamIndex);
2607 }
2608 }
2609 } else {
2610 // If we have a non-function, non-method declaration but no
2611 // function prototype, try to dig out the function prototype.
2612 if (!Proto) {
2613 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2614 QualType type = VD->getType().getNonReferenceType();
2615 if (auto pointerType = type->getAs<PointerType>())
2616 type = pointerType->getPointeeType();
2617 else if (auto blockType = type->getAs<BlockPointerType>())
2618 type = blockType->getPointeeType();
2619 // FIXME: data member pointers?
2620
2621 // Dig out the function prototype, if there is one.
2622 Proto = type->getAs<FunctionProtoType>();
2623 }
2624 }
2625
2626 // Fill in non-null argument information from the nullability
2627 // information on the parameter types (if we have them).
2628 if (Proto) {
2629 unsigned Index = 0;
2630 for (auto paramType : Proto->getParamTypes()) {
2631 if (isNonNullType(S.Context, paramType)) {
2632 if (NonNullArgs.empty())
2633 NonNullArgs.resize(Args.size());
2634
2635 NonNullArgs.set(Index);
2636 }
2637
2638 ++Index;
2639 }
2640 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002641 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002642
Douglas Gregorb4866e82015-06-19 18:13:19 +00002643 // Check for non-null arguments.
2644 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2645 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002646 if (NonNullArgs[ArgIndex])
2647 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002648 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002649}
2650
Richard Smith55ce3522012-06-25 20:30:08 +00002651/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002652/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2653/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002654void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002655 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2656 bool IsMemberFunction, SourceLocation Loc,
2657 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002658 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002659 if (CurContext->isDependentContext())
2660 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002661
Ted Kremenekb8176da2010-09-09 04:33:05 +00002662 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002663 llvm::SmallBitVector CheckedVarArgs;
2664 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002665 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002666 // Only create vector if there are format attributes.
2667 CheckedVarArgs.resize(Args.size());
2668
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002669 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002670 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002671 }
Richard Smithd7293d72013-08-05 18:49:43 +00002672 }
Richard Smith55ce3522012-06-25 20:30:08 +00002673
2674 // Refuse POD arguments that weren't caught by the format string
2675 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002676 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2677 if (CallType != VariadicDoesNotApply &&
2678 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002679 unsigned NumParams = Proto ? Proto->getNumParams()
2680 : FDecl && isa<FunctionDecl>(FDecl)
2681 ? cast<FunctionDecl>(FDecl)->getNumParams()
2682 : FDecl && isa<ObjCMethodDecl>(FDecl)
2683 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2684 : 0;
2685
Alp Toker9cacbab2014-01-20 20:26:09 +00002686 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002687 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002688 if (const Expr *Arg = Args[ArgIdx]) {
2689 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2690 checkVariadicArgument(Arg, CallType);
2691 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002692 }
Richard Smithd7293d72013-08-05 18:49:43 +00002693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694
Douglas Gregorb4866e82015-06-19 18:13:19 +00002695 if (FDecl || Proto) {
2696 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002697
Richard Trieu41bc0992013-06-22 00:20:41 +00002698 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002699 if (FDecl) {
2700 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2701 CheckArgumentWithTypeTag(I, Args.data());
2702 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002703 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002704
2705 if (FD)
2706 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002707}
2708
2709/// CheckConstructorCall - Check a constructor call for correctness and safety
2710/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002711void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2712 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002713 const FunctionProtoType *Proto,
2714 SourceLocation Loc) {
2715 VariadicCallType CallType =
2716 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002717 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2718 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002719}
2720
2721/// CheckFunctionCall - Check a direct function call for various correctness
2722/// and safety properties not strictly enforced by the C type system.
2723bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2724 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002725 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2726 isa<CXXMethodDecl>(FDecl);
2727 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2728 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002729 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2730 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002731 Expr** Args = TheCall->getArgs();
2732 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002733
2734 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002735 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002736 // If this is a call to a member operator, hide the first argument
2737 // from checkCall.
2738 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002739 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002740 ++Args;
2741 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002742 } else if (IsMemberFunction)
2743 ImplicitThis =
2744 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2745
2746 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002747 IsMemberFunction, TheCall->getRParenLoc(),
2748 TheCall->getCallee()->getSourceRange(), CallType);
2749
2750 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2751 // None of the checks below are needed for functions that don't have
2752 // simple names (e.g., C++ conversion functions).
2753 if (!FnInfo)
2754 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002755
Richard Trieua7f30b12016-12-06 01:42:28 +00002756 CheckAbsoluteValueFunction(TheCall, FDecl);
2757 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002758
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002759 if (getLangOpts().ObjC1)
2760 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002761
Anna Zaks22122702012-01-17 00:37:07 +00002762 unsigned CMId = FDecl->getMemoryFunctionKind();
2763 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002764 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002765
Anna Zaks201d4892012-01-13 21:52:01 +00002766 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002767 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002768 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002769 else if (CMId == Builtin::BIstrncat)
2770 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002771 else
Anna Zaks22122702012-01-17 00:37:07 +00002772 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002773
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002774 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002775}
2776
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002777bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002778 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002779 VariadicCallType CallType =
2780 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002781
George Burgess IVce6284b2017-01-28 02:19:40 +00002782 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2783 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002784 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002785
2786 return false;
2787}
2788
Richard Trieu664c4c62013-06-20 21:03:13 +00002789bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2790 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002791 QualType Ty;
2792 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002793 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002794 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002795 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002796 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002797 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002798
Douglas Gregorb4866e82015-06-19 18:13:19 +00002799 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2800 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002801 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002802
Richard Trieu664c4c62013-06-20 21:03:13 +00002803 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002804 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002805 CallType = VariadicDoesNotApply;
2806 } else if (Ty->isBlockPointerType()) {
2807 CallType = VariadicBlock;
2808 } else { // Ty->isFunctionPointerType()
2809 CallType = VariadicFunction;
2810 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002811
George Burgess IVce6284b2017-01-28 02:19:40 +00002812 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002813 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2814 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002815 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002816
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002817 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002818}
2819
Richard Trieu41bc0992013-06-22 00:20:41 +00002820/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2821/// such as function pointers returned from functions.
2822bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002823 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002824 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002825 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002826 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002827 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002828 TheCall->getCallee()->getSourceRange(), CallType);
2829
2830 return false;
2831}
2832
Tim Northovere94a34c2014-03-11 10:49:14 +00002833static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002834 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002835 return false;
2836
JF Bastiendda2cb12016-04-18 18:01:49 +00002837 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002838 switch (Op) {
2839 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002840 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002841 llvm_unreachable("There is no ordering argument for an init");
2842
2843 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002844 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002845 case AtomicExpr::AO__atomic_load_n:
2846 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002847 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2848 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002849
2850 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002851 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002852 case AtomicExpr::AO__atomic_store:
2853 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002854 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2855 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2856 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002857
2858 default:
2859 return true;
2860 }
2861}
2862
Richard Smithfeea8832012-04-12 05:08:17 +00002863ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2864 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002865 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2866 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002867
Yaxun Liu39195062017-08-04 18:16:31 +00002868 // All the non-OpenCL operations take one of the following forms.
2869 // The OpenCL operations take the __c11 forms with one extra argument for
2870 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002871 enum {
2872 // C __c11_atomic_init(A *, C)
2873 Init,
2874 // C __c11_atomic_load(A *, int)
2875 Load,
2876 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002877 LoadCopy,
2878 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002879 Copy,
2880 // C __c11_atomic_add(A *, M, int)
2881 Arithmetic,
2882 // C __atomic_exchange_n(A *, CP, int)
2883 Xchg,
2884 // void __atomic_exchange(A *, C *, CP, int)
2885 GNUXchg,
2886 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2887 C11CmpXchg,
2888 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2889 GNUCmpXchg
2890 } Form = Init;
Yaxun Liu39195062017-08-04 18:16:31 +00002891 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002892 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2893 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002894 // where:
2895 // C is an appropriate type,
2896 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2897 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2898 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2899 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002900
Yaxun Liu39195062017-08-04 18:16:31 +00002901 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2902 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2903 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002904 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2905 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2906 AtomicExpr::AO__atomic_load,
2907 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002908 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2909 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2910 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2911 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2912 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002913 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2914 Op == AtomicExpr::AO__atomic_store_n ||
2915 Op == AtomicExpr::AO__atomic_exchange_n ||
2916 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2917 bool IsAddSub = false;
2918
2919 switch (Op) {
2920 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002921 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002922 Form = Init;
2923 break;
2924
2925 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002926 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002927 case AtomicExpr::AO__atomic_load_n:
2928 Form = Load;
2929 break;
2930
Richard Smithfeea8832012-04-12 05:08:17 +00002931 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00002932 Form = LoadCopy;
2933 break;
2934
2935 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002936 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00002937 case AtomicExpr::AO__atomic_store:
2938 case AtomicExpr::AO__atomic_store_n:
2939 Form = Copy;
2940 break;
2941
2942 case AtomicExpr::AO__c11_atomic_fetch_add:
2943 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00002944 case AtomicExpr::AO__opencl_atomic_fetch_add:
2945 case AtomicExpr::AO__opencl_atomic_fetch_sub:
2946 case AtomicExpr::AO__opencl_atomic_fetch_min:
2947 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00002948 case AtomicExpr::AO__atomic_fetch_add:
2949 case AtomicExpr::AO__atomic_fetch_sub:
2950 case AtomicExpr::AO__atomic_add_fetch:
2951 case AtomicExpr::AO__atomic_sub_fetch:
2952 IsAddSub = true;
2953 // Fall through.
2954 case AtomicExpr::AO__c11_atomic_fetch_and:
2955 case AtomicExpr::AO__c11_atomic_fetch_or:
2956 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00002957 case AtomicExpr::AO__opencl_atomic_fetch_and:
2958 case AtomicExpr::AO__opencl_atomic_fetch_or:
2959 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00002960 case AtomicExpr::AO__atomic_fetch_and:
2961 case AtomicExpr::AO__atomic_fetch_or:
2962 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00002963 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00002964 case AtomicExpr::AO__atomic_and_fetch:
2965 case AtomicExpr::AO__atomic_or_fetch:
2966 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00002967 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00002968 Form = Arithmetic;
2969 break;
2970
2971 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00002972 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00002973 case AtomicExpr::AO__atomic_exchange_n:
2974 Form = Xchg;
2975 break;
2976
2977 case AtomicExpr::AO__atomic_exchange:
2978 Form = GNUXchg;
2979 break;
2980
2981 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2982 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00002983 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2984 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00002985 Form = C11CmpXchg;
2986 break;
2987
2988 case AtomicExpr::AO__atomic_compare_exchange:
2989 case AtomicExpr::AO__atomic_compare_exchange_n:
2990 Form = GNUCmpXchg;
2991 break;
2992 }
2993
Yaxun Liu39195062017-08-04 18:16:31 +00002994 unsigned AdjustedNumArgs = NumArgs[Form];
2995 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2996 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00002997 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00002998 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002999 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003000 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003001 << TheCall->getCallee()->getSourceRange();
3002 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003003 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3004 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003005 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003006 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003007 << TheCall->getCallee()->getSourceRange();
3008 return ExprError();
3009 }
3010
Richard Smithfeea8832012-04-12 05:08:17 +00003011 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003012 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003013 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3014 if (ConvertedPtr.isInvalid())
3015 return ExprError();
3016
3017 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003018 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3019 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003020 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003021 << Ptr->getType() << Ptr->getSourceRange();
3022 return ExprError();
3023 }
3024
Richard Smithfeea8832012-04-12 05:08:17 +00003025 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3026 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3027 QualType ValType = AtomTy; // 'C'
3028 if (IsC11) {
3029 if (!AtomTy->isAtomicType()) {
3030 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3031 << Ptr->getType() << Ptr->getSourceRange();
3032 return ExprError();
3033 }
Yaxun Liu39195062017-08-04 18:16:31 +00003034 if (AtomTy.isConstQualified() ||
3035 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003036 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003037 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3038 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003039 return ExprError();
3040 }
Richard Smithfeea8832012-04-12 05:08:17 +00003041 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003042 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003043 if (ValType.isConstQualified()) {
3044 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3045 << Ptr->getType() << Ptr->getSourceRange();
3046 return ExprError();
3047 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003048 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003049
Richard Smithfeea8832012-04-12 05:08:17 +00003050 // For an arithmetic operation, the implied arithmetic must be well-formed.
3051 if (Form == Arithmetic) {
3052 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3053 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3054 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3055 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3056 return ExprError();
3057 }
3058 if (!IsAddSub && !ValType->isIntegerType()) {
3059 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3060 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3061 return ExprError();
3062 }
David Majnemere85cff82015-01-28 05:48:06 +00003063 if (IsC11 && ValType->isPointerType() &&
3064 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3065 diag::err_incomplete_type)) {
3066 return ExprError();
3067 }
Richard Smithfeea8832012-04-12 05:08:17 +00003068 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3069 // For __atomic_*_n operations, the value type must be a scalar integral or
3070 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003071 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003072 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3073 return ExprError();
3074 }
3075
Eli Friedmanaa769812013-09-11 03:49:34 +00003076 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3077 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003078 // For GNU atomics, require a trivially-copyable type. This is not part of
3079 // the GNU atomics specification, but we enforce it for sanity.
3080 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003081 << Ptr->getType() << Ptr->getSourceRange();
3082 return ExprError();
3083 }
3084
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003085 switch (ValType.getObjCLifetime()) {
3086 case Qualifiers::OCL_None:
3087 case Qualifiers::OCL_ExplicitNone:
3088 // okay
3089 break;
3090
3091 case Qualifiers::OCL_Weak:
3092 case Qualifiers::OCL_Strong:
3093 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003094 // FIXME: Can this happen? By this point, ValType should be known
3095 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003096 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3097 << ValType << Ptr->getSourceRange();
3098 return ExprError();
3099 }
3100
David Majnemerc6eb6502015-06-03 00:26:35 +00003101 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3102 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003103 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003104 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003105 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003106 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003107 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3108 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003109 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003110 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003111 ResultType = Context.BoolTy;
3112
Richard Smithfeea8832012-04-12 05:08:17 +00003113 // The type of a parameter passed 'by value'. In the GNU atomics, such
3114 // arguments are actually passed as pointers.
3115 QualType ByValType = ValType; // 'CP'
3116 if (!IsC11 && !IsN)
3117 ByValType = Ptr->getType();
3118
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003119 // The first argument --- the pointer --- has a fixed type; we
3120 // deduce the types of the rest of the arguments accordingly. Walk
3121 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003122 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003123 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003124 if (i < NumVals[Form] + 1) {
3125 switch (i) {
3126 case 1:
3127 // The second argument is the non-atomic operand. For arithmetic, this
3128 // is always passed by value, and for a compare_exchange it is always
3129 // passed by address. For the rest, GNU uses by-address and C11 uses
3130 // by-value.
3131 assert(Form != Load);
3132 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3133 Ty = ValType;
3134 else if (Form == Copy || Form == Xchg)
3135 Ty = ByValType;
3136 else if (Form == Arithmetic)
3137 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003138 else {
3139 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003140 // Treat this argument as _Nonnull as we want to show a warning if
3141 // NULL is passed into it.
3142 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003143 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003144 // Keep address space of non-atomic pointer type.
3145 if (const PointerType *PtrTy =
3146 ValArg->getType()->getAs<PointerType>()) {
3147 AS = PtrTy->getPointeeType().getAddressSpace();
3148 }
3149 Ty = Context.getPointerType(
3150 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3151 }
Richard Smithfeea8832012-04-12 05:08:17 +00003152 break;
3153 case 2:
3154 // The third argument to compare_exchange / GNU exchange is a
3155 // (pointer to a) desired value.
3156 Ty = ByValType;
3157 break;
3158 case 3:
3159 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3160 Ty = Context.BoolTy;
3161 break;
3162 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003163 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003164 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003165 Ty = Context.IntTy;
3166 }
Richard Smithfeea8832012-04-12 05:08:17 +00003167
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003168 InitializedEntity Entity =
3169 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003170 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003171 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3172 if (Arg.isInvalid())
3173 return true;
3174 TheCall->setArg(i, Arg.get());
3175 }
3176
Richard Smithfeea8832012-04-12 05:08:17 +00003177 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003178 SmallVector<Expr*, 5> SubExprs;
3179 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003180 switch (Form) {
3181 case Init:
3182 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003183 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003184 break;
3185 case Load:
3186 SubExprs.push_back(TheCall->getArg(1)); // Order
3187 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003188 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003189 case Copy:
3190 case Arithmetic:
3191 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003192 SubExprs.push_back(TheCall->getArg(2)); // Order
3193 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003194 break;
3195 case GNUXchg:
3196 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3197 SubExprs.push_back(TheCall->getArg(3)); // Order
3198 SubExprs.push_back(TheCall->getArg(1)); // Val1
3199 SubExprs.push_back(TheCall->getArg(2)); // Val2
3200 break;
3201 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003202 SubExprs.push_back(TheCall->getArg(3)); // Order
3203 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003204 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003205 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003206 break;
3207 case GNUCmpXchg:
3208 SubExprs.push_back(TheCall->getArg(4)); // Order
3209 SubExprs.push_back(TheCall->getArg(1)); // Val1
3210 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3211 SubExprs.push_back(TheCall->getArg(2)); // Val2
3212 SubExprs.push_back(TheCall->getArg(3)); // Weak
3213 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003214 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003215
3216 if (SubExprs.size() >= 2 && Form != Init) {
3217 llvm::APSInt Result(32);
3218 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3219 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003220 Diag(SubExprs[1]->getLocStart(),
3221 diag::warn_atomic_op_has_invalid_memory_order)
3222 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003223 }
3224
Yaxun Liu30d652a2017-08-15 16:02:49 +00003225 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3226 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3227 llvm::APSInt Result(32);
3228 if (Scope->isIntegerConstantExpr(Result, Context) &&
3229 !ScopeModel->isValid(Result.getZExtValue())) {
3230 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3231 << Scope->getSourceRange();
3232 }
3233 SubExprs.push_back(Scope);
3234 }
3235
Fariborz Jahanian615de762013-05-28 17:37:39 +00003236 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3237 SubExprs, ResultType, Op,
3238 TheCall->getRParenLoc());
3239
3240 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003241 Op == AtomicExpr::AO__c11_atomic_store ||
3242 Op == AtomicExpr::AO__opencl_atomic_load ||
3243 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003244 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003245 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3246 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3247 Op == AtomicExpr::AO__opencl_atomic_load)
3248 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003249
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003250 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003251}
3252
John McCall29ad95b2011-08-27 01:09:30 +00003253/// checkBuiltinArgument - Given a call to a builtin function, perform
3254/// normal type-checking on the given argument, updating the call in
3255/// place. This is useful when a builtin function requires custom
3256/// type-checking for some of its arguments but not necessarily all of
3257/// them.
3258///
3259/// Returns true on error.
3260static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3261 FunctionDecl *Fn = E->getDirectCallee();
3262 assert(Fn && "builtin call without direct callee!");
3263
3264 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3265 InitializedEntity Entity =
3266 InitializedEntity::InitializeParameter(S.Context, Param);
3267
3268 ExprResult Arg = E->getArg(0);
3269 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3270 if (Arg.isInvalid())
3271 return true;
3272
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003273 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003274 return false;
3275}
3276
Chris Lattnerdc046542009-05-08 06:58:22 +00003277/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3278/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3279/// type of its first argument. The main ActOnCallExpr routines have already
3280/// promoted the types of arguments because all of these calls are prototyped as
3281/// void(...).
3282///
3283/// This function goes through and does final semantic checking for these
3284/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003285ExprResult
3286Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003287 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003288 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3289 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3290
3291 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003292 if (TheCall->getNumArgs() < 1) {
3293 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3294 << 0 << 1 << TheCall->getNumArgs()
3295 << TheCall->getCallee()->getSourceRange();
3296 return ExprError();
3297 }
Mike Stump11289f42009-09-09 15:08:12 +00003298
Chris Lattnerdc046542009-05-08 06:58:22 +00003299 // Inspect the first argument of the atomic builtin. This should always be
3300 // a pointer type, whose element is an integral scalar or pointer type.
3301 // Because it is a pointer type, we don't have to worry about any implicit
3302 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003303 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003304 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003305 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3306 if (FirstArgResult.isInvalid())
3307 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003308 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003309 TheCall->setArg(0, FirstArg);
3310
John McCall31168b02011-06-15 23:02:42 +00003311 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3312 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003313 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3314 << FirstArg->getType() << FirstArg->getSourceRange();
3315 return ExprError();
3316 }
Mike Stump11289f42009-09-09 15:08:12 +00003317
John McCall31168b02011-06-15 23:02:42 +00003318 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003319 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003320 !ValType->isBlockPointerType()) {
3321 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3322 << FirstArg->getType() << FirstArg->getSourceRange();
3323 return ExprError();
3324 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003325
John McCall31168b02011-06-15 23:02:42 +00003326 switch (ValType.getObjCLifetime()) {
3327 case Qualifiers::OCL_None:
3328 case Qualifiers::OCL_ExplicitNone:
3329 // okay
3330 break;
3331
3332 case Qualifiers::OCL_Weak:
3333 case Qualifiers::OCL_Strong:
3334 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003335 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003336 << ValType << FirstArg->getSourceRange();
3337 return ExprError();
3338 }
3339
John McCallb50451a2011-10-05 07:41:44 +00003340 // Strip any qualifiers off ValType.
3341 ValType = ValType.getUnqualifiedType();
3342
Chandler Carruth3973af72010-07-18 20:54:12 +00003343 // The majority of builtins return a value, but a few have special return
3344 // types, so allow them to override appropriately below.
3345 QualType ResultType = ValType;
3346
Chris Lattnerdc046542009-05-08 06:58:22 +00003347 // We need to figure out which concrete builtin this maps onto. For example,
3348 // __sync_fetch_and_add with a 2 byte object turns into
3349 // __sync_fetch_and_add_2.
3350#define BUILTIN_ROW(x) \
3351 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3352 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003353
Chris Lattnerdc046542009-05-08 06:58:22 +00003354 static const unsigned BuiltinIndices[][5] = {
3355 BUILTIN_ROW(__sync_fetch_and_add),
3356 BUILTIN_ROW(__sync_fetch_and_sub),
3357 BUILTIN_ROW(__sync_fetch_and_or),
3358 BUILTIN_ROW(__sync_fetch_and_and),
3359 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003360 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003361
Chris Lattnerdc046542009-05-08 06:58:22 +00003362 BUILTIN_ROW(__sync_add_and_fetch),
3363 BUILTIN_ROW(__sync_sub_and_fetch),
3364 BUILTIN_ROW(__sync_and_and_fetch),
3365 BUILTIN_ROW(__sync_or_and_fetch),
3366 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003367 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattnerdc046542009-05-08 06:58:22 +00003369 BUILTIN_ROW(__sync_val_compare_and_swap),
3370 BUILTIN_ROW(__sync_bool_compare_and_swap),
3371 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003372 BUILTIN_ROW(__sync_lock_release),
3373 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003374 };
Mike Stump11289f42009-09-09 15:08:12 +00003375#undef BUILTIN_ROW
3376
Chris Lattnerdc046542009-05-08 06:58:22 +00003377 // Determine the index of the size.
3378 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003379 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003380 case 1: SizeIndex = 0; break;
3381 case 2: SizeIndex = 1; break;
3382 case 4: SizeIndex = 2; break;
3383 case 8: SizeIndex = 3; break;
3384 case 16: SizeIndex = 4; break;
3385 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003386 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3387 << FirstArg->getType() << FirstArg->getSourceRange();
3388 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003389 }
Mike Stump11289f42009-09-09 15:08:12 +00003390
Chris Lattnerdc046542009-05-08 06:58:22 +00003391 // Each of these builtins has one pointer argument, followed by some number of
3392 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3393 // that we ignore. Find out which row of BuiltinIndices to read from as well
3394 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003395 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003396 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003397 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003398 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003399 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003400 case Builtin::BI__sync_fetch_and_add:
3401 case Builtin::BI__sync_fetch_and_add_1:
3402 case Builtin::BI__sync_fetch_and_add_2:
3403 case Builtin::BI__sync_fetch_and_add_4:
3404 case Builtin::BI__sync_fetch_and_add_8:
3405 case Builtin::BI__sync_fetch_and_add_16:
3406 BuiltinIndex = 0;
3407 break;
3408
3409 case Builtin::BI__sync_fetch_and_sub:
3410 case Builtin::BI__sync_fetch_and_sub_1:
3411 case Builtin::BI__sync_fetch_and_sub_2:
3412 case Builtin::BI__sync_fetch_and_sub_4:
3413 case Builtin::BI__sync_fetch_and_sub_8:
3414 case Builtin::BI__sync_fetch_and_sub_16:
3415 BuiltinIndex = 1;
3416 break;
3417
3418 case Builtin::BI__sync_fetch_and_or:
3419 case Builtin::BI__sync_fetch_and_or_1:
3420 case Builtin::BI__sync_fetch_and_or_2:
3421 case Builtin::BI__sync_fetch_and_or_4:
3422 case Builtin::BI__sync_fetch_and_or_8:
3423 case Builtin::BI__sync_fetch_and_or_16:
3424 BuiltinIndex = 2;
3425 break;
3426
3427 case Builtin::BI__sync_fetch_and_and:
3428 case Builtin::BI__sync_fetch_and_and_1:
3429 case Builtin::BI__sync_fetch_and_and_2:
3430 case Builtin::BI__sync_fetch_and_and_4:
3431 case Builtin::BI__sync_fetch_and_and_8:
3432 case Builtin::BI__sync_fetch_and_and_16:
3433 BuiltinIndex = 3;
3434 break;
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregor73722482011-11-28 16:30:08 +00003436 case Builtin::BI__sync_fetch_and_xor:
3437 case Builtin::BI__sync_fetch_and_xor_1:
3438 case Builtin::BI__sync_fetch_and_xor_2:
3439 case Builtin::BI__sync_fetch_and_xor_4:
3440 case Builtin::BI__sync_fetch_and_xor_8:
3441 case Builtin::BI__sync_fetch_and_xor_16:
3442 BuiltinIndex = 4;
3443 break;
3444
Hal Finkeld2208b52014-10-02 20:53:50 +00003445 case Builtin::BI__sync_fetch_and_nand:
3446 case Builtin::BI__sync_fetch_and_nand_1:
3447 case Builtin::BI__sync_fetch_and_nand_2:
3448 case Builtin::BI__sync_fetch_and_nand_4:
3449 case Builtin::BI__sync_fetch_and_nand_8:
3450 case Builtin::BI__sync_fetch_and_nand_16:
3451 BuiltinIndex = 5;
3452 WarnAboutSemanticsChange = true;
3453 break;
3454
Douglas Gregor73722482011-11-28 16:30:08 +00003455 case Builtin::BI__sync_add_and_fetch:
3456 case Builtin::BI__sync_add_and_fetch_1:
3457 case Builtin::BI__sync_add_and_fetch_2:
3458 case Builtin::BI__sync_add_and_fetch_4:
3459 case Builtin::BI__sync_add_and_fetch_8:
3460 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003461 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003462 break;
3463
3464 case Builtin::BI__sync_sub_and_fetch:
3465 case Builtin::BI__sync_sub_and_fetch_1:
3466 case Builtin::BI__sync_sub_and_fetch_2:
3467 case Builtin::BI__sync_sub_and_fetch_4:
3468 case Builtin::BI__sync_sub_and_fetch_8:
3469 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003470 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003471 break;
3472
3473 case Builtin::BI__sync_and_and_fetch:
3474 case Builtin::BI__sync_and_and_fetch_1:
3475 case Builtin::BI__sync_and_and_fetch_2:
3476 case Builtin::BI__sync_and_and_fetch_4:
3477 case Builtin::BI__sync_and_and_fetch_8:
3478 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003479 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003480 break;
3481
3482 case Builtin::BI__sync_or_and_fetch:
3483 case Builtin::BI__sync_or_and_fetch_1:
3484 case Builtin::BI__sync_or_and_fetch_2:
3485 case Builtin::BI__sync_or_and_fetch_4:
3486 case Builtin::BI__sync_or_and_fetch_8:
3487 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003488 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003489 break;
3490
3491 case Builtin::BI__sync_xor_and_fetch:
3492 case Builtin::BI__sync_xor_and_fetch_1:
3493 case Builtin::BI__sync_xor_and_fetch_2:
3494 case Builtin::BI__sync_xor_and_fetch_4:
3495 case Builtin::BI__sync_xor_and_fetch_8:
3496 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003497 BuiltinIndex = 10;
3498 break;
3499
3500 case Builtin::BI__sync_nand_and_fetch:
3501 case Builtin::BI__sync_nand_and_fetch_1:
3502 case Builtin::BI__sync_nand_and_fetch_2:
3503 case Builtin::BI__sync_nand_and_fetch_4:
3504 case Builtin::BI__sync_nand_and_fetch_8:
3505 case Builtin::BI__sync_nand_and_fetch_16:
3506 BuiltinIndex = 11;
3507 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003508 break;
Mike Stump11289f42009-09-09 15:08:12 +00003509
Chris Lattnerdc046542009-05-08 06:58:22 +00003510 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003511 case Builtin::BI__sync_val_compare_and_swap_1:
3512 case Builtin::BI__sync_val_compare_and_swap_2:
3513 case Builtin::BI__sync_val_compare_and_swap_4:
3514 case Builtin::BI__sync_val_compare_and_swap_8:
3515 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003516 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003517 NumFixed = 2;
3518 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003519
Chris Lattnerdc046542009-05-08 06:58:22 +00003520 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003521 case Builtin::BI__sync_bool_compare_and_swap_1:
3522 case Builtin::BI__sync_bool_compare_and_swap_2:
3523 case Builtin::BI__sync_bool_compare_and_swap_4:
3524 case Builtin::BI__sync_bool_compare_and_swap_8:
3525 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003526 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003527 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003528 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003529 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003530
3531 case Builtin::BI__sync_lock_test_and_set:
3532 case Builtin::BI__sync_lock_test_and_set_1:
3533 case Builtin::BI__sync_lock_test_and_set_2:
3534 case Builtin::BI__sync_lock_test_and_set_4:
3535 case Builtin::BI__sync_lock_test_and_set_8:
3536 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003537 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003538 break;
3539
Chris Lattnerdc046542009-05-08 06:58:22 +00003540 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003541 case Builtin::BI__sync_lock_release_1:
3542 case Builtin::BI__sync_lock_release_2:
3543 case Builtin::BI__sync_lock_release_4:
3544 case Builtin::BI__sync_lock_release_8:
3545 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003546 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003547 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003548 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003549 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003550
3551 case Builtin::BI__sync_swap:
3552 case Builtin::BI__sync_swap_1:
3553 case Builtin::BI__sync_swap_2:
3554 case Builtin::BI__sync_swap_4:
3555 case Builtin::BI__sync_swap_8:
3556 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003557 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003558 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003559 }
Mike Stump11289f42009-09-09 15:08:12 +00003560
Chris Lattnerdc046542009-05-08 06:58:22 +00003561 // Now that we know how many fixed arguments we expect, first check that we
3562 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003563 if (TheCall->getNumArgs() < 1+NumFixed) {
3564 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3565 << 0 << 1+NumFixed << TheCall->getNumArgs()
3566 << TheCall->getCallee()->getSourceRange();
3567 return ExprError();
3568 }
Mike Stump11289f42009-09-09 15:08:12 +00003569
Hal Finkeld2208b52014-10-02 20:53:50 +00003570 if (WarnAboutSemanticsChange) {
3571 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3572 << TheCall->getCallee()->getSourceRange();
3573 }
3574
Chris Lattner5b9241b2009-05-08 15:36:58 +00003575 // Get the decl for the concrete builtin from this, we can tell what the
3576 // concrete integer type we should convert to is.
3577 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003578 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003579 FunctionDecl *NewBuiltinDecl;
3580 if (NewBuiltinID == BuiltinID)
3581 NewBuiltinDecl = FDecl;
3582 else {
3583 // Perform builtin lookup to avoid redeclaring it.
3584 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3585 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3586 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3587 assert(Res.getFoundDecl());
3588 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003589 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003590 return ExprError();
3591 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003592
John McCallcf142162010-08-07 06:22:56 +00003593 // The first argument --- the pointer --- has a fixed type; we
3594 // deduce the types of the rest of the arguments accordingly. Walk
3595 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003596 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003597 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003598
Chris Lattnerdc046542009-05-08 06:58:22 +00003599 // GCC does an implicit conversion to the pointer or integer ValType. This
3600 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003601 // Initialize the argument.
3602 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3603 ValType, /*consume*/ false);
3604 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003605 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003606 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003607
Chris Lattnerdc046542009-05-08 06:58:22 +00003608 // Okay, we have something that *can* be converted to the right type. Check
3609 // to see if there is a potentially weird extension going on here. This can
3610 // happen when you do an atomic operation on something like an char* and
3611 // pass in 42. The 42 gets converted to char. This is even more strange
3612 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003613 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003614 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003615 }
Mike Stump11289f42009-09-09 15:08:12 +00003616
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003617 ASTContext& Context = this->getASTContext();
3618
3619 // Create a new DeclRefExpr to refer to the new decl.
3620 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3621 Context,
3622 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003623 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003624 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003625 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003626 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003627 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003628 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003629
Chris Lattnerdc046542009-05-08 06:58:22 +00003630 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003631 // FIXME: This loses syntactic information.
3632 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3633 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3634 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003635 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003636
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003637 // Change the result type of the call to match the original value type. This
3638 // is arbitrary, but the codegen for these builtins ins design to handle it
3639 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003640 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003641
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003642 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003643}
3644
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003645/// SemaBuiltinNontemporalOverloaded - We have a call to
3646/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3647/// overloaded function based on the pointer type of its last argument.
3648///
3649/// This function goes through and does final semantic checking for these
3650/// builtins.
3651ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3652 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3653 DeclRefExpr *DRE =
3654 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3655 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3656 unsigned BuiltinID = FDecl->getBuiltinID();
3657 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3658 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3659 "Unexpected nontemporal load/store builtin!");
3660 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3661 unsigned numArgs = isStore ? 2 : 1;
3662
3663 // Ensure that we have the proper number of arguments.
3664 if (checkArgCount(*this, TheCall, numArgs))
3665 return ExprError();
3666
3667 // Inspect the last argument of the nontemporal builtin. This should always
3668 // be a pointer type, from which we imply the type of the memory access.
3669 // Because it is a pointer type, we don't have to worry about any implicit
3670 // casts here.
3671 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3672 ExprResult PointerArgResult =
3673 DefaultFunctionArrayLvalueConversion(PointerArg);
3674
3675 if (PointerArgResult.isInvalid())
3676 return ExprError();
3677 PointerArg = PointerArgResult.get();
3678 TheCall->setArg(numArgs - 1, PointerArg);
3679
3680 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3681 if (!pointerType) {
3682 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3683 << PointerArg->getType() << PointerArg->getSourceRange();
3684 return ExprError();
3685 }
3686
3687 QualType ValType = pointerType->getPointeeType();
3688
3689 // Strip any qualifiers off ValType.
3690 ValType = ValType.getUnqualifiedType();
3691 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3692 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3693 !ValType->isVectorType()) {
3694 Diag(DRE->getLocStart(),
3695 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3696 << PointerArg->getType() << PointerArg->getSourceRange();
3697 return ExprError();
3698 }
3699
3700 if (!isStore) {
3701 TheCall->setType(ValType);
3702 return TheCallResult;
3703 }
3704
3705 ExprResult ValArg = TheCall->getArg(0);
3706 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3707 Context, ValType, /*consume*/ false);
3708 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3709 if (ValArg.isInvalid())
3710 return ExprError();
3711
3712 TheCall->setArg(0, ValArg.get());
3713 TheCall->setType(Context.VoidTy);
3714 return TheCallResult;
3715}
3716
Chris Lattner6436fb62009-02-18 06:01:06 +00003717/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003718/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003719/// Note: It might also make sense to do the UTF-16 conversion here (would
3720/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003721bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003722 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003723 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3724
Douglas Gregorfb65e592011-07-27 05:40:30 +00003725 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003726 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3727 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003728 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003729 }
Mike Stump11289f42009-09-09 15:08:12 +00003730
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003731 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003732 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003733 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003734 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3735 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3736 llvm::UTF16 *ToPtr = &ToBuf[0];
3737
3738 llvm::ConversionResult Result =
3739 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3740 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003741 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003742 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003743 Diag(Arg->getLocStart(),
3744 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3745 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003746 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003747}
3748
Mehdi Amini06d367c2016-10-24 20:39:34 +00003749/// CheckObjCString - Checks that the format string argument to the os_log()
3750/// and os_trace() functions is correct, and converts it to const char *.
3751ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3752 Arg = Arg->IgnoreParenCasts();
3753 auto *Literal = dyn_cast<StringLiteral>(Arg);
3754 if (!Literal) {
3755 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3756 Literal = ObjcLiteral->getString();
3757 }
3758 }
3759
3760 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3761 return ExprError(
3762 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3763 << Arg->getSourceRange());
3764 }
3765
3766 ExprResult Result(Literal);
3767 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3768 InitializedEntity Entity =
3769 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3770 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3771 return Result;
3772}
3773
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003774/// Check that the user is calling the appropriate va_start builtin for the
3775/// target and calling convention.
3776static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3777 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3778 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003779 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003780 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003781 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3782 if (IsX64 || IsAArch64) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003783 clang::CallingConv CC = CC_C;
3784 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3785 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3786 if (IsMSVAStart) {
3787 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003788 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003789 return S.Diag(Fn->getLocStart(),
3790 diag::err_ms_va_start_used_in_sysv_function);
3791 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003792 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003793 // On x64 Windows, don't allow this in System V ABI functions.
3794 // (Yes, that means there's no corresponding way to support variadic
3795 // System V ABI functions on Windows.)
3796 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003797 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003798 return S.Diag(Fn->getLocStart(),
3799 diag::err_va_start_used_in_wrong_abi_function)
3800 << !IsWindows;
3801 }
3802 return false;
3803 }
3804
3805 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003806 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003807 return false;
3808}
3809
3810static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3811 ParmVarDecl **LastParam = nullptr) {
3812 // Determine whether the current function, block, or obj-c method is variadic
3813 // and get its parameter list.
3814 bool IsVariadic = false;
3815 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003816 DeclContext *Caller = S.CurContext;
3817 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3818 IsVariadic = Block->isVariadic();
3819 Params = Block->parameters();
3820 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003821 IsVariadic = FD->isVariadic();
3822 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003823 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003824 IsVariadic = MD->isVariadic();
3825 // FIXME: This isn't correct for methods (results in bogus warning).
3826 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003827 } else if (isa<CapturedDecl>(Caller)) {
3828 // We don't support va_start in a CapturedDecl.
3829 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3830 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003831 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003832 // This must be some other declcontext that parses exprs.
3833 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3834 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003835 }
3836
3837 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003838 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003839 return true;
3840 }
3841
3842 if (LastParam)
3843 *LastParam = Params.empty() ? nullptr : Params.back();
3844
3845 return false;
3846}
3847
Charles Davisc7d5c942015-09-17 20:55:33 +00003848/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3849/// for validity. Emit an error and return true on failure; return false
3850/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003851bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003852 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003853
3854 if (checkVAStartABI(*this, BuiltinID, Fn))
3855 return true;
3856
Chris Lattner08464942007-12-28 05:29:59 +00003857 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003858 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003859 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003860 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3861 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003862 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003863 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003864 return true;
3865 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003866
3867 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003868 return Diag(TheCall->getLocEnd(),
3869 diag::err_typecheck_call_too_few_args_at_least)
3870 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003871 }
3872
John McCall29ad95b2011-08-27 01:09:30 +00003873 // Type-check the first argument normally.
3874 if (checkBuiltinArgument(*this, TheCall, 0))
3875 return true;
3876
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003877 // Check that the current function is variadic, and get its last parameter.
3878 ParmVarDecl *LastParam;
3879 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003880 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003881
Chris Lattner43be2e62007-12-19 23:59:04 +00003882 // Verify that the second argument to the builtin is the last argument of the
3883 // current function or method.
3884 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003885 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003886
Nico Weber9eea7642013-05-24 23:31:57 +00003887 // These are valid if SecondArgIsLastNamedArgument is false after the next
3888 // block.
3889 QualType Type;
3890 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003891 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003892
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003893 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3894 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003895 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003896
3897 Type = PV->getType();
3898 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003899 IsCRegister =
3900 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003901 }
3902 }
Mike Stump11289f42009-09-09 15:08:12 +00003903
Chris Lattner43be2e62007-12-19 23:59:04 +00003904 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003905 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003906 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003907 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003908 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3909 // Promotable integers are UB, but enumerations need a bit of
3910 // extra checking to see what their promotable type actually is.
3911 if (!Type->isPromotableIntegerType())
3912 return false;
3913 if (!Type->isEnumeralType())
3914 return true;
3915 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3916 return !(ED &&
3917 Context.typesAreCompatible(ED->getPromotionType(), Type));
3918 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003919 unsigned Reason = 0;
3920 if (Type->isReferenceType()) Reason = 1;
3921 else if (IsCRegister) Reason = 2;
3922 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003923 Diag(ParamLoc, diag::note_parameter_type) << Type;
3924 }
3925
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003926 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003927 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003928}
Chris Lattner43be2e62007-12-19 23:59:04 +00003929
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00003930bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003931 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3932 // const char *named_addr);
3933
3934 Expr *Func = Call->getCallee();
3935
3936 if (Call->getNumArgs() < 3)
3937 return Diag(Call->getLocEnd(),
3938 diag::err_typecheck_call_too_few_args_at_least)
3939 << 0 /*function call*/ << 3 << Call->getNumArgs();
3940
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003941 // Type-check the first argument normally.
3942 if (checkBuiltinArgument(*this, Call, 0))
3943 return true;
3944
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003945 // Check that the current function is variadic.
3946 if (checkVAStartIsInVariadicFunction(*this, Func))
3947 return true;
3948
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00003949 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003950
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00003951 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3952 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
3953
3954 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
3955 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
3956
3957 const QualType &ConstCharPtrTy =
3958 Context.getPointerType(Context.CharTy.withConst());
3959 if (!Arg1Ty->isPointerType() ||
3960 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
3961 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
3962 << Arg1->getType() << ConstCharPtrTy
3963 << 1 /* different class */
3964 << 0 /* qualifier difference */
3965 << 3 /* parameter mismatch */
3966 << 2 << Arg1->getType() << ConstCharPtrTy;
3967
3968 const QualType SizeTy = Context.getSizeType();
3969 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
3970 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
3971 << Arg2->getType() << SizeTy
3972 << 1 /* different class */
3973 << 0 /* qualifier difference */
3974 << 3 /* parameter mismatch */
3975 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00003976
3977 return false;
3978}
3979
Chris Lattner2da14fb2007-12-20 00:26:33 +00003980/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3981/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00003982bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3983 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00003984 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00003985 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00003986 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00003987 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003988 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003989 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00003990 << SourceRange(TheCall->getArg(2)->getLocStart(),
3991 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003992
John Wiegley01296292011-04-08 18:41:53 +00003993 ExprResult OrigArg0 = TheCall->getArg(0);
3994 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00003995
Chris Lattner2da14fb2007-12-20 00:26:33 +00003996 // Do standard promotions between the two arguments, returning their common
3997 // type.
Chris Lattner08464942007-12-28 05:29:59 +00003998 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00003999 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4000 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004001
4002 // Make sure any conversions are pushed back into the call; this is
4003 // type safe since unordered compare builtins are declared as "_Bool
4004 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004005 TheCall->setArg(0, OrigArg0.get());
4006 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004007
John Wiegley01296292011-04-08 18:41:53 +00004008 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004009 return false;
4010
Chris Lattner2da14fb2007-12-20 00:26:33 +00004011 // If the common type isn't a real floating type, then the arguments were
4012 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004013 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004014 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004015 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004016 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4017 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004018
Chris Lattner2da14fb2007-12-20 00:26:33 +00004019 return false;
4020}
4021
Benjamin Kramer634fc102010-02-15 22:42:31 +00004022/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4023/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004024/// to check everything. We expect the last argument to be a floating point
4025/// value.
4026bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4027 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004028 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004029 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004030 if (TheCall->getNumArgs() > NumArgs)
4031 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004032 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004033 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004034 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004035 (*(TheCall->arg_end()-1))->getLocEnd());
4036
Benjamin Kramer64aae502010-02-16 10:07:31 +00004037 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004038
Eli Friedman7e4faac2009-08-31 20:06:00 +00004039 if (OrigArg->isTypeDependent())
4040 return false;
4041
Chris Lattner68784ef2010-05-06 05:50:07 +00004042 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004043 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004044 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004045 diag::err_typecheck_call_invalid_unary_fp)
4046 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004047
Neil Hickey88c0fac2016-12-13 16:22:50 +00004048 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004049 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004050 // Only remove standard FloatCasts, leaving other casts inplace
4051 if (Cast->getCastKind() == CK_FloatingCast) {
4052 Expr *CastArg = Cast->getSubExpr();
4053 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4054 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4055 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4056 "promotion from float to either float or double is the only expected cast here");
4057 Cast->setSubExpr(nullptr);
4058 TheCall->setArg(NumArgs-1, CastArg);
4059 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004060 }
4061 }
4062
Eli Friedman7e4faac2009-08-31 20:06:00 +00004063 return false;
4064}
4065
Tony Jiangbbc48e92017-05-24 15:13:32 +00004066// Customized Sema Checking for VSX builtins that have the following signature:
4067// vector [...] builtinName(vector [...], vector [...], const int);
4068// Which takes the same type of vectors (any legal vector type) for the first
4069// two arguments and takes compile time constant for the third argument.
4070// Example builtins are :
4071// vector double vec_xxpermdi(vector double, vector double, int);
4072// vector short vec_xxsldwi(vector short, vector short, int);
4073bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4074 unsigned ExpectedNumArgs = 3;
4075 if (TheCall->getNumArgs() < ExpectedNumArgs)
4076 return Diag(TheCall->getLocEnd(),
4077 diag::err_typecheck_call_too_few_args_at_least)
4078 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4079 << TheCall->getSourceRange();
4080
4081 if (TheCall->getNumArgs() > ExpectedNumArgs)
4082 return Diag(TheCall->getLocEnd(),
4083 diag::err_typecheck_call_too_many_args_at_most)
4084 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4085 << TheCall->getSourceRange();
4086
4087 // Check the third argument is a compile time constant
4088 llvm::APSInt Value;
4089 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4090 return Diag(TheCall->getLocStart(),
4091 diag::err_vsx_builtin_nonconstant_argument)
4092 << 3 /* argument index */ << TheCall->getDirectCallee()
4093 << SourceRange(TheCall->getArg(2)->getLocStart(),
4094 TheCall->getArg(2)->getLocEnd());
4095
4096 QualType Arg1Ty = TheCall->getArg(0)->getType();
4097 QualType Arg2Ty = TheCall->getArg(1)->getType();
4098
4099 // Check the type of argument 1 and argument 2 are vectors.
4100 SourceLocation BuiltinLoc = TheCall->getLocStart();
4101 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4102 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4103 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4104 << TheCall->getDirectCallee()
4105 << SourceRange(TheCall->getArg(0)->getLocStart(),
4106 TheCall->getArg(1)->getLocEnd());
4107 }
4108
4109 // Check the first two arguments are the same type.
4110 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4111 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4112 << TheCall->getDirectCallee()
4113 << SourceRange(TheCall->getArg(0)->getLocStart(),
4114 TheCall->getArg(1)->getLocEnd());
4115 }
4116
4117 // When default clang type checking is turned off and the customized type
4118 // checking is used, the returning type of the function must be explicitly
4119 // set. Otherwise it is _Bool by default.
4120 TheCall->setType(Arg1Ty);
4121
4122 return false;
4123}
4124
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004125/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4126// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004127ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004128 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004129 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004130 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004131 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4132 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004133
Nate Begemana0110022010-06-08 00:16:34 +00004134 // Determine which of the following types of shufflevector we're checking:
4135 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004136 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004137 QualType resType = TheCall->getArg(0)->getType();
4138 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004139
Douglas Gregorc25f7662009-05-19 22:10:17 +00004140 if (!TheCall->getArg(0)->isTypeDependent() &&
4141 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004142 QualType LHSType = TheCall->getArg(0)->getType();
4143 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004144
Craig Topperbaca3892013-07-29 06:47:04 +00004145 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4146 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004147 diag::err_vec_builtin_non_vector)
4148 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004149 << SourceRange(TheCall->getArg(0)->getLocStart(),
4150 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004151
Nate Begemana0110022010-06-08 00:16:34 +00004152 numElements = LHSType->getAs<VectorType>()->getNumElements();
4153 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004154
Nate Begemana0110022010-06-08 00:16:34 +00004155 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4156 // with mask. If so, verify that RHS is an integer vector type with the
4157 // same number of elts as lhs.
4158 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004159 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004160 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004161 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004162 diag::err_vec_builtin_incompatible_vector)
4163 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004164 << SourceRange(TheCall->getArg(1)->getLocStart(),
4165 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004166 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004167 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004168 diag::err_vec_builtin_incompatible_vector)
4169 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004170 << SourceRange(TheCall->getArg(0)->getLocStart(),
4171 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004172 } else if (numElements != numResElements) {
4173 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004174 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004175 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004176 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004177 }
4178
4179 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004180 if (TheCall->getArg(i)->isTypeDependent() ||
4181 TheCall->getArg(i)->isValueDependent())
4182 continue;
4183
Nate Begemana0110022010-06-08 00:16:34 +00004184 llvm::APSInt Result(32);
4185 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4186 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004187 diag::err_shufflevector_nonconstant_argument)
4188 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004189
Craig Topper50ad5b72013-08-03 17:40:38 +00004190 // Allow -1 which will be translated to undef in the IR.
4191 if (Result.isSigned() && Result.isAllOnesValue())
4192 continue;
4193
Chris Lattner7ab824e2008-08-10 02:05:13 +00004194 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004195 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004196 diag::err_shufflevector_argument_too_large)
4197 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004198 }
4199
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004200 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004201
Chris Lattner7ab824e2008-08-10 02:05:13 +00004202 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004203 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004204 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004205 }
4206
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004207 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4208 TheCall->getCallee()->getLocStart(),
4209 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004210}
Chris Lattner43be2e62007-12-19 23:59:04 +00004211
Hal Finkelc4d7c822013-09-18 03:29:45 +00004212/// SemaConvertVectorExpr - Handle __builtin_convertvector
4213ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4214 SourceLocation BuiltinLoc,
4215 SourceLocation RParenLoc) {
4216 ExprValueKind VK = VK_RValue;
4217 ExprObjectKind OK = OK_Ordinary;
4218 QualType DstTy = TInfo->getType();
4219 QualType SrcTy = E->getType();
4220
4221 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4222 return ExprError(Diag(BuiltinLoc,
4223 diag::err_convertvector_non_vector)
4224 << E->getSourceRange());
4225 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4226 return ExprError(Diag(BuiltinLoc,
4227 diag::err_convertvector_non_vector_type));
4228
4229 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4230 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4231 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4232 if (SrcElts != DstElts)
4233 return ExprError(Diag(BuiltinLoc,
4234 diag::err_convertvector_incompatible_vector)
4235 << E->getSourceRange());
4236 }
4237
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004238 return new (Context)
4239 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004240}
4241
Daniel Dunbarb7257262008-07-21 22:59:13 +00004242/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4243// This is declared to take (const void*, ...) and can take two
4244// optional constant int args.
4245bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004246 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004247
Chris Lattner3b054132008-11-19 05:08:23 +00004248 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004249 return Diag(TheCall->getLocEnd(),
4250 diag::err_typecheck_call_too_many_args_at_most)
4251 << 0 /*function call*/ << 3 << NumArgs
4252 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004253
4254 // Argument 0 is checked for us and the remaining arguments must be
4255 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004256 for (unsigned i = 1; i != NumArgs; ++i)
4257 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004258 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004259
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004260 return false;
4261}
4262
Hal Finkelf0417332014-07-17 14:25:55 +00004263/// SemaBuiltinAssume - Handle __assume (MS Extension).
4264// __assume does not evaluate its arguments, and should warn if its argument
4265// has side effects.
4266bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4267 Expr *Arg = TheCall->getArg(0);
4268 if (Arg->isInstantiationDependent()) return false;
4269
4270 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004271 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004272 << Arg->getSourceRange()
4273 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4274
4275 return false;
4276}
4277
David Majnemer86b1bfa2016-10-31 18:07:57 +00004278/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004279/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4280/// than 8.
4281bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4282 // The alignment must be a constant integer.
4283 Expr *Arg = TheCall->getArg(1);
4284
4285 // We can't check the value of a dependent argument.
4286 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004287 if (const auto *UE =
4288 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4289 if (UE->getKind() == UETT_AlignOf)
4290 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4291 << Arg->getSourceRange();
4292
David Majnemer51169932016-10-31 05:37:48 +00004293 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4294
4295 if (!Result.isPowerOf2())
4296 return Diag(TheCall->getLocStart(),
4297 diag::err_alignment_not_power_of_two)
4298 << Arg->getSourceRange();
4299
4300 if (Result < Context.getCharWidth())
4301 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4302 << (unsigned)Context.getCharWidth()
4303 << Arg->getSourceRange();
4304
4305 if (Result > INT32_MAX)
4306 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4307 << INT32_MAX
4308 << Arg->getSourceRange();
4309 }
4310
4311 return false;
4312}
4313
4314/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004315/// as (const void*, size_t, ...) and can take one optional constant int arg.
4316bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4317 unsigned NumArgs = TheCall->getNumArgs();
4318
4319 if (NumArgs > 3)
4320 return Diag(TheCall->getLocEnd(),
4321 diag::err_typecheck_call_too_many_args_at_most)
4322 << 0 /*function call*/ << 3 << NumArgs
4323 << TheCall->getSourceRange();
4324
4325 // The alignment must be a constant integer.
4326 Expr *Arg = TheCall->getArg(1);
4327
4328 // We can't check the value of a dependent argument.
4329 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4330 llvm::APSInt Result;
4331 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4332 return true;
4333
4334 if (!Result.isPowerOf2())
4335 return Diag(TheCall->getLocStart(),
4336 diag::err_alignment_not_power_of_two)
4337 << Arg->getSourceRange();
4338 }
4339
4340 if (NumArgs > 2) {
4341 ExprResult Arg(TheCall->getArg(2));
4342 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4343 Context.getSizeType(), false);
4344 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4345 if (Arg.isInvalid()) return true;
4346 TheCall->setArg(2, Arg.get());
4347 }
Hal Finkelf0417332014-07-17 14:25:55 +00004348
4349 return false;
4350}
4351
Mehdi Amini06d367c2016-10-24 20:39:34 +00004352bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4353 unsigned BuiltinID =
4354 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4355 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4356
4357 unsigned NumArgs = TheCall->getNumArgs();
4358 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4359 if (NumArgs < NumRequiredArgs) {
4360 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4361 << 0 /* function call */ << NumRequiredArgs << NumArgs
4362 << TheCall->getSourceRange();
4363 }
4364 if (NumArgs >= NumRequiredArgs + 0x100) {
4365 return Diag(TheCall->getLocEnd(),
4366 diag::err_typecheck_call_too_many_args_at_most)
4367 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4368 << TheCall->getSourceRange();
4369 }
4370 unsigned i = 0;
4371
4372 // For formatting call, check buffer arg.
4373 if (!IsSizeCall) {
4374 ExprResult Arg(TheCall->getArg(i));
4375 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4376 Context, Context.VoidPtrTy, false);
4377 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4378 if (Arg.isInvalid())
4379 return true;
4380 TheCall->setArg(i, Arg.get());
4381 i++;
4382 }
4383
4384 // Check string literal arg.
4385 unsigned FormatIdx = i;
4386 {
4387 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4388 if (Arg.isInvalid())
4389 return true;
4390 TheCall->setArg(i, Arg.get());
4391 i++;
4392 }
4393
4394 // Make sure variadic args are scalar.
4395 unsigned FirstDataArg = i;
4396 while (i < NumArgs) {
4397 ExprResult Arg = DefaultVariadicArgumentPromotion(
4398 TheCall->getArg(i), VariadicFunction, nullptr);
4399 if (Arg.isInvalid())
4400 return true;
4401 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4402 if (ArgSize.getQuantity() >= 0x100) {
4403 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4404 << i << (int)ArgSize.getQuantity() << 0xff
4405 << TheCall->getSourceRange();
4406 }
4407 TheCall->setArg(i, Arg.get());
4408 i++;
4409 }
4410
4411 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4412 // call to avoid duplicate diagnostics.
4413 if (!IsSizeCall) {
4414 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4415 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4416 bool Success = CheckFormatArguments(
4417 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4418 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4419 CheckedVarArgs);
4420 if (!Success)
4421 return true;
4422 }
4423
4424 if (IsSizeCall) {
4425 TheCall->setType(Context.getSizeType());
4426 } else {
4427 TheCall->setType(Context.VoidPtrTy);
4428 }
4429 return false;
4430}
4431
Eric Christopher8d0c6212010-04-17 02:26:23 +00004432/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4433/// TheCall is a constant expression.
4434bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4435 llvm::APSInt &Result) {
4436 Expr *Arg = TheCall->getArg(ArgNum);
4437 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4438 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4439
4440 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4441
4442 if (!Arg->isIntegerConstantExpr(Result, Context))
4443 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004444 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004445
Chris Lattnerd545ad12009-09-23 06:06:36 +00004446 return false;
4447}
4448
Richard Sandiford28940af2014-04-16 08:47:51 +00004449/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4450/// TheCall is a constant expression in the range [Low, High].
4451bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4452 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004453 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004454
4455 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004456 Expr *Arg = TheCall->getArg(ArgNum);
4457 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004458 return false;
4459
Eric Christopher8d0c6212010-04-17 02:26:23 +00004460 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004461 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004462 return true;
4463
Richard Sandiford28940af2014-04-16 08:47:51 +00004464 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004465 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004466 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004467
4468 return false;
4469}
4470
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004471/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4472/// TheCall is a constant expression is a multiple of Num..
4473bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4474 unsigned Num) {
4475 llvm::APSInt Result;
4476
4477 // We can't check the value of a dependent argument.
4478 Expr *Arg = TheCall->getArg(ArgNum);
4479 if (Arg->isTypeDependent() || Arg->isValueDependent())
4480 return false;
4481
4482 // Check constant-ness first.
4483 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4484 return true;
4485
4486 if (Result.getSExtValue() % Num != 0)
4487 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4488 << Num << Arg->getSourceRange();
4489
4490 return false;
4491}
4492
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004493/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4494/// TheCall is an ARM/AArch64 special register string literal.
4495bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4496 int ArgNum, unsigned ExpectedFieldNum,
4497 bool AllowName) {
4498 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4499 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4500 BuiltinID == ARM::BI__builtin_arm_rsr ||
4501 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4502 BuiltinID == ARM::BI__builtin_arm_wsr ||
4503 BuiltinID == ARM::BI__builtin_arm_wsrp;
4504 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4505 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4506 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4507 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4508 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4509 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4510 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4511
4512 // We can't check the value of a dependent argument.
4513 Expr *Arg = TheCall->getArg(ArgNum);
4514 if (Arg->isTypeDependent() || Arg->isValueDependent())
4515 return false;
4516
4517 // Check if the argument is a string literal.
4518 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4519 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4520 << Arg->getSourceRange();
4521
4522 // Check the type of special register given.
4523 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4524 SmallVector<StringRef, 6> Fields;
4525 Reg.split(Fields, ":");
4526
4527 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4528 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4529 << Arg->getSourceRange();
4530
4531 // If the string is the name of a register then we cannot check that it is
4532 // valid here but if the string is of one the forms described in ACLE then we
4533 // can check that the supplied fields are integers and within the valid
4534 // ranges.
4535 if (Fields.size() > 1) {
4536 bool FiveFields = Fields.size() == 5;
4537
4538 bool ValidString = true;
4539 if (IsARMBuiltin) {
4540 ValidString &= Fields[0].startswith_lower("cp") ||
4541 Fields[0].startswith_lower("p");
4542 if (ValidString)
4543 Fields[0] =
4544 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4545
4546 ValidString &= Fields[2].startswith_lower("c");
4547 if (ValidString)
4548 Fields[2] = Fields[2].drop_front(1);
4549
4550 if (FiveFields) {
4551 ValidString &= Fields[3].startswith_lower("c");
4552 if (ValidString)
4553 Fields[3] = Fields[3].drop_front(1);
4554 }
4555 }
4556
4557 SmallVector<int, 5> Ranges;
4558 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004559 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004560 else
4561 Ranges.append({15, 7, 15});
4562
4563 for (unsigned i=0; i<Fields.size(); ++i) {
4564 int IntField;
4565 ValidString &= !Fields[i].getAsInteger(10, IntField);
4566 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4567 }
4568
4569 if (!ValidString)
4570 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4571 << Arg->getSourceRange();
4572
4573 } else if (IsAArch64Builtin && Fields.size() == 1) {
4574 // If the register name is one of those that appear in the condition below
4575 // and the special register builtin being used is one of the write builtins,
4576 // then we require that the argument provided for writing to the register
4577 // is an integer constant expression. This is because it will be lowered to
4578 // an MSR (immediate) instruction, so we need to know the immediate at
4579 // compile time.
4580 if (TheCall->getNumArgs() != 2)
4581 return false;
4582
4583 std::string RegLower = Reg.lower();
4584 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4585 RegLower != "pan" && RegLower != "uao")
4586 return false;
4587
4588 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4589 }
4590
4591 return false;
4592}
4593
Eli Friedmanc97d0142009-05-03 06:04:26 +00004594/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004595/// This checks that the target supports __builtin_longjmp and
4596/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004597bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004598 if (!Context.getTargetInfo().hasSjLjLowering())
4599 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4600 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4601
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004602 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004603 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004604
Eric Christopher8d0c6212010-04-17 02:26:23 +00004605 // TODO: This is less than ideal. Overload this to take a value.
4606 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4607 return true;
4608
4609 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004610 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4611 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4612
4613 return false;
4614}
4615
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004616/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4617/// This checks that the target supports __builtin_setjmp.
4618bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4619 if (!Context.getTargetInfo().hasSjLjLowering())
4620 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4621 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4622 return false;
4623}
4624
Richard Smithd7293d72013-08-05 18:49:43 +00004625namespace {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004626class UncoveredArgHandler {
4627 enum { Unknown = -1, AllCovered = -2 };
4628 signed FirstUncoveredArg;
4629 SmallVector<const Expr *, 4> DiagnosticExprs;
4630
4631public:
4632 UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4633
4634 bool hasUncoveredArg() const {
4635 return (FirstUncoveredArg >= 0);
4636 }
4637
4638 unsigned getUncoveredArg() const {
4639 assert(hasUncoveredArg() && "no uncovered argument");
4640 return FirstUncoveredArg;
4641 }
4642
4643 void setAllCovered() {
4644 // A string has been found with all arguments covered, so clear out
4645 // the diagnostics.
4646 DiagnosticExprs.clear();
4647 FirstUncoveredArg = AllCovered;
4648 }
4649
4650 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4651 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4652
4653 // Don't update if a previous string covers all arguments.
4654 if (FirstUncoveredArg == AllCovered)
4655 return;
4656
4657 // UncoveredArgHandler tracks the highest uncovered argument index
4658 // and with it all the strings that match this index.
4659 if (NewFirstUncoveredArg == FirstUncoveredArg)
4660 DiagnosticExprs.push_back(StrExpr);
4661 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4662 DiagnosticExprs.clear();
4663 DiagnosticExprs.push_back(StrExpr);
4664 FirstUncoveredArg = NewFirstUncoveredArg;
4665 }
4666 }
4667
4668 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4669};
4670
Richard Smithd7293d72013-08-05 18:49:43 +00004671enum StringLiteralCheckType {
4672 SLCT_NotALiteral,
4673 SLCT_UncheckedLiteral,
4674 SLCT_CheckedLiteral
4675};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004676} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004677
Stephen Hines648c3692016-09-16 01:07:04 +00004678static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4679 BinaryOperatorKind BinOpKind,
4680 bool AddendIsRight) {
4681 unsigned BitWidth = Offset.getBitWidth();
4682 unsigned AddendBitWidth = Addend.getBitWidth();
4683 // There might be negative interim results.
4684 if (Addend.isUnsigned()) {
4685 Addend = Addend.zext(++AddendBitWidth);
4686 Addend.setIsSigned(true);
4687 }
4688 // Adjust the bit width of the APSInts.
4689 if (AddendBitWidth > BitWidth) {
4690 Offset = Offset.sext(AddendBitWidth);
4691 BitWidth = AddendBitWidth;
4692 } else if (BitWidth > AddendBitWidth) {
4693 Addend = Addend.sext(BitWidth);
4694 }
4695
4696 bool Ov = false;
4697 llvm::APSInt ResOffset = Offset;
4698 if (BinOpKind == BO_Add)
4699 ResOffset = Offset.sadd_ov(Addend, Ov);
4700 else {
4701 assert(AddendIsRight && BinOpKind == BO_Sub &&
4702 "operator must be add or sub with addend on the right");
4703 ResOffset = Offset.ssub_ov(Addend, Ov);
4704 }
4705
4706 // We add an offset to a pointer here so we should support an offset as big as
4707 // possible.
4708 if (Ov) {
4709 assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004710 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004711 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4712 return;
4713 }
4714
4715 Offset = ResOffset;
4716}
4717
4718namespace {
4719// This is a wrapper class around StringLiteral to support offsetted string
4720// literals as format strings. It takes the offset into account when returning
4721// the string and its length or the source locations to display notes correctly.
4722class FormatStringLiteral {
4723 const StringLiteral *FExpr;
4724 int64_t Offset;
4725
4726 public:
4727 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4728 : FExpr(fexpr), Offset(Offset) {}
4729
4730 StringRef getString() const {
4731 return FExpr->getString().drop_front(Offset);
4732 }
4733
4734 unsigned getByteLength() const {
4735 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4736 }
4737 unsigned getLength() const { return FExpr->getLength() - Offset; }
4738 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4739
4740 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4741
4742 QualType getType() const { return FExpr->getType(); }
4743
4744 bool isAscii() const { return FExpr->isAscii(); }
4745 bool isWide() const { return FExpr->isWide(); }
4746 bool isUTF8() const { return FExpr->isUTF8(); }
4747 bool isUTF16() const { return FExpr->isUTF16(); }
4748 bool isUTF32() const { return FExpr->isUTF32(); }
4749 bool isPascal() const { return FExpr->isPascal(); }
4750
4751 SourceLocation getLocationOfByte(
4752 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4753 const TargetInfo &Target, unsigned *StartToken = nullptr,
4754 unsigned *StartTokenByteOffset = nullptr) const {
4755 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4756 StartToken, StartTokenByteOffset);
4757 }
4758
4759 SourceLocation getLocStart() const LLVM_READONLY {
4760 return FExpr->getLocStart().getLocWithOffset(Offset);
4761 }
4762 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4763};
4764} // end anonymous namespace
4765
4766static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004767 const Expr *OrigFormatExpr,
4768 ArrayRef<const Expr *> Args,
4769 bool HasVAListArg, unsigned format_idx,
4770 unsigned firstDataArg,
4771 Sema::FormatStringType Type,
4772 bool inFunctionCall,
4773 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004774 llvm::SmallBitVector &CheckedVarArgs,
4775 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004776
Richard Smith55ce3522012-06-25 20:30:08 +00004777// Determine if an expression is a string literal or constant string.
4778// If this function returns false on the arguments to a function expecting a
4779// format string, we will usually need to emit a warning.
4780// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004781static StringLiteralCheckType
4782checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4783 bool HasVAListArg, unsigned format_idx,
4784 unsigned firstDataArg, Sema::FormatStringType Type,
4785 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004786 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004787 UncoveredArgHandler &UncoveredArg,
4788 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004789 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004790 assert(Offset.isSigned() && "invalid offset");
4791
Douglas Gregorc25f7662009-05-19 22:10:17 +00004792 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004793 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004794
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004795 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004796
Richard Smithd7293d72013-08-05 18:49:43 +00004797 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004798 // Technically -Wformat-nonliteral does not warn about this case.
4799 // The behavior of printf and friends in this case is implementation
4800 // dependent. Ideally if the format string cannot be null then
4801 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004802 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004803
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004804 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004805 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004806 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004807 // The expression is a literal if both sub-expressions were, and it was
4808 // completely checked only if both sub-expressions were checked.
4809 const AbstractConditionalOperator *C =
4810 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004811
4812 // Determine whether it is necessary to check both sub-expressions, for
4813 // example, because the condition expression is a constant that can be
4814 // evaluated at compile time.
4815 bool CheckLeft = true, CheckRight = true;
4816
4817 bool Cond;
4818 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4819 if (Cond)
4820 CheckRight = false;
4821 else
4822 CheckLeft = false;
4823 }
4824
Stephen Hines648c3692016-09-16 01:07:04 +00004825 // We need to maintain the offsets for the right and the left hand side
4826 // separately to check if every possible indexed expression is a valid
4827 // string literal. They might have different offsets for different string
4828 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004829 StringLiteralCheckType Left;
4830 if (!CheckLeft)
4831 Left = SLCT_UncheckedLiteral;
4832 else {
4833 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4834 HasVAListArg, format_idx, firstDataArg,
4835 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004836 CheckedVarArgs, UncoveredArg, Offset);
4837 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004838 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004839 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004840 }
4841
Richard Smith55ce3522012-06-25 20:30:08 +00004842 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004843 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004844 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004845 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004846 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004847
4848 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004849 }
4850
4851 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00004852 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4853 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004854 }
4855
John McCallc07a0c72011-02-17 10:25:35 +00004856 case Stmt::OpaqueValueExprClass:
4857 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4858 E = src;
4859 goto tryAgain;
4860 }
Richard Smith55ce3522012-06-25 20:30:08 +00004861 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004862
Ted Kremeneka8890832011-02-24 23:03:04 +00004863 case Stmt::PredefinedExprClass:
4864 // While __func__, etc., are technically not string literals, they
4865 // cannot contain format specifiers and thus are not a security
4866 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004867 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004868
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004869 case Stmt::DeclRefExprClass: {
4870 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004871
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004872 // As an exception, do not flag errors for variables binding to
4873 // const string literals.
4874 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4875 bool isConstant = false;
4876 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004877
Richard Smithd7293d72013-08-05 18:49:43 +00004878 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4879 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004880 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004881 isConstant = T.isConstant(S.Context) &&
4882 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004883 } else if (T->isObjCObjectPointerType()) {
4884 // In ObjC, there is usually no "const ObjectPointer" type,
4885 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004886 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004887 }
Mike Stump11289f42009-09-09 15:08:12 +00004888
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004889 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004890 if (const Expr *Init = VD->getAnyInitializer()) {
4891 // Look through initializers like const char c[] = { "foo" }
4892 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4893 if (InitList->isStringLiteralInit())
4894 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4895 }
Richard Smithd7293d72013-08-05 18:49:43 +00004896 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004897 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004898 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004899 /*InFunctionCall*/ false, CheckedVarArgs,
4900 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004901 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004902 }
Mike Stump11289f42009-09-09 15:08:12 +00004903
Anders Carlssonb012ca92009-06-28 19:55:58 +00004904 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4905 // special check to see if the format string is a function parameter
4906 // of the function calling the printf function. If the function
4907 // has an attribute indicating it is a printf-like function, then we
4908 // should suppress warnings concerning non-literals being used in a call
4909 // to a vprintf function. For example:
4910 //
4911 // void
4912 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4913 // va_list ap;
4914 // va_start(ap, fmt);
4915 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4916 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004917 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004918 if (HasVAListArg) {
4919 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4920 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4921 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004922 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004923 // adjust for implicit parameter
4924 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4925 if (MD->isInstance())
4926 ++PVIndex;
4927 // We also check if the formats are compatible.
4928 // We can't pass a 'scanf' string to a 'printf' function.
4929 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00004930 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00004931 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004932 }
4933 }
4934 }
4935 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004936 }
Mike Stump11289f42009-09-09 15:08:12 +00004937
Richard Smith55ce3522012-06-25 20:30:08 +00004938 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004939 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004940
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004941 case Stmt::CallExprClass:
4942 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004943 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00004944 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4945 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4946 unsigned ArgIndex = FA->getFormatIdx();
4947 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4948 if (MD->isInstance())
4949 --ArgIndex;
4950 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00004951
Richard Smithd7293d72013-08-05 18:49:43 +00004952 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004953 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00004954 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004955 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004956 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4957 unsigned BuiltinID = FD->getBuiltinID();
4958 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4959 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4960 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00004961 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004962 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004963 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004964 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004965 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004966 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004967 }
4968 }
Mike Stump11289f42009-09-09 15:08:12 +00004969
Richard Smith55ce3522012-06-25 20:30:08 +00004970 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00004971 }
Alex Lorenzd9007142016-10-24 09:42:34 +00004972 case Stmt::ObjCMessageExprClass: {
4973 const auto *ME = cast<ObjCMessageExpr>(E);
4974 if (const auto *ND = ME->getMethodDecl()) {
4975 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4976 unsigned ArgIndex = FA->getFormatIdx();
4977 const Expr *Arg = ME->getArg(ArgIndex - 1);
4978 return checkFormatStringExpr(
4979 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4980 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4981 }
4982 }
4983
4984 return SLCT_NotALiteral;
4985 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004986 case Stmt::ObjCStringLiteralClass:
4987 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00004988 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004989
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004990 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004991 StrE = ObjCFExpr->getString();
4992 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004993 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004994
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004995 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00004996 if (Offset.isNegative() || Offset > StrE->getLength()) {
4997 // TODO: It would be better to have an explicit warning for out of
4998 // bounds literals.
4999 return SLCT_NotALiteral;
5000 }
5001 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5002 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005003 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005004 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005005 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005006 }
Mike Stump11289f42009-09-09 15:08:12 +00005007
Richard Smith55ce3522012-06-25 20:30:08 +00005008 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005009 }
Stephen Hines648c3692016-09-16 01:07:04 +00005010 case Stmt::BinaryOperatorClass: {
5011 llvm::APSInt LResult;
5012 llvm::APSInt RResult;
5013
5014 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5015
5016 // A string literal + an int offset is still a string literal.
5017 if (BinOp->isAdditiveOp()) {
5018 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5019 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5020
5021 if (LIsInt != RIsInt) {
5022 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5023
5024 if (LIsInt) {
5025 if (BinOpKind == BO_Add) {
5026 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5027 E = BinOp->getRHS();
5028 goto tryAgain;
5029 }
5030 } else {
5031 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5032 E = BinOp->getLHS();
5033 goto tryAgain;
5034 }
5035 }
Stephen Hines648c3692016-09-16 01:07:04 +00005036 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005037
5038 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005039 }
5040 case Stmt::UnaryOperatorClass: {
5041 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5042 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5043 if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5044 llvm::APSInt IndexResult;
5045 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5046 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5047 E = ASE->getBase();
5048 goto tryAgain;
5049 }
5050 }
5051
5052 return SLCT_NotALiteral;
5053 }
Mike Stump11289f42009-09-09 15:08:12 +00005054
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005055 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005056 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005057 }
5058}
5059
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005060Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005061 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005062 .Case("scanf", FST_Scanf)
5063 .Cases("printf", "printf0", FST_Printf)
5064 .Cases("NSString", "CFString", FST_NSString)
5065 .Case("strftime", FST_Strftime)
5066 .Case("strfmon", FST_Strfmon)
5067 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5068 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5069 .Case("os_trace", FST_OSLog)
5070 .Case("os_log", FST_OSLog)
5071 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005072}
5073
Jordan Rose3e0ec582012-07-19 18:10:23 +00005074/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005075/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005076/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005077bool Sema::CheckFormatArguments(const FormatAttr *Format,
5078 ArrayRef<const Expr *> Args,
5079 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005080 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005081 SourceLocation Loc, SourceRange Range,
5082 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005083 FormatStringInfo FSI;
5084 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005085 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005086 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005087 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005088 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005089}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005090
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005091bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005092 bool HasVAListArg, unsigned format_idx,
5093 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005094 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005095 SourceLocation Loc, SourceRange Range,
5096 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005097 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005098 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005099 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005100 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005101 }
Mike Stump11289f42009-09-09 15:08:12 +00005102
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005103 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005104
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005105 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005106 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005107 // Dynamically generated format strings are difficult to
5108 // automatically vet at compile time. Requiring that format strings
5109 // are string literals: (1) permits the checking of format strings by
5110 // the compiler and thereby (2) can practically remove the source of
5111 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005112
Mike Stump11289f42009-09-09 15:08:12 +00005113 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005114 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005115 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005116 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005117 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005118 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005119 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5120 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005121 /*IsFunctionCall*/ true, CheckedVarArgs,
5122 UncoveredArg,
5123 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005124
5125 // Generate a diagnostic where an uncovered argument is detected.
5126 if (UncoveredArg.hasUncoveredArg()) {
5127 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5128 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5129 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5130 }
5131
Richard Smith55ce3522012-06-25 20:30:08 +00005132 if (CT != SLCT_NotALiteral)
5133 // Literal format string found, check done!
5134 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005135
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005136 // Strftime is particular as it always uses a single 'time' argument,
5137 // so it is safe to pass a non-literal string.
5138 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005139 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005140
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005141 // Do not emit diag when the string param is a macro expansion and the
5142 // format is either NSString or CFString. This is a hack to prevent
5143 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5144 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005145 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5146 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005147 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005148
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005149 // If there are no arguments specified, warn with -Wformat-security, otherwise
5150 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005151 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005152 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5153 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005154 switch (Type) {
5155 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005156 break;
5157 case FST_Kprintf:
5158 case FST_FreeBSDKPrintf:
5159 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005160 Diag(FormatLoc, diag::note_format_security_fixit)
5161 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005162 break;
5163 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005164 Diag(FormatLoc, diag::note_format_security_fixit)
5165 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005166 break;
5167 }
5168 } else {
5169 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005170 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005171 }
Richard Smith55ce3522012-06-25 20:30:08 +00005172 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005173}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005174
Ted Kremenekab278de2010-01-28 23:39:18 +00005175namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00005176class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5177protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005178 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005179 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005180 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005181 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005182 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005183 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005184 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005185 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005186 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005187 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005188 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00005189 bool usesPositionalArgs;
5190 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005191 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005192 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005193 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005194 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005195
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005196public:
Stephen Hines648c3692016-09-16 01:07:04 +00005197 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005198 const Expr *origFormatExpr,
5199 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005200 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005201 ArrayRef<const Expr *> Args, unsigned formatIdx,
5202 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005203 llvm::SmallBitVector &CheckedVarArgs,
5204 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005205 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5206 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5207 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5208 usesPositionalArgs(false), atFirstArg(true),
5209 inFunctionCall(inFunctionCall), CallType(callType),
5210 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005211 CoveredArgs.resize(numDataArgs);
5212 CoveredArgs.reset();
5213 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005214
Ted Kremenek019d2242010-01-29 01:50:07 +00005215 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005216
Ted Kremenek02087932010-07-16 02:11:22 +00005217 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005218 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005219
Jordan Rose92303592012-09-08 04:00:03 +00005220 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005221 const analyze_format_string::FormatSpecifier &FS,
5222 const analyze_format_string::ConversionSpecifier &CS,
5223 const char *startSpecifier, unsigned specifierLen,
5224 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005225
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005226 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005227 const analyze_format_string::FormatSpecifier &FS,
5228 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005229
5230 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005231 const analyze_format_string::ConversionSpecifier &CS,
5232 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005233
Craig Toppere14c0f82014-03-12 04:55:44 +00005234 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005235
Craig Toppere14c0f82014-03-12 04:55:44 +00005236 void HandleInvalidPosition(const char *startSpecifier,
5237 unsigned specifierLen,
5238 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005239
Craig Toppere14c0f82014-03-12 04:55:44 +00005240 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005241
Craig Toppere14c0f82014-03-12 04:55:44 +00005242 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005243
Richard Trieu03cf7b72011-10-28 00:41:25 +00005244 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005245 static void
5246 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5247 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5248 bool IsStringLocation, Range StringRange,
5249 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005250
Ted Kremenek02087932010-07-16 02:11:22 +00005251protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005252 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5253 const char *startSpec,
5254 unsigned specifierLen,
5255 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005256
5257 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5258 const char *startSpec,
5259 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005260
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005261 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005262 CharSourceRange getSpecifierRange(const char *startSpecifier,
5263 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005264 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005265
Ted Kremenek5739de72010-01-29 01:06:55 +00005266 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005267
5268 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5269 const analyze_format_string::ConversionSpecifier &CS,
5270 const char *startSpecifier, unsigned specifierLen,
5271 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005272
5273 template <typename Range>
5274 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5275 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005276 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005277};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005278} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005279
Ted Kremenek02087932010-07-16 02:11:22 +00005280SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005281 return OrigFormatExpr->getSourceRange();
5282}
5283
Ted Kremenek02087932010-07-16 02:11:22 +00005284CharSourceRange CheckFormatHandler::
5285getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005286 SourceLocation Start = getLocationOfByte(startSpecifier);
5287 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5288
5289 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005290 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005291
5292 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005293}
5294
Ted Kremenek02087932010-07-16 02:11:22 +00005295SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005296 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5297 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005298}
5299
Ted Kremenek02087932010-07-16 02:11:22 +00005300void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5301 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005302 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5303 getLocationOfByte(startSpecifier),
5304 /*IsStringLocation*/true,
5305 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005306}
5307
Jordan Rose92303592012-09-08 04:00:03 +00005308void CheckFormatHandler::HandleInvalidLengthModifier(
5309 const analyze_format_string::FormatSpecifier &FS,
5310 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005311 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005312 using namespace analyze_format_string;
5313
5314 const LengthModifier &LM = FS.getLengthModifier();
5315 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5316
5317 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005318 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005319 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005320 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005321 getLocationOfByte(LM.getStart()),
5322 /*IsStringLocation*/true,
5323 getSpecifierRange(startSpecifier, specifierLen));
5324
5325 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5326 << FixedLM->toString()
5327 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5328
5329 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005330 FixItHint Hint;
5331 if (DiagID == diag::warn_format_nonsensical_length)
5332 Hint = FixItHint::CreateRemoval(LMRange);
5333
5334 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005335 getLocationOfByte(LM.getStart()),
5336 /*IsStringLocation*/true,
5337 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005338 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005339 }
5340}
5341
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005342void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005343 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005344 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005345 using namespace analyze_format_string;
5346
5347 const LengthModifier &LM = FS.getLengthModifier();
5348 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5349
5350 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005351 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005352 if (FixedLM) {
5353 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5354 << LM.toString() << 0,
5355 getLocationOfByte(LM.getStart()),
5356 /*IsStringLocation*/true,
5357 getSpecifierRange(startSpecifier, specifierLen));
5358
5359 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5360 << FixedLM->toString()
5361 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5362
5363 } else {
5364 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5365 << LM.toString() << 0,
5366 getLocationOfByte(LM.getStart()),
5367 /*IsStringLocation*/true,
5368 getSpecifierRange(startSpecifier, specifierLen));
5369 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005370}
5371
5372void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5373 const analyze_format_string::ConversionSpecifier &CS,
5374 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005375 using namespace analyze_format_string;
5376
5377 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005378 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005379 if (FixedCS) {
5380 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5381 << CS.toString() << /*conversion specifier*/1,
5382 getLocationOfByte(CS.getStart()),
5383 /*IsStringLocation*/true,
5384 getSpecifierRange(startSpecifier, specifierLen));
5385
5386 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5387 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5388 << FixedCS->toString()
5389 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5390 } else {
5391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5392 << CS.toString() << /*conversion specifier*/1,
5393 getLocationOfByte(CS.getStart()),
5394 /*IsStringLocation*/true,
5395 getSpecifierRange(startSpecifier, specifierLen));
5396 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005397}
5398
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005399void CheckFormatHandler::HandlePosition(const char *startPos,
5400 unsigned posLen) {
5401 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5402 getLocationOfByte(startPos),
5403 /*IsStringLocation*/true,
5404 getSpecifierRange(startPos, posLen));
5405}
5406
Ted Kremenekd1668192010-02-27 01:41:03 +00005407void
Ted Kremenek02087932010-07-16 02:11:22 +00005408CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5409 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005410 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5411 << (unsigned) p,
5412 getLocationOfByte(startPos), /*IsStringLocation*/true,
5413 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005414}
5415
Ted Kremenek02087932010-07-16 02:11:22 +00005416void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005417 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005418 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5419 getLocationOfByte(startPos),
5420 /*IsStringLocation*/true,
5421 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005422}
5423
Ted Kremenek02087932010-07-16 02:11:22 +00005424void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005425 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005426 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005427 EmitFormatDiagnostic(
5428 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5429 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5430 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005431 }
Ted Kremenek02087932010-07-16 02:11:22 +00005432}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005433
Jordan Rose58bbe422012-07-19 18:10:08 +00005434// Note that this may return NULL if there was an error parsing or building
5435// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005436const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005437 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005438}
5439
5440void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005441 // Does the number of data arguments exceed the number of
5442 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005443 if (!HasVAListArg) {
5444 // Find any arguments that weren't covered.
5445 CoveredArgs.flip();
5446 signed notCoveredArg = CoveredArgs.find_first();
5447 if (notCoveredArg >= 0) {
5448 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005449 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5450 } else {
5451 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005452 }
5453 }
5454}
5455
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005456void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5457 const Expr *ArgExpr) {
5458 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5459 "Invalid state");
5460
5461 if (!ArgExpr)
5462 return;
5463
5464 SourceLocation Loc = ArgExpr->getLocStart();
5465
5466 if (S.getSourceManager().isInSystemMacro(Loc))
5467 return;
5468
5469 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5470 for (auto E : DiagnosticExprs)
5471 PDiag << E->getSourceRange();
5472
5473 CheckFormatHandler::EmitFormatDiagnostic(
5474 S, IsFunctionCall, DiagnosticExprs[0],
5475 PDiag, Loc, /*IsStringLocation*/false,
5476 DiagnosticExprs[0]->getSourceRange());
5477}
5478
Ted Kremenekce815422010-07-19 21:25:57 +00005479bool
5480CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5481 SourceLocation Loc,
5482 const char *startSpec,
5483 unsigned specifierLen,
5484 const char *csStart,
5485 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005486 bool keepGoing = true;
5487 if (argIndex < NumDataArgs) {
5488 // Consider the argument coverered, even though the specifier doesn't
5489 // make sense.
5490 CoveredArgs.set(argIndex);
5491 }
5492 else {
5493 // If argIndex exceeds the number of data arguments we
5494 // don't issue a warning because that is just a cascade of warnings (and
5495 // they may have intended '%%' anyway). We don't want to continue processing
5496 // the format string after this point, however, as we will like just get
5497 // gibberish when trying to match arguments.
5498 keepGoing = false;
5499 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005500
5501 StringRef Specifier(csStart, csLen);
5502
5503 // If the specifier in non-printable, it could be the first byte of a UTF-8
5504 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5505 // hex value.
5506 std::string CodePointStr;
5507 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005508 llvm::UTF32 CodePoint;
5509 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5510 const llvm::UTF8 *E =
5511 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5512 llvm::ConversionResult Result =
5513 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005514
Justin Lebar90910552016-09-30 00:38:45 +00005515 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005516 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005517 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005518 }
5519
5520 llvm::raw_string_ostream OS(CodePointStr);
5521 if (CodePoint < 256)
5522 OS << "\\x" << llvm::format("%02x", CodePoint);
5523 else if (CodePoint <= 0xFFFF)
5524 OS << "\\u" << llvm::format("%04x", CodePoint);
5525 else
5526 OS << "\\U" << llvm::format("%08x", CodePoint);
5527 OS.flush();
5528 Specifier = CodePointStr;
5529 }
5530
5531 EmitFormatDiagnostic(
5532 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5533 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5534
Ted Kremenekce815422010-07-19 21:25:57 +00005535 return keepGoing;
5536}
5537
Richard Trieu03cf7b72011-10-28 00:41:25 +00005538void
5539CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5540 const char *startSpec,
5541 unsigned specifierLen) {
5542 EmitFormatDiagnostic(
5543 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5544 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5545}
5546
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005547bool
5548CheckFormatHandler::CheckNumArgs(
5549 const analyze_format_string::FormatSpecifier &FS,
5550 const analyze_format_string::ConversionSpecifier &CS,
5551 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5552
5553 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005554 PartialDiagnostic PDiag = FS.usesPositionalArg()
5555 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5556 << (argIndex+1) << NumDataArgs)
5557 : S.PDiag(diag::warn_printf_insufficient_data_args);
5558 EmitFormatDiagnostic(
5559 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5560 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005561
5562 // Since more arguments than conversion tokens are given, by extension
5563 // all arguments are covered, so mark this as so.
5564 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005565 return false;
5566 }
5567 return true;
5568}
5569
Richard Trieu03cf7b72011-10-28 00:41:25 +00005570template<typename Range>
5571void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5572 SourceLocation Loc,
5573 bool IsStringLocation,
5574 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005575 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005576 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005577 Loc, IsStringLocation, StringRange, FixIt);
5578}
5579
5580/// \brief If the format string is not within the funcion call, emit a note
5581/// so that the function call and string are in diagnostic messages.
5582///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005583/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005584/// call and only one diagnostic message will be produced. Otherwise, an
5585/// extra note will be emitted pointing to location of the format string.
5586///
5587/// \param ArgumentExpr the expression that is passed as the format string
5588/// argument in the function call. Used for getting locations when two
5589/// diagnostics are emitted.
5590///
5591/// \param PDiag the callee should already have provided any strings for the
5592/// diagnostic message. This function only adds locations and fixits
5593/// to diagnostics.
5594///
5595/// \param Loc primary location for diagnostic. If two diagnostics are
5596/// required, one will be at Loc and a new SourceLocation will be created for
5597/// the other one.
5598///
5599/// \param IsStringLocation if true, Loc points to the format string should be
5600/// used for the note. Otherwise, Loc points to the argument list and will
5601/// be used with PDiag.
5602///
5603/// \param StringRange some or all of the string to highlight. This is
5604/// templated so it can accept either a CharSourceRange or a SourceRange.
5605///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005606/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005607template <typename Range>
5608void CheckFormatHandler::EmitFormatDiagnostic(
5609 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5610 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5611 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005612 if (InFunctionCall) {
5613 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5614 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005615 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005616 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005617 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5618 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005619
5620 const Sema::SemaDiagnosticBuilder &Note =
5621 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5622 diag::note_format_string_defined);
5623
5624 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005625 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005626 }
5627}
5628
Ted Kremenek02087932010-07-16 02:11:22 +00005629//===--- CHECK: Printf format string checking ------------------------------===//
5630
5631namespace {
5632class CheckPrintfHandler : public CheckFormatHandler {
5633public:
Stephen Hines648c3692016-09-16 01:07:04 +00005634 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005635 const Expr *origFormatExpr,
5636 const Sema::FormatStringType type, unsigned firstDataArg,
5637 unsigned numDataArgs, bool isObjC, const char *beg,
5638 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005639 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005640 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005641 llvm::SmallBitVector &CheckedVarArgs,
5642 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005643 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5644 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5645 inFunctionCall, CallType, CheckedVarArgs,
5646 UncoveredArg) {}
5647
5648 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5649
5650 /// Returns true if '%@' specifiers are allowed in the format string.
5651 bool allowsObjCArg() const {
5652 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5653 FSType == Sema::FST_OSTrace;
5654 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005655
Ted Kremenek02087932010-07-16 02:11:22 +00005656 bool HandleInvalidPrintfConversionSpecifier(
5657 const analyze_printf::PrintfSpecifier &FS,
5658 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005659 unsigned specifierLen) override;
5660
Ted Kremenek02087932010-07-16 02:11:22 +00005661 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5662 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005663 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005664 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5665 const char *StartSpecifier,
5666 unsigned SpecifierLen,
5667 const Expr *E);
5668
Ted Kremenek02087932010-07-16 02:11:22 +00005669 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5670 const char *startSpecifier, unsigned specifierLen);
5671 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5672 const analyze_printf::OptionalAmount &Amt,
5673 unsigned type,
5674 const char *startSpecifier, unsigned specifierLen);
5675 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5676 const analyze_printf::OptionalFlag &flag,
5677 const char *startSpecifier, unsigned specifierLen);
5678 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5679 const analyze_printf::OptionalFlag &ignoredFlag,
5680 const analyze_printf::OptionalFlag &flag,
5681 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005682 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005683 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005684
5685 void HandleEmptyObjCModifierFlag(const char *startFlag,
5686 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005687
Ted Kremenek2b417712015-07-02 05:39:16 +00005688 void HandleInvalidObjCModifierFlag(const char *startFlag,
5689 unsigned flagLen) override;
5690
5691 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5692 const char *flagsEnd,
5693 const char *conversionPosition)
5694 override;
5695};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005696} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005697
5698bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5699 const analyze_printf::PrintfSpecifier &FS,
5700 const char *startSpecifier,
5701 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005702 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005703 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005704
Ted Kremenekce815422010-07-19 21:25:57 +00005705 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5706 getLocationOfByte(CS.getStart()),
5707 startSpecifier, specifierLen,
5708 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005709}
5710
Ted Kremenek02087932010-07-16 02:11:22 +00005711bool CheckPrintfHandler::HandleAmount(
5712 const analyze_format_string::OptionalAmount &Amt,
5713 unsigned k, const char *startSpecifier,
5714 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005715 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005716 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005717 unsigned argIndex = Amt.getArgIndex();
5718 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005719 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5720 << k,
5721 getLocationOfByte(Amt.getStart()),
5722 /*IsStringLocation*/true,
5723 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005724 // Don't do any more checking. We will just emit
5725 // spurious errors.
5726 return false;
5727 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005728
Ted Kremenek5739de72010-01-29 01:06:55 +00005729 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005730 // Although not in conformance with C99, we also allow the argument to be
5731 // an 'unsigned int' as that is a reasonably safe case. GCC also
5732 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005733 CoveredArgs.set(argIndex);
5734 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005735 if (!Arg)
5736 return false;
5737
Ted Kremenek5739de72010-01-29 01:06:55 +00005738 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005739
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005740 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5741 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005742
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005743 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005744 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005745 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005746 << T << Arg->getSourceRange(),
5747 getLocationOfByte(Amt.getStart()),
5748 /*IsStringLocation*/true,
5749 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005750 // Don't do any more checking. We will just emit
5751 // spurious errors.
5752 return false;
5753 }
5754 }
5755 }
5756 return true;
5757}
Ted Kremenek5739de72010-01-29 01:06:55 +00005758
Tom Careb49ec692010-06-17 19:00:27 +00005759void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005760 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005761 const analyze_printf::OptionalAmount &Amt,
5762 unsigned type,
5763 const char *startSpecifier,
5764 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005765 const analyze_printf::PrintfConversionSpecifier &CS =
5766 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005767
Richard Trieu03cf7b72011-10-28 00:41:25 +00005768 FixItHint fixit =
5769 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5770 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5771 Amt.getConstantLength()))
5772 : FixItHint();
5773
5774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5775 << type << CS.toString(),
5776 getLocationOfByte(Amt.getStart()),
5777 /*IsStringLocation*/true,
5778 getSpecifierRange(startSpecifier, specifierLen),
5779 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005780}
5781
Ted Kremenek02087932010-07-16 02:11:22 +00005782void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005783 const analyze_printf::OptionalFlag &flag,
5784 const char *startSpecifier,
5785 unsigned specifierLen) {
5786 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005787 const analyze_printf::PrintfConversionSpecifier &CS =
5788 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005789 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5790 << flag.toString() << CS.toString(),
5791 getLocationOfByte(flag.getPosition()),
5792 /*IsStringLocation*/true,
5793 getSpecifierRange(startSpecifier, specifierLen),
5794 FixItHint::CreateRemoval(
5795 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005796}
5797
5798void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005799 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005800 const analyze_printf::OptionalFlag &ignoredFlag,
5801 const analyze_printf::OptionalFlag &flag,
5802 const char *startSpecifier,
5803 unsigned specifierLen) {
5804 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005805 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5806 << ignoredFlag.toString() << flag.toString(),
5807 getLocationOfByte(ignoredFlag.getPosition()),
5808 /*IsStringLocation*/true,
5809 getSpecifierRange(startSpecifier, specifierLen),
5810 FixItHint::CreateRemoval(
5811 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005812}
5813
Ted Kremenek2b417712015-07-02 05:39:16 +00005814// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5815// bool IsStringLocation, Range StringRange,
5816// ArrayRef<FixItHint> Fixit = None);
5817
5818void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5819 unsigned flagLen) {
5820 // Warn about an empty flag.
5821 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5822 getLocationOfByte(startFlag),
5823 /*IsStringLocation*/true,
5824 getSpecifierRange(startFlag, flagLen));
5825}
5826
5827void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5828 unsigned flagLen) {
5829 // Warn about an invalid flag.
5830 auto Range = getSpecifierRange(startFlag, flagLen);
5831 StringRef flag(startFlag, flagLen);
5832 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5833 getLocationOfByte(startFlag),
5834 /*IsStringLocation*/true,
5835 Range, FixItHint::CreateRemoval(Range));
5836}
5837
5838void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5839 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5840 // Warn about using '[...]' without a '@' conversion.
5841 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5842 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5843 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5844 getLocationOfByte(conversionPosition),
5845 /*IsStringLocation*/true,
5846 Range, FixItHint::CreateRemoval(Range));
5847}
5848
Richard Smith55ce3522012-06-25 20:30:08 +00005849// Determines if the specified is a C++ class or struct containing
5850// a member with the specified name and kind (e.g. a CXXMethodDecl named
5851// "c_str()").
5852template<typename MemberKind>
5853static llvm::SmallPtrSet<MemberKind*, 1>
5854CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5855 const RecordType *RT = Ty->getAs<RecordType>();
5856 llvm::SmallPtrSet<MemberKind*, 1> Results;
5857
5858 if (!RT)
5859 return Results;
5860 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005861 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005862 return Results;
5863
Alp Tokerb6cc5922014-05-03 03:45:55 +00005864 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005865 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005866 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005867
5868 // We just need to include all members of the right kind turned up by the
5869 // filter, at this point.
5870 if (S.LookupQualifiedName(R, RT->getDecl()))
5871 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5872 NamedDecl *decl = (*I)->getUnderlyingDecl();
5873 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5874 Results.insert(FK);
5875 }
5876 return Results;
5877}
5878
Richard Smith2868a732014-02-28 01:36:39 +00005879/// Check if we could call '.c_str()' on an object.
5880///
5881/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5882/// allow the call, or if it would be ambiguous).
5883bool Sema::hasCStrMethod(const Expr *E) {
5884 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5885 MethodSet Results =
5886 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5887 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5888 MI != ME; ++MI)
5889 if ((*MI)->getMinRequiredArguments() == 0)
5890 return true;
5891 return false;
5892}
5893
Richard Smith55ce3522012-06-25 20:30:08 +00005894// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005895// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005896// Returns true when a c_str() conversion method is found.
5897bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005898 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00005899 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5900
5901 MethodSet Results =
5902 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5903
5904 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5905 MI != ME; ++MI) {
5906 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005907 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005908 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005909 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005910 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005911 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5912 << "c_str()"
5913 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5914 return true;
5915 }
5916 }
5917
5918 return false;
5919}
5920
Ted Kremenekab278de2010-01-28 23:39:18 +00005921bool
Ted Kremenek02087932010-07-16 02:11:22 +00005922CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005923 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00005924 const char *startSpecifier,
5925 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005926 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00005927 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005928 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00005929
Ted Kremenek6cd69422010-07-19 22:01:06 +00005930 if (FS.consumesDataArgument()) {
5931 if (atFirstArg) {
5932 atFirstArg = false;
5933 usesPositionalArgs = FS.usesPositionalArg();
5934 }
5935 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005936 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5937 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00005938 return false;
5939 }
Ted Kremenek5739de72010-01-29 01:06:55 +00005940 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005941
Ted Kremenekd1668192010-02-27 01:41:03 +00005942 // First check if the field width, precision, and conversion specifier
5943 // have matching data arguments.
5944 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5945 startSpecifier, specifierLen)) {
5946 return false;
5947 }
5948
5949 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5950 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005951 return false;
5952 }
5953
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005954 if (!CS.consumesDataArgument()) {
5955 // FIXME: Technically specifying a precision or field width here
5956 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00005957 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005958 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005959
Ted Kremenek4a49d982010-02-26 19:18:41 +00005960 // Consume the argument.
5961 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00005962 if (argIndex < NumDataArgs) {
5963 // The check to see if the argIndex is valid will come later.
5964 // We set the bit here because we may exit early from this
5965 // function if we encounter some other error.
5966 CoveredArgs.set(argIndex);
5967 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00005968
Dimitry Andric6b5ed342015-02-19 22:32:33 +00005969 // FreeBSD kernel extensions.
5970 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5971 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5972 // We need at least two arguments.
5973 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5974 return false;
5975
5976 // Claim the second argument.
5977 CoveredArgs.set(argIndex + 1);
5978
5979 // Type check the first argument (int for %b, pointer for %D)
5980 const Expr *Ex = getDataArg(argIndex);
5981 const analyze_printf::ArgType &AT =
5982 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5983 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5984 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5985 EmitFormatDiagnostic(
5986 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5987 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5988 << false << Ex->getSourceRange(),
5989 Ex->getLocStart(), /*IsStringLocation*/false,
5990 getSpecifierRange(startSpecifier, specifierLen));
5991
5992 // Type check the second argument (char * for both %b and %D)
5993 Ex = getDataArg(argIndex + 1);
5994 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5995 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5996 EmitFormatDiagnostic(
5997 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5998 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5999 << false << Ex->getSourceRange(),
6000 Ex->getLocStart(), /*IsStringLocation*/false,
6001 getSpecifierRange(startSpecifier, specifierLen));
6002
6003 return true;
6004 }
6005
Ted Kremenek4a49d982010-02-26 19:18:41 +00006006 // Check for using an Objective-C specific conversion specifier
6007 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006008 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006009 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6010 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006011 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006012
Mehdi Amini06d367c2016-10-24 20:39:34 +00006013 // %P can only be used with os_log.
6014 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6015 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6016 specifierLen);
6017 }
6018
6019 // %n is not allowed with os_log.
6020 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6021 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6022 getLocationOfByte(CS.getStart()),
6023 /*IsStringLocation*/ false,
6024 getSpecifierRange(startSpecifier, specifierLen));
6025
6026 return true;
6027 }
6028
6029 // Only scalars are allowed for os_trace.
6030 if (FSType == Sema::FST_OSTrace &&
6031 (CS.getKind() == ConversionSpecifier::PArg ||
6032 CS.getKind() == ConversionSpecifier::sArg ||
6033 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6034 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6035 specifierLen);
6036 }
6037
6038 // Check for use of public/private annotation outside of os_log().
6039 if (FSType != Sema::FST_OSLog) {
6040 if (FS.isPublic().isSet()) {
6041 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6042 << "public",
6043 getLocationOfByte(FS.isPublic().getPosition()),
6044 /*IsStringLocation*/ false,
6045 getSpecifierRange(startSpecifier, specifierLen));
6046 }
6047 if (FS.isPrivate().isSet()) {
6048 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6049 << "private",
6050 getLocationOfByte(FS.isPrivate().getPosition()),
6051 /*IsStringLocation*/ false,
6052 getSpecifierRange(startSpecifier, specifierLen));
6053 }
6054 }
6055
Tom Careb49ec692010-06-17 19:00:27 +00006056 // Check for invalid use of field width
6057 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006058 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006059 startSpecifier, specifierLen);
6060 }
6061
6062 // Check for invalid use of precision
6063 if (!FS.hasValidPrecision()) {
6064 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6065 startSpecifier, specifierLen);
6066 }
6067
Mehdi Amini06d367c2016-10-24 20:39:34 +00006068 // Precision is mandatory for %P specifier.
6069 if (CS.getKind() == ConversionSpecifier::PArg &&
6070 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6071 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6072 getLocationOfByte(startSpecifier),
6073 /*IsStringLocation*/ false,
6074 getSpecifierRange(startSpecifier, specifierLen));
6075 }
6076
Tom Careb49ec692010-06-17 19:00:27 +00006077 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006078 if (!FS.hasValidThousandsGroupingPrefix())
6079 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006080 if (!FS.hasValidLeadingZeros())
6081 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6082 if (!FS.hasValidPlusPrefix())
6083 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006084 if (!FS.hasValidSpacePrefix())
6085 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006086 if (!FS.hasValidAlternativeForm())
6087 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6088 if (!FS.hasValidLeftJustified())
6089 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6090
6091 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006092 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6093 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6094 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006095 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6096 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6097 startSpecifier, specifierLen);
6098
6099 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006100 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006101 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6102 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006103 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006104 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006105 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006106 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6107 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006108
Jordan Rose92303592012-09-08 04:00:03 +00006109 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6110 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6111
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006112 // The remaining checks depend on the data arguments.
6113 if (HasVAListArg)
6114 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006115
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006116 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006117 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006118
Jordan Rose58bbe422012-07-19 18:10:08 +00006119 const Expr *Arg = getDataArg(argIndex);
6120 if (!Arg)
6121 return true;
6122
6123 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006124}
6125
Jordan Roseaee34382012-09-05 22:56:26 +00006126static bool requiresParensToAddCast(const Expr *E) {
6127 // FIXME: We should have a general way to reason about operator
6128 // precedence and whether parens are actually needed here.
6129 // Take care of a few common cases where they aren't.
6130 const Expr *Inside = E->IgnoreImpCasts();
6131 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6132 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6133
6134 switch (Inside->getStmtClass()) {
6135 case Stmt::ArraySubscriptExprClass:
6136 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006137 case Stmt::CharacterLiteralClass:
6138 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006139 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006140 case Stmt::FloatingLiteralClass:
6141 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006142 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006143 case Stmt::ObjCArrayLiteralClass:
6144 case Stmt::ObjCBoolLiteralExprClass:
6145 case Stmt::ObjCBoxedExprClass:
6146 case Stmt::ObjCDictionaryLiteralClass:
6147 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006148 case Stmt::ObjCIvarRefExprClass:
6149 case Stmt::ObjCMessageExprClass:
6150 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006151 case Stmt::ObjCStringLiteralClass:
6152 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006153 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006154 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006155 case Stmt::UnaryOperatorClass:
6156 return false;
6157 default:
6158 return true;
6159 }
6160}
6161
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006162static std::pair<QualType, StringRef>
6163shouldNotPrintDirectly(const ASTContext &Context,
6164 QualType IntendedTy,
6165 const Expr *E) {
6166 // Use a 'while' to peel off layers of typedefs.
6167 QualType TyTy = IntendedTy;
6168 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6169 StringRef Name = UserTy->getDecl()->getName();
6170 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006171 .Case("CFIndex", Context.getNSIntegerType())
6172 .Case("NSInteger", Context.getNSIntegerType())
6173 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006174 .Case("SInt32", Context.IntTy)
6175 .Case("UInt32", Context.UnsignedIntTy)
6176 .Default(QualType());
6177
6178 if (!CastTy.isNull())
6179 return std::make_pair(CastTy, Name);
6180
6181 TyTy = UserTy->desugar();
6182 }
6183
6184 // Strip parens if necessary.
6185 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6186 return shouldNotPrintDirectly(Context,
6187 PE->getSubExpr()->getType(),
6188 PE->getSubExpr());
6189
6190 // If this is a conditional expression, then its result type is constructed
6191 // via usual arithmetic conversions and thus there might be no necessary
6192 // typedef sugar there. Recurse to operands to check for NSInteger &
6193 // Co. usage condition.
6194 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6195 QualType TrueTy, FalseTy;
6196 StringRef TrueName, FalseName;
6197
6198 std::tie(TrueTy, TrueName) =
6199 shouldNotPrintDirectly(Context,
6200 CO->getTrueExpr()->getType(),
6201 CO->getTrueExpr());
6202 std::tie(FalseTy, FalseName) =
6203 shouldNotPrintDirectly(Context,
6204 CO->getFalseExpr()->getType(),
6205 CO->getFalseExpr());
6206
6207 if (TrueTy == FalseTy)
6208 return std::make_pair(TrueTy, TrueName);
6209 else if (TrueTy.isNull())
6210 return std::make_pair(FalseTy, FalseName);
6211 else if (FalseTy.isNull())
6212 return std::make_pair(TrueTy, TrueName);
6213 }
6214
6215 return std::make_pair(QualType(), StringRef());
6216}
6217
Richard Smith55ce3522012-06-25 20:30:08 +00006218bool
6219CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6220 const char *StartSpecifier,
6221 unsigned SpecifierLen,
6222 const Expr *E) {
6223 using namespace analyze_format_string;
6224 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006225 // Now type check the data expression that matches the
6226 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006227 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006228 if (!AT.isValid())
6229 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006230
Jordan Rose598ec092012-12-05 18:44:40 +00006231 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006232 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6233 ExprTy = TET->getUnderlyingExpr()->getType();
6234 }
6235
Seth Cantrellb4802962015-03-04 03:12:10 +00006236 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6237
6238 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006239 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006240 }
Jordan Rose98709982012-06-04 22:48:57 +00006241
Jordan Rose22b74712012-09-05 22:56:19 +00006242 // Look through argument promotions for our error message's reported type.
6243 // This includes the integral and floating promotions, but excludes array
6244 // and function pointer decay; seeing that an argument intended to be a
6245 // string has type 'char [6]' is probably more confusing than 'char *'.
6246 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6247 if (ICE->getCastKind() == CK_IntegralCast ||
6248 ICE->getCastKind() == CK_FloatingCast) {
6249 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006250 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006251
6252 // Check if we didn't match because of an implicit cast from a 'char'
6253 // or 'short' to an 'int'. This is done because printf is a varargs
6254 // function.
6255 if (ICE->getType() == S.Context.IntTy ||
6256 ICE->getType() == S.Context.UnsignedIntTy) {
6257 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006258 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006259 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006260 }
Jordan Rose98709982012-06-04 22:48:57 +00006261 }
Jordan Rose598ec092012-12-05 18:44:40 +00006262 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6263 // Special case for 'a', which has type 'int' in C.
6264 // Note, however, that we do /not/ want to treat multibyte constants like
6265 // 'MooV' as characters! This form is deprecated but still exists.
6266 if (ExprTy == S.Context.IntTy)
6267 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6268 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006269 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006270
Jordan Rosebc53ed12014-05-31 04:12:14 +00006271 // Look through enums to their underlying type.
6272 bool IsEnum = false;
6273 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6274 ExprTy = EnumTy->getDecl()->getIntegerType();
6275 IsEnum = true;
6276 }
6277
Jordan Rose0e5badd2012-12-05 18:44:49 +00006278 // %C in an Objective-C context prints a unichar, not a wchar_t.
6279 // If the argument is an integer of some kind, believe the %C and suggest
6280 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006281 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006282 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006283 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6284 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6285 !ExprTy->isCharType()) {
6286 // 'unichar' is defined as a typedef of unsigned short, but we should
6287 // prefer using the typedef if it is visible.
6288 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006289
6290 // While we are here, check if the value is an IntegerLiteral that happens
6291 // to be within the valid range.
6292 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6293 const llvm::APInt &V = IL->getValue();
6294 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6295 return true;
6296 }
6297
Jordan Rose0e5badd2012-12-05 18:44:49 +00006298 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6299 Sema::LookupOrdinaryName);
6300 if (S.LookupName(Result, S.getCurScope())) {
6301 NamedDecl *ND = Result.getFoundDecl();
6302 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6303 if (TD->getUnderlyingType() == IntendedTy)
6304 IntendedTy = S.Context.getTypedefType(TD);
6305 }
6306 }
6307 }
6308
6309 // Special-case some of Darwin's platform-independence types by suggesting
6310 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006311 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006312 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006313 QualType CastTy;
6314 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6315 if (!CastTy.isNull()) {
6316 IntendedTy = CastTy;
6317 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006318 }
6319 }
6320
Jordan Rose22b74712012-09-05 22:56:19 +00006321 // We may be able to offer a FixItHint if it is a supported type.
6322 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006323 bool success =
6324 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006325
Jordan Rose22b74712012-09-05 22:56:19 +00006326 if (success) {
6327 // Get the fix string from the fixed format specifier
6328 SmallString<16> buf;
6329 llvm::raw_svector_ostream os(buf);
6330 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006331
Jordan Roseaee34382012-09-05 22:56:26 +00006332 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6333
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006334 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006335 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6336 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6337 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6338 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006339 // In this case, the specifier is wrong and should be changed to match
6340 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006341 EmitFormatDiagnostic(S.PDiag(diag)
6342 << AT.getRepresentativeTypeName(S.Context)
6343 << IntendedTy << IsEnum << E->getSourceRange(),
6344 E->getLocStart(),
6345 /*IsStringLocation*/ false, SpecRange,
6346 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006347 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006348 // The canonical type for formatting this value is different from the
6349 // actual type of the expression. (This occurs, for example, with Darwin's
6350 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6351 // should be printed as 'long' for 64-bit compatibility.)
6352 // Rather than emitting a normal format/argument mismatch, we want to
6353 // add a cast to the recommended type (and correct the format string
6354 // if necessary).
6355 SmallString<16> CastBuf;
6356 llvm::raw_svector_ostream CastFix(CastBuf);
6357 CastFix << "(";
6358 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6359 CastFix << ")";
6360
6361 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006362 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006363 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6364
6365 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6366 // If there's already a cast present, just replace it.
6367 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6368 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6369
6370 } else if (!requiresParensToAddCast(E)) {
6371 // If the expression has high enough precedence,
6372 // just write the C-style cast.
6373 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6374 CastFix.str()));
6375 } else {
6376 // Otherwise, add parens around the expression as well as the cast.
6377 CastFix << "(";
6378 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6379 CastFix.str()));
6380
Alp Tokerb6cc5922014-05-03 03:45:55 +00006381 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006382 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6383 }
6384
Jordan Rose0e5badd2012-12-05 18:44:49 +00006385 if (ShouldNotPrintDirectly) {
6386 // The expression has a type that should not be printed directly.
6387 // We extract the name from the typedef because we don't want to show
6388 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006389 StringRef Name;
6390 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6391 Name = TypedefTy->getDecl()->getName();
6392 else
6393 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006394 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006395 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006396 << E->getSourceRange(),
6397 E->getLocStart(), /*IsStringLocation=*/false,
6398 SpecRange, Hints);
6399 } else {
6400 // In this case, the expression could be printed using a different
6401 // specifier, but we've decided that the specifier is probably correct
6402 // and we should cast instead. Just use the normal warning message.
6403 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006404 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6405 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006406 << E->getSourceRange(),
6407 E->getLocStart(), /*IsStringLocation*/false,
6408 SpecRange, Hints);
6409 }
Jordan Roseaee34382012-09-05 22:56:26 +00006410 }
Jordan Rose22b74712012-09-05 22:56:19 +00006411 } else {
6412 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6413 SpecifierLen);
6414 // Since the warning for passing non-POD types to variadic functions
6415 // was deferred until now, we emit a warning for non-POD
6416 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006417 switch (S.isValidVarArgType(ExprTy)) {
6418 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006419 case Sema::VAK_ValidInCXX11: {
6420 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6421 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6422 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6423 }
Richard Smithd7293d72013-08-05 18:49:43 +00006424
Seth Cantrellb4802962015-03-04 03:12:10 +00006425 EmitFormatDiagnostic(
6426 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6427 << IsEnum << CSR << E->getSourceRange(),
6428 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6429 break;
6430 }
Richard Smithd7293d72013-08-05 18:49:43 +00006431 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006432 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006433 EmitFormatDiagnostic(
6434 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006435 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006436 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006437 << CallType
6438 << AT.getRepresentativeTypeName(S.Context)
6439 << CSR
6440 << E->getSourceRange(),
6441 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006442 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006443 break;
6444
6445 case Sema::VAK_Invalid:
6446 if (ExprTy->isObjCObjectType())
6447 EmitFormatDiagnostic(
6448 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6449 << S.getLangOpts().CPlusPlus11
6450 << ExprTy
6451 << CallType
6452 << AT.getRepresentativeTypeName(S.Context)
6453 << CSR
6454 << E->getSourceRange(),
6455 E->getLocStart(), /*IsStringLocation*/false, CSR);
6456 else
6457 // FIXME: If this is an initializer list, suggest removing the braces
6458 // or inserting a cast to the target type.
6459 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6460 << isa<InitListExpr>(E) << ExprTy << CallType
6461 << AT.getRepresentativeTypeName(S.Context)
6462 << E->getSourceRange();
6463 break;
6464 }
6465
6466 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6467 "format string specifier index out of range");
6468 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006469 }
6470
Ted Kremenekab278de2010-01-28 23:39:18 +00006471 return true;
6472}
6473
Ted Kremenek02087932010-07-16 02:11:22 +00006474//===--- CHECK: Scanf format string checking ------------------------------===//
6475
6476namespace {
6477class CheckScanfHandler : public CheckFormatHandler {
6478public:
Stephen Hines648c3692016-09-16 01:07:04 +00006479 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006480 const Expr *origFormatExpr, Sema::FormatStringType type,
6481 unsigned firstDataArg, unsigned numDataArgs,
6482 const char *beg, bool hasVAListArg,
6483 ArrayRef<const Expr *> Args, unsigned formatIdx,
6484 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006485 llvm::SmallBitVector &CheckedVarArgs,
6486 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006487 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6488 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6489 inFunctionCall, CallType, CheckedVarArgs,
6490 UncoveredArg) {}
6491
Ted Kremenek02087932010-07-16 02:11:22 +00006492 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6493 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006494 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006495
6496 bool HandleInvalidScanfConversionSpecifier(
6497 const analyze_scanf::ScanfSpecifier &FS,
6498 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006499 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006500
Craig Toppere14c0f82014-03-12 04:55:44 +00006501 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006502};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006503} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006504
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006505void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6506 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006507 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6508 getLocationOfByte(end), /*IsStringLocation*/true,
6509 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006510}
6511
Ted Kremenekce815422010-07-19 21:25:57 +00006512bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6513 const analyze_scanf::ScanfSpecifier &FS,
6514 const char *startSpecifier,
6515 unsigned specifierLen) {
6516
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006517 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006518 FS.getConversionSpecifier();
6519
6520 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6521 getLocationOfByte(CS.getStart()),
6522 startSpecifier, specifierLen,
6523 CS.getStart(), CS.getLength());
6524}
6525
Ted Kremenek02087932010-07-16 02:11:22 +00006526bool CheckScanfHandler::HandleScanfSpecifier(
6527 const analyze_scanf::ScanfSpecifier &FS,
6528 const char *startSpecifier,
6529 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006530 using namespace analyze_scanf;
6531 using namespace analyze_format_string;
6532
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006533 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006534
Ted Kremenek6cd69422010-07-19 22:01:06 +00006535 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6536 // be used to decide if we are using positional arguments consistently.
6537 if (FS.consumesDataArgument()) {
6538 if (atFirstArg) {
6539 atFirstArg = false;
6540 usesPositionalArgs = FS.usesPositionalArg();
6541 }
6542 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006543 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6544 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006545 return false;
6546 }
Ted Kremenek02087932010-07-16 02:11:22 +00006547 }
6548
6549 // Check if the field with is non-zero.
6550 const OptionalAmount &Amt = FS.getFieldWidth();
6551 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6552 if (Amt.getConstantAmount() == 0) {
6553 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6554 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006555 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6556 getLocationOfByte(Amt.getStart()),
6557 /*IsStringLocation*/true, R,
6558 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006559 }
6560 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006561
Ted Kremenek02087932010-07-16 02:11:22 +00006562 if (!FS.consumesDataArgument()) {
6563 // FIXME: Technically specifying a precision or field width here
6564 // makes no sense. Worth issuing a warning at some point.
6565 return true;
6566 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006567
Ted Kremenek02087932010-07-16 02:11:22 +00006568 // Consume the argument.
6569 unsigned argIndex = FS.getArgIndex();
6570 if (argIndex < NumDataArgs) {
6571 // The check to see if the argIndex is valid will come later.
6572 // We set the bit here because we may exit early from this
6573 // function if we encounter some other error.
6574 CoveredArgs.set(argIndex);
6575 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006576
Ted Kremenek4407ea42010-07-20 20:04:47 +00006577 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006578 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006579 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6580 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006581 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006582 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006583 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006584 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6585 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006586
Jordan Rose92303592012-09-08 04:00:03 +00006587 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6588 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6589
Ted Kremenek02087932010-07-16 02:11:22 +00006590 // The remaining checks depend on the data arguments.
6591 if (HasVAListArg)
6592 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006593
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006594 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006595 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006596
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006597 // Check that the argument type matches the format specifier.
6598 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006599 if (!Ex)
6600 return true;
6601
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006602 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006603
6604 if (!AT.isValid()) {
6605 return true;
6606 }
6607
Seth Cantrellb4802962015-03-04 03:12:10 +00006608 analyze_format_string::ArgType::MatchKind match =
6609 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006610 if (match == analyze_format_string::ArgType::Match) {
6611 return true;
6612 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006613
Seth Cantrell79340072015-03-04 05:58:08 +00006614 ScanfSpecifier fixedFS = FS;
6615 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6616 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006617
Seth Cantrell79340072015-03-04 05:58:08 +00006618 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6619 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6620 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6621 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006622
Seth Cantrell79340072015-03-04 05:58:08 +00006623 if (success) {
6624 // Get the fix string from the fixed format specifier.
6625 SmallString<128> buf;
6626 llvm::raw_svector_ostream os(buf);
6627 fixedFS.toString(os);
6628
6629 EmitFormatDiagnostic(
6630 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6631 << Ex->getType() << false << Ex->getSourceRange(),
6632 Ex->getLocStart(),
6633 /*IsStringLocation*/ false,
6634 getSpecifierRange(startSpecifier, specifierLen),
6635 FixItHint::CreateReplacement(
6636 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6637 } else {
6638 EmitFormatDiagnostic(S.PDiag(diag)
6639 << AT.getRepresentativeTypeName(S.Context)
6640 << Ex->getType() << false << Ex->getSourceRange(),
6641 Ex->getLocStart(),
6642 /*IsStringLocation*/ false,
6643 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006644 }
6645
Ted Kremenek02087932010-07-16 02:11:22 +00006646 return true;
6647}
6648
Stephen Hines648c3692016-09-16 01:07:04 +00006649static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006650 const Expr *OrigFormatExpr,
6651 ArrayRef<const Expr *> Args,
6652 bool HasVAListArg, unsigned format_idx,
6653 unsigned firstDataArg,
6654 Sema::FormatStringType Type,
6655 bool inFunctionCall,
6656 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006657 llvm::SmallBitVector &CheckedVarArgs,
6658 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006659 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006660 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006661 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006662 S, inFunctionCall, Args[format_idx],
6663 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006664 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006665 return;
6666 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006667
Ted Kremenekab278de2010-01-28 23:39:18 +00006668 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006669 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006670 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006671 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006672 const ConstantArrayType *T =
6673 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006674 assert(T && "String literal not of constant array type!");
6675 size_t TypeSize = T->getSize().getZExtValue();
6676 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006677 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006678
6679 // Emit a warning if the string literal is truncated and does not contain an
6680 // embedded null character.
6681 if (TypeSize <= StrRef.size() &&
6682 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6683 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006684 S, inFunctionCall, Args[format_idx],
6685 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006686 FExpr->getLocStart(),
6687 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6688 return;
6689 }
6690
Ted Kremenekab278de2010-01-28 23:39:18 +00006691 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006692 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006693 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006694 S, inFunctionCall, Args[format_idx],
6695 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006696 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006697 return;
6698 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006699
6700 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006701 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6702 Type == Sema::FST_OSTrace) {
6703 CheckPrintfHandler H(
6704 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6705 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6706 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6707 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006708
Hans Wennborg23926bd2011-12-15 10:25:47 +00006709 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006710 S.getLangOpts(),
6711 S.Context.getTargetInfo(),
6712 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006713 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006714 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006715 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6716 numDataArgs, Str, HasVAListArg, Args, format_idx,
6717 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006718
Hans Wennborg23926bd2011-12-15 10:25:47 +00006719 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006720 S.getLangOpts(),
6721 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006722 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006723 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006724}
6725
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006726bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6727 // Str - The format string. NOTE: this is NOT null-terminated!
6728 StringRef StrRef = FExpr->getString();
6729 const char *Str = StrRef.data();
6730 // Account for cases where the string literal is truncated in a declaration.
6731 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6732 assert(T && "String literal not of constant array type!");
6733 size_t TypeSize = T->getSize().getZExtValue();
6734 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6735 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6736 getLangOpts(),
6737 Context.getTargetInfo());
6738}
6739
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006740//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6741
6742// Returns the related absolute value function that is larger, of 0 if one
6743// does not exist.
6744static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6745 switch (AbsFunction) {
6746 default:
6747 return 0;
6748
6749 case Builtin::BI__builtin_abs:
6750 return Builtin::BI__builtin_labs;
6751 case Builtin::BI__builtin_labs:
6752 return Builtin::BI__builtin_llabs;
6753 case Builtin::BI__builtin_llabs:
6754 return 0;
6755
6756 case Builtin::BI__builtin_fabsf:
6757 return Builtin::BI__builtin_fabs;
6758 case Builtin::BI__builtin_fabs:
6759 return Builtin::BI__builtin_fabsl;
6760 case Builtin::BI__builtin_fabsl:
6761 return 0;
6762
6763 case Builtin::BI__builtin_cabsf:
6764 return Builtin::BI__builtin_cabs;
6765 case Builtin::BI__builtin_cabs:
6766 return Builtin::BI__builtin_cabsl;
6767 case Builtin::BI__builtin_cabsl:
6768 return 0;
6769
6770 case Builtin::BIabs:
6771 return Builtin::BIlabs;
6772 case Builtin::BIlabs:
6773 return Builtin::BIllabs;
6774 case Builtin::BIllabs:
6775 return 0;
6776
6777 case Builtin::BIfabsf:
6778 return Builtin::BIfabs;
6779 case Builtin::BIfabs:
6780 return Builtin::BIfabsl;
6781 case Builtin::BIfabsl:
6782 return 0;
6783
6784 case Builtin::BIcabsf:
6785 return Builtin::BIcabs;
6786 case Builtin::BIcabs:
6787 return Builtin::BIcabsl;
6788 case Builtin::BIcabsl:
6789 return 0;
6790 }
6791}
6792
6793// Returns the argument type of the absolute value function.
6794static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6795 unsigned AbsType) {
6796 if (AbsType == 0)
6797 return QualType();
6798
6799 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6800 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6801 if (Error != ASTContext::GE_None)
6802 return QualType();
6803
6804 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6805 if (!FT)
6806 return QualType();
6807
6808 if (FT->getNumParams() != 1)
6809 return QualType();
6810
6811 return FT->getParamType(0);
6812}
6813
6814// Returns the best absolute value function, or zero, based on type and
6815// current absolute value function.
6816static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6817 unsigned AbsFunctionKind) {
6818 unsigned BestKind = 0;
6819 uint64_t ArgSize = Context.getTypeSize(ArgType);
6820 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6821 Kind = getLargerAbsoluteValueFunction(Kind)) {
6822 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6823 if (Context.getTypeSize(ParamType) >= ArgSize) {
6824 if (BestKind == 0)
6825 BestKind = Kind;
6826 else if (Context.hasSameType(ParamType, ArgType)) {
6827 BestKind = Kind;
6828 break;
6829 }
6830 }
6831 }
6832 return BestKind;
6833}
6834
6835enum AbsoluteValueKind {
6836 AVK_Integer,
6837 AVK_Floating,
6838 AVK_Complex
6839};
6840
6841static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6842 if (T->isIntegralOrEnumerationType())
6843 return AVK_Integer;
6844 if (T->isRealFloatingType())
6845 return AVK_Floating;
6846 if (T->isAnyComplexType())
6847 return AVK_Complex;
6848
6849 llvm_unreachable("Type not integer, floating, or complex");
6850}
6851
6852// Changes the absolute value function to a different type. Preserves whether
6853// the function is a builtin.
6854static unsigned changeAbsFunction(unsigned AbsKind,
6855 AbsoluteValueKind ValueKind) {
6856 switch (ValueKind) {
6857 case AVK_Integer:
6858 switch (AbsKind) {
6859 default:
6860 return 0;
6861 case Builtin::BI__builtin_fabsf:
6862 case Builtin::BI__builtin_fabs:
6863 case Builtin::BI__builtin_fabsl:
6864 case Builtin::BI__builtin_cabsf:
6865 case Builtin::BI__builtin_cabs:
6866 case Builtin::BI__builtin_cabsl:
6867 return Builtin::BI__builtin_abs;
6868 case Builtin::BIfabsf:
6869 case Builtin::BIfabs:
6870 case Builtin::BIfabsl:
6871 case Builtin::BIcabsf:
6872 case Builtin::BIcabs:
6873 case Builtin::BIcabsl:
6874 return Builtin::BIabs;
6875 }
6876 case AVK_Floating:
6877 switch (AbsKind) {
6878 default:
6879 return 0;
6880 case Builtin::BI__builtin_abs:
6881 case Builtin::BI__builtin_labs:
6882 case Builtin::BI__builtin_llabs:
6883 case Builtin::BI__builtin_cabsf:
6884 case Builtin::BI__builtin_cabs:
6885 case Builtin::BI__builtin_cabsl:
6886 return Builtin::BI__builtin_fabsf;
6887 case Builtin::BIabs:
6888 case Builtin::BIlabs:
6889 case Builtin::BIllabs:
6890 case Builtin::BIcabsf:
6891 case Builtin::BIcabs:
6892 case Builtin::BIcabsl:
6893 return Builtin::BIfabsf;
6894 }
6895 case AVK_Complex:
6896 switch (AbsKind) {
6897 default:
6898 return 0;
6899 case Builtin::BI__builtin_abs:
6900 case Builtin::BI__builtin_labs:
6901 case Builtin::BI__builtin_llabs:
6902 case Builtin::BI__builtin_fabsf:
6903 case Builtin::BI__builtin_fabs:
6904 case Builtin::BI__builtin_fabsl:
6905 return Builtin::BI__builtin_cabsf;
6906 case Builtin::BIabs:
6907 case Builtin::BIlabs:
6908 case Builtin::BIllabs:
6909 case Builtin::BIfabsf:
6910 case Builtin::BIfabs:
6911 case Builtin::BIfabsl:
6912 return Builtin::BIcabsf;
6913 }
6914 }
6915 llvm_unreachable("Unable to convert function");
6916}
6917
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006918static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006919 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6920 if (!FnInfo)
6921 return 0;
6922
6923 switch (FDecl->getBuiltinID()) {
6924 default:
6925 return 0;
6926 case Builtin::BI__builtin_abs:
6927 case Builtin::BI__builtin_fabs:
6928 case Builtin::BI__builtin_fabsf:
6929 case Builtin::BI__builtin_fabsl:
6930 case Builtin::BI__builtin_labs:
6931 case Builtin::BI__builtin_llabs:
6932 case Builtin::BI__builtin_cabs:
6933 case Builtin::BI__builtin_cabsf:
6934 case Builtin::BI__builtin_cabsl:
6935 case Builtin::BIabs:
6936 case Builtin::BIlabs:
6937 case Builtin::BIllabs:
6938 case Builtin::BIfabs:
6939 case Builtin::BIfabsf:
6940 case Builtin::BIfabsl:
6941 case Builtin::BIcabs:
6942 case Builtin::BIcabsf:
6943 case Builtin::BIcabsl:
6944 return FDecl->getBuiltinID();
6945 }
6946 llvm_unreachable("Unknown Builtin type");
6947}
6948
6949// If the replacement is valid, emit a note with replacement function.
6950// Additionally, suggest including the proper header if not already included.
6951static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00006952 unsigned AbsKind, QualType ArgType) {
6953 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006954 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00006955 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006956 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6957 FunctionName = "std::abs";
6958 if (ArgType->isIntegralOrEnumerationType()) {
6959 HeaderName = "cstdlib";
6960 } else if (ArgType->isRealFloatingType()) {
6961 HeaderName = "cmath";
6962 } else {
6963 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006964 }
Richard Trieubeffb832014-04-15 23:47:53 +00006965
6966 // Lookup all std::abs
6967 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00006968 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00006969 R.suppressDiagnostics();
6970 S.LookupQualifiedName(R, Std);
6971
6972 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006973 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00006974 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6975 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6976 } else {
6977 FDecl = dyn_cast<FunctionDecl>(I);
6978 }
6979 if (!FDecl)
6980 continue;
6981
6982 // Found std::abs(), check that they are the right ones.
6983 if (FDecl->getNumParams() != 1)
6984 continue;
6985
6986 // Check that the parameter type can handle the argument.
6987 QualType ParamType = FDecl->getParamDecl(0)->getType();
6988 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6989 S.Context.getTypeSize(ArgType) <=
6990 S.Context.getTypeSize(ParamType)) {
6991 // Found a function, don't need the header hint.
6992 EmitHeaderHint = false;
6993 break;
6994 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006995 }
Richard Trieubeffb832014-04-15 23:47:53 +00006996 }
6997 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00006998 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00006999 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7000
7001 if (HeaderName) {
7002 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7003 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7004 R.suppressDiagnostics();
7005 S.LookupName(R, S.getCurScope());
7006
7007 if (R.isSingleResult()) {
7008 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7009 if (FD && FD->getBuiltinID() == AbsKind) {
7010 EmitHeaderHint = false;
7011 } else {
7012 return;
7013 }
7014 } else if (!R.empty()) {
7015 return;
7016 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007017 }
7018 }
7019
7020 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007021 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007022
Richard Trieubeffb832014-04-15 23:47:53 +00007023 if (!HeaderName)
7024 return;
7025
7026 if (!EmitHeaderHint)
7027 return;
7028
Alp Toker5d96e0a2014-07-11 20:53:51 +00007029 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7030 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007031}
7032
Richard Trieua7f30b12016-12-06 01:42:28 +00007033template <std::size_t StrLen>
7034static bool IsStdFunction(const FunctionDecl *FDecl,
7035 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007036 if (!FDecl)
7037 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007038 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007039 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007040 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007041 return false;
7042
7043 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007044}
7045
7046// Warn when using the wrong abs() function.
7047void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007048 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007049 if (Call->getNumArgs() != 1)
7050 return;
7051
7052 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007053 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007054 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007055 return;
7056
7057 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7058 QualType ParamType = Call->getArg(0)->getType();
7059
Alp Toker5d96e0a2014-07-11 20:53:51 +00007060 // Unsigned types cannot be negative. Suggest removing the absolute value
7061 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007062 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007063 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007064 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007065 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7066 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007067 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007068 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7069 return;
7070 }
7071
David Majnemer7f77eb92015-11-15 03:04:34 +00007072 // Taking the absolute value of a pointer is very suspicious, they probably
7073 // wanted to index into an array, dereference a pointer, call a function, etc.
7074 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7075 unsigned DiagType = 0;
7076 if (ArgType->isFunctionType())
7077 DiagType = 1;
7078 else if (ArgType->isArrayType())
7079 DiagType = 2;
7080
7081 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7082 return;
7083 }
7084
Richard Trieubeffb832014-04-15 23:47:53 +00007085 // std::abs has overloads which prevent most of the absolute value problems
7086 // from occurring.
7087 if (IsStdAbs)
7088 return;
7089
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007090 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7091 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7092
7093 // The argument and parameter are the same kind. Check if they are the right
7094 // size.
7095 if (ArgValueKind == ParamValueKind) {
7096 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7097 return;
7098
7099 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7100 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7101 << FDecl << ArgType << ParamType;
7102
7103 if (NewAbsKind == 0)
7104 return;
7105
7106 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007107 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007108 return;
7109 }
7110
7111 // ArgValueKind != ParamValueKind
7112 // The wrong type of absolute value function was used. Attempt to find the
7113 // proper one.
7114 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7115 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7116 if (NewAbsKind == 0)
7117 return;
7118
7119 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7120 << FDecl << ParamValueKind << ArgValueKind;
7121
7122 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007123 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007124}
7125
Richard Trieu67c00712016-12-05 23:41:46 +00007126//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007127void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7128 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007129 if (!Call || !FDecl) return;
7130
7131 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007132 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007133 if (Call->getExprLoc().isMacroID()) return;
7134
7135 // Only care about the one template argument, two function parameter std::max
7136 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007137 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007138 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7139 if (!ArgList) return;
7140 if (ArgList->size() != 1) return;
7141
7142 // Check that template type argument is unsigned integer.
7143 const auto& TA = ArgList->get(0);
7144 if (TA.getKind() != TemplateArgument::Type) return;
7145 QualType ArgType = TA.getAsType();
7146 if (!ArgType->isUnsignedIntegerType()) return;
7147
7148 // See if either argument is a literal zero.
7149 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7150 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7151 if (!MTE) return false;
7152 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7153 if (!Num) return false;
7154 if (Num->getValue() != 0) return false;
7155 return true;
7156 };
7157
7158 const Expr *FirstArg = Call->getArg(0);
7159 const Expr *SecondArg = Call->getArg(1);
7160 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7161 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7162
7163 // Only warn when exactly one argument is zero.
7164 if (IsFirstArgZero == IsSecondArgZero) return;
7165
7166 SourceRange FirstRange = FirstArg->getSourceRange();
7167 SourceRange SecondRange = SecondArg->getSourceRange();
7168
7169 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7170
7171 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7172 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7173
7174 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7175 SourceRange RemovalRange;
7176 if (IsFirstArgZero) {
7177 RemovalRange = SourceRange(FirstRange.getBegin(),
7178 SecondRange.getBegin().getLocWithOffset(-1));
7179 } else {
7180 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7181 SecondRange.getEnd());
7182 }
7183
7184 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7185 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7186 << FixItHint::CreateRemoval(RemovalRange);
7187}
7188
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007189//===--- CHECK: Standard memory functions ---------------------------------===//
7190
Nico Weber0e6daef2013-12-26 23:38:39 +00007191/// \brief Takes the expression passed to the size_t parameter of functions
7192/// such as memcmp, strncat, etc and warns if it's a comparison.
7193///
7194/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7195static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7196 IdentifierInfo *FnName,
7197 SourceLocation FnLoc,
7198 SourceLocation RParenLoc) {
7199 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7200 if (!Size)
7201 return false;
7202
7203 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7204 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7205 return false;
7206
Nico Weber0e6daef2013-12-26 23:38:39 +00007207 SourceRange SizeRange = Size->getSourceRange();
7208 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7209 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007210 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007211 << FnName << FixItHint::CreateInsertion(
7212 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007213 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007214 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007215 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007216 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7217 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007218
7219 return true;
7220}
7221
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007222/// \brief Determine whether the given type is or contains a dynamic class type
7223/// (e.g., whether it has a vtable).
7224static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7225 bool &IsContained) {
7226 // Look through array types while ignoring qualifiers.
7227 const Type *Ty = T->getBaseElementTypeUnsafe();
7228 IsContained = false;
7229
7230 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7231 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007232 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007233 return nullptr;
7234
7235 if (RD->isDynamicClass())
7236 return RD;
7237
7238 // Check all the fields. If any bases were dynamic, the class is dynamic.
7239 // It's impossible for a class to transitively contain itself by value, so
7240 // infinite recursion is impossible.
7241 for (auto *FD : RD->fields()) {
7242 bool SubContained;
7243 if (const CXXRecordDecl *ContainedRD =
7244 getContainedDynamicClass(FD->getType(), SubContained)) {
7245 IsContained = true;
7246 return ContainedRD;
7247 }
7248 }
7249
7250 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007251}
7252
Chandler Carruth889ed862011-06-21 23:04:20 +00007253/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007254/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007255static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007256 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007257 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7258 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7259 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007260
Craig Topperc3ec1492014-05-26 06:22:03 +00007261 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007262}
7263
Chandler Carruth889ed862011-06-21 23:04:20 +00007264/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007265static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007266 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7267 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7268 if (SizeOf->getKind() == clang::UETT_SizeOf)
7269 return SizeOf->getTypeOfArgument();
7270
7271 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007272}
7273
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007274/// \brief Check for dangerous or invalid arguments to memset().
7275///
Chandler Carruthac687262011-06-03 06:23:57 +00007276/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007277/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7278/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007279///
7280/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007281void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007282 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007283 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007284 assert(BId != 0);
7285
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007286 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007287 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007288 unsigned ExpectedNumArgs =
7289 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007290 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007291 return;
7292
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007293 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007294 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007295 unsigned LenArg =
7296 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007297 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007298
Nico Weber0e6daef2013-12-26 23:38:39 +00007299 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7300 Call->getLocStart(), Call->getRParenLoc()))
7301 return;
7302
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007303 // We have special checking when the length is a sizeof expression.
7304 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7305 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7306 llvm::FoldingSetNodeID SizeOfArgID;
7307
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007308 // Although widely used, 'bzero' is not a standard function. Be more strict
7309 // with the argument types before allowing diagnostics and only allow the
7310 // form bzero(ptr, sizeof(...)).
7311 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7312 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7313 return;
7314
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007315 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7316 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007317 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007318
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007319 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007320 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007321 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007322 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007323
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007324 // Never warn about void type pointers. This can be used to suppress
7325 // false positives.
7326 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007327 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007328
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007329 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7330 // actually comparing the expressions for equality. Because computing the
7331 // expression IDs can be expensive, we only do this if the diagnostic is
7332 // enabled.
7333 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007334 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7335 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007336 // We only compute IDs for expressions if the warning is enabled, and
7337 // cache the sizeof arg's ID.
7338 if (SizeOfArgID == llvm::FoldingSetNodeID())
7339 SizeOfArg->Profile(SizeOfArgID, Context, true);
7340 llvm::FoldingSetNodeID DestID;
7341 Dest->Profile(DestID, Context, true);
7342 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007343 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7344 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007345 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007346 StringRef ReadableName = FnName->getName();
7347
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007348 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007349 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007350 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007351 if (!PointeeTy->isIncompleteType() &&
7352 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007353 ActionIdx = 2; // If the pointee's size is sizeof(char),
7354 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007355
7356 // If the function is defined as a builtin macro, do not show macro
7357 // expansion.
7358 SourceLocation SL = SizeOfArg->getExprLoc();
7359 SourceRange DSR = Dest->getSourceRange();
7360 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007361 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007362
7363 if (SM.isMacroArgExpansion(SL)) {
7364 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7365 SL = SM.getSpellingLoc(SL);
7366 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7367 SM.getSpellingLoc(DSR.getEnd()));
7368 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7369 SM.getSpellingLoc(SSR.getEnd()));
7370 }
7371
Anna Zaksd08d9152012-05-30 23:14:52 +00007372 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007373 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007374 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007375 << PointeeTy
7376 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007377 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007378 << SSR);
7379 DiagRuntimeBehavior(SL, SizeOfArg,
7380 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7381 << ActionIdx
7382 << SSR);
7383
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007384 break;
7385 }
7386 }
7387
7388 // Also check for cases where the sizeof argument is the exact same
7389 // type as the memory argument, and where it points to a user-defined
7390 // record type.
7391 if (SizeOfArgTy != QualType()) {
7392 if (PointeeTy->isRecordType() &&
7393 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7394 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7395 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7396 << FnName << SizeOfArgTy << ArgIdx
7397 << PointeeTy << Dest->getSourceRange()
7398 << LenExpr->getSourceRange());
7399 break;
7400 }
Nico Weberc5e73862011-06-14 16:14:58 +00007401 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007402 } else if (DestTy->isArrayType()) {
7403 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007404 }
Nico Weberc5e73862011-06-14 16:14:58 +00007405
Nico Weberc44b35e2015-03-21 17:37:46 +00007406 if (PointeeTy == QualType())
7407 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007408
Nico Weberc44b35e2015-03-21 17:37:46 +00007409 // Always complain about dynamic classes.
7410 bool IsContained;
7411 if (const CXXRecordDecl *ContainedRD =
7412 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007413
Nico Weberc44b35e2015-03-21 17:37:46 +00007414 unsigned OperationType = 0;
7415 // "overwritten" if we're warning about the destination for any call
7416 // but memcmp; otherwise a verb appropriate to the call.
7417 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7418 if (BId == Builtin::BImemcpy)
7419 OperationType = 1;
7420 else if(BId == Builtin::BImemmove)
7421 OperationType = 2;
7422 else if (BId == Builtin::BImemcmp)
7423 OperationType = 3;
7424 }
7425
John McCall31168b02011-06-15 23:02:42 +00007426 DiagRuntimeBehavior(
7427 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007428 PDiag(diag::warn_dyn_class_memaccess)
7429 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7430 << FnName << IsContained << ContainedRD << OperationType
7431 << Call->getCallee()->getSourceRange());
7432 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7433 BId != Builtin::BImemset)
7434 DiagRuntimeBehavior(
7435 Dest->getExprLoc(), Dest,
7436 PDiag(diag::warn_arc_object_memaccess)
7437 << ArgIdx << FnName << PointeeTy
7438 << Call->getCallee()->getSourceRange());
7439 else
7440 continue;
7441
7442 DiagRuntimeBehavior(
7443 Dest->getExprLoc(), Dest,
7444 PDiag(diag::note_bad_memaccess_silence)
7445 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7446 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007447 }
7448}
7449
Ted Kremenek6865f772011-08-18 20:55:45 +00007450// A little helper routine: ignore addition and subtraction of integer literals.
7451// This intentionally does not ignore all integer constant expressions because
7452// we don't want to remove sizeof().
7453static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7454 Ex = Ex->IgnoreParenCasts();
7455
7456 for (;;) {
7457 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7458 if (!BO || !BO->isAdditiveOp())
7459 break;
7460
7461 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7462 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7463
7464 if (isa<IntegerLiteral>(RHS))
7465 Ex = LHS;
7466 else if (isa<IntegerLiteral>(LHS))
7467 Ex = RHS;
7468 else
7469 break;
7470 }
7471
7472 return Ex;
7473}
7474
Anna Zaks13b08572012-08-08 21:42:23 +00007475static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7476 ASTContext &Context) {
7477 // Only handle constant-sized or VLAs, but not flexible members.
7478 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7479 // Only issue the FIXIT for arrays of size > 1.
7480 if (CAT->getSize().getSExtValue() <= 1)
7481 return false;
7482 } else if (!Ty->isVariableArrayType()) {
7483 return false;
7484 }
7485 return true;
7486}
7487
Ted Kremenek6865f772011-08-18 20:55:45 +00007488// Warn if the user has made the 'size' argument to strlcpy or strlcat
7489// be the size of the source, instead of the destination.
7490void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7491 IdentifierInfo *FnName) {
7492
7493 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007494 unsigned NumArgs = Call->getNumArgs();
7495 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007496 return;
7497
7498 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7499 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007500 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007501
7502 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7503 Call->getLocStart(), Call->getRParenLoc()))
7504 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007505
7506 // Look for 'strlcpy(dst, x, sizeof(x))'
7507 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7508 CompareWithSrc = Ex;
7509 else {
7510 // Look for 'strlcpy(dst, x, strlen(x))'
7511 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007512 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7513 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007514 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7515 }
7516 }
7517
7518 if (!CompareWithSrc)
7519 return;
7520
7521 // Determine if the argument to sizeof/strlen is equal to the source
7522 // argument. In principle there's all kinds of things you could do
7523 // here, for instance creating an == expression and evaluating it with
7524 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7525 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7526 if (!SrcArgDRE)
7527 return;
7528
7529 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7530 if (!CompareWithSrcDRE ||
7531 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7532 return;
7533
7534 const Expr *OriginalSizeArg = Call->getArg(2);
7535 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7536 << OriginalSizeArg->getSourceRange() << FnName;
7537
7538 // Output a FIXIT hint if the destination is an array (rather than a
7539 // pointer to an array). This could be enhanced to handle some
7540 // pointers if we know the actual size, like if DstArg is 'array+2'
7541 // we could say 'sizeof(array)-2'.
7542 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007543 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007544 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007545
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007546 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007547 llvm::raw_svector_ostream OS(sizeString);
7548 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007549 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007550 OS << ")";
7551
7552 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7553 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7554 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007555}
7556
Anna Zaks314cd092012-02-01 19:08:57 +00007557/// Check if two expressions refer to the same declaration.
7558static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7559 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7560 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7561 return D1->getDecl() == D2->getDecl();
7562 return false;
7563}
7564
7565static const Expr *getStrlenExprArg(const Expr *E) {
7566 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7567 const FunctionDecl *FD = CE->getDirectCallee();
7568 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007569 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007570 return CE->getArg(0)->IgnoreParenCasts();
7571 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007572 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007573}
7574
7575// Warn on anti-patterns as the 'size' argument to strncat.
7576// The correct size argument should look like following:
7577// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7578void Sema::CheckStrncatArguments(const CallExpr *CE,
7579 IdentifierInfo *FnName) {
7580 // Don't crash if the user has the wrong number of arguments.
7581 if (CE->getNumArgs() < 3)
7582 return;
7583 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7584 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7585 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7586
Nico Weber0e6daef2013-12-26 23:38:39 +00007587 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7588 CE->getRParenLoc()))
7589 return;
7590
Anna Zaks314cd092012-02-01 19:08:57 +00007591 // Identify common expressions, which are wrongly used as the size argument
7592 // to strncat and may lead to buffer overflows.
7593 unsigned PatternType = 0;
7594 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7595 // - sizeof(dst)
7596 if (referToTheSameDecl(SizeOfArg, DstArg))
7597 PatternType = 1;
7598 // - sizeof(src)
7599 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7600 PatternType = 2;
7601 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7602 if (BE->getOpcode() == BO_Sub) {
7603 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7604 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7605 // - sizeof(dst) - strlen(dst)
7606 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7607 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7608 PatternType = 1;
7609 // - sizeof(src) - (anything)
7610 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7611 PatternType = 2;
7612 }
7613 }
7614
7615 if (PatternType == 0)
7616 return;
7617
Anna Zaks5069aa32012-02-03 01:27:37 +00007618 // Generate the diagnostic.
7619 SourceLocation SL = LenArg->getLocStart();
7620 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007621 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007622
7623 // If the function is defined as a builtin macro, do not show macro expansion.
7624 if (SM.isMacroArgExpansion(SL)) {
7625 SL = SM.getSpellingLoc(SL);
7626 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7627 SM.getSpellingLoc(SR.getEnd()));
7628 }
7629
Anna Zaks13b08572012-08-08 21:42:23 +00007630 // Check if the destination is an array (rather than a pointer to an array).
7631 QualType DstTy = DstArg->getType();
7632 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7633 Context);
7634 if (!isKnownSizeArray) {
7635 if (PatternType == 1)
7636 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7637 else
7638 Diag(SL, diag::warn_strncat_src_size) << SR;
7639 return;
7640 }
7641
Anna Zaks314cd092012-02-01 19:08:57 +00007642 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007643 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007644 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007645 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007646
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007647 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007648 llvm::raw_svector_ostream OS(sizeString);
7649 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007650 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007651 OS << ") - ";
7652 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007653 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007654 OS << ") - 1";
7655
Anna Zaks5069aa32012-02-03 01:27:37 +00007656 Diag(SL, diag::note_strncat_wrong_size)
7657 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007658}
7659
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007660//===--- CHECK: Return Address of Stack Variable --------------------------===//
7661
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007662static const Expr *EvalVal(const Expr *E,
7663 SmallVectorImpl<const DeclRefExpr *> &refVars,
7664 const Decl *ParentDecl);
7665static const Expr *EvalAddr(const Expr *E,
7666 SmallVectorImpl<const DeclRefExpr *> &refVars,
7667 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007668
7669/// CheckReturnStackAddr - Check if a return statement returns the address
7670/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007671static void
7672CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7673 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00007674
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007675 const Expr *stackE = nullptr;
7676 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007677
7678 // Perform checking for returned stack addresses, local blocks,
7679 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007680 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007681 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007682 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007683 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007684 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007685 }
7686
Craig Topperc3ec1492014-05-26 06:22:03 +00007687 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007688 return; // Nothing suspicious was found.
7689
Simon Pilgrim750bde62017-03-31 11:00:53 +00007690 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007691 // of a parameter reference doesn't need a warning.
7692 for (auto *DRE : refVars)
7693 if (isa<ParmVarDecl>(DRE->getDecl()))
7694 return;
7695
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007696 SourceLocation diagLoc;
7697 SourceRange diagRange;
7698 if (refVars.empty()) {
7699 diagLoc = stackE->getLocStart();
7700 diagRange = stackE->getSourceRange();
7701 } else {
7702 // We followed through a reference variable. 'stackE' contains the
7703 // problematic expression but we will warn at the return statement pointing
7704 // at the reference variable. We will later display the "trail" of
7705 // reference variables using notes.
7706 diagLoc = refVars[0]->getLocStart();
7707 diagRange = refVars[0]->getSourceRange();
7708 }
7709
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007710 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7711 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007712 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007713 << DR->getDecl()->getDeclName() << diagRange;
7714 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007715 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007716 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007717 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007718 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007719 // If there is an LValue->RValue conversion, then the value of the
7720 // reference type is used, not the reference.
7721 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7722 if (ICE->getCastKind() == CK_LValueToRValue) {
7723 return;
7724 }
7725 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007726 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7727 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007728 }
7729
7730 // Display the "trail" of reference variables that we followed until we
7731 // found the problematic expression using notes.
7732 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007733 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007734 // If this var binds to another reference var, show the range of the next
7735 // var, otherwise the var binds to the problematic expression, in which case
7736 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007737 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7738 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007739 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7740 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007741 }
7742}
7743
7744/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7745/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007746/// to a location on the stack, a local block, an address of a label, or a
7747/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007748/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007749/// encounter a subexpression that (1) clearly does not lead to one of the
7750/// above problematic expressions (2) is something we cannot determine leads to
7751/// a problematic expression based on such local checking.
7752///
7753/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7754/// the expression that they point to. Such variables are added to the
7755/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007756///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007757/// EvalAddr processes expressions that are pointers that are used as
7758/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007759/// At the base case of the recursion is a check for the above problematic
7760/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007761///
7762/// This implementation handles:
7763///
7764/// * pointer-to-pointer casts
7765/// * implicit conversions from array references to pointers
7766/// * taking the address of fields
7767/// * arbitrary interplay between "&" and "*" operators
7768/// * pointer arithmetic from an address of a stack variable
7769/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007770static const Expr *EvalAddr(const Expr *E,
7771 SmallVectorImpl<const DeclRefExpr *> &refVars,
7772 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007773 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007774 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007775
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007776 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007777 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007778 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007779 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007780 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007781
Peter Collingbourne91147592011-04-15 00:35:48 +00007782 E = E->IgnoreParens();
7783
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007784 // Our "symbolic interpreter" is just a dispatch off the currently
7785 // viewed AST node. We then recursively traverse the AST by calling
7786 // EvalAddr and EvalVal appropriately.
7787 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007788 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007789 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007790
Richard Smith40f08eb2014-01-30 22:05:38 +00007791 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007792 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007793 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007794
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007795 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007796 // If this is a reference variable, follow through to the expression that
7797 // it points to.
7798 if (V->hasLocalStorage() &&
7799 V->getType()->isReferenceType() && V->hasInit()) {
7800 // Add the reference variable to the "trail".
7801 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007802 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007803 }
7804
Craig Topperc3ec1492014-05-26 06:22:03 +00007805 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007806 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007807
Chris Lattner934edb22007-12-28 05:31:15 +00007808 case Stmt::UnaryOperatorClass: {
7809 // The only unary operator that make sense to handle here
7810 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007811 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007812
John McCalle3027922010-08-25 11:45:40 +00007813 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007814 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007815 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007816 }
Mike Stump11289f42009-09-09 15:08:12 +00007817
Chris Lattner934edb22007-12-28 05:31:15 +00007818 case Stmt::BinaryOperatorClass: {
7819 // Handle pointer arithmetic. All other binary operators are not valid
7820 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007821 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007822 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007823
John McCalle3027922010-08-25 11:45:40 +00007824 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007825 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007826
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007827 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007828
7829 // Determine which argument is the real pointer base. It could be
7830 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007831 if (!Base->getType()->isPointerType())
7832 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007833
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007834 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007835 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007836 }
Steve Naroff2752a172008-09-10 19:17:48 +00007837
Chris Lattner934edb22007-12-28 05:31:15 +00007838 // For conditional operators we need to see if either the LHS or RHS are
7839 // valid DeclRefExpr*s. If one of them is valid, we return it.
7840 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007841 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007842
Chris Lattner934edb22007-12-28 05:31:15 +00007843 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007844 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007845 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007846 // In C++, we can have a throw-expression, which has 'void' type.
7847 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007848 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007849 return LHS;
7850 }
Chris Lattner934edb22007-12-28 05:31:15 +00007851
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007852 // In C++, we can have a throw-expression, which has 'void' type.
7853 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007854 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007855
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007856 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007857 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007858
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007859 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007860 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007861 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007862 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007863
7864 case Stmt::AddrLabelExprClass:
7865 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007866
John McCall28fc7092011-11-10 05:35:25 +00007867 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007868 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7869 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007870
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007871 // For casts, we need to handle conversions from arrays to
7872 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007873 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007874 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007875 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007876 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007877 case Stmt::CXXStaticCastExprClass:
7878 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007879 case Stmt::CXXConstCastExprClass:
7880 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007881 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007882 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007883 case CK_LValueToRValue:
7884 case CK_NoOp:
7885 case CK_BaseToDerived:
7886 case CK_DerivedToBase:
7887 case CK_UncheckedDerivedToBase:
7888 case CK_Dynamic:
7889 case CK_CPointerToObjCPointerCast:
7890 case CK_BlockPointerToObjCPointerCast:
7891 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007892 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007893
7894 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007895 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007896
Richard Trieudadefde2014-07-02 04:39:38 +00007897 case CK_BitCast:
7898 if (SubExpr->getType()->isAnyPointerType() ||
7899 SubExpr->getType()->isBlockPointerType() ||
7900 SubExpr->getType()->isObjCQualifiedIdType())
7901 return EvalAddr(SubExpr, refVars, ParentDecl);
7902 else
7903 return nullptr;
7904
Eli Friedman8195ad72012-02-23 23:04:32 +00007905 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007906 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007907 }
Chris Lattner934edb22007-12-28 05:31:15 +00007908 }
Mike Stump11289f42009-09-09 15:08:12 +00007909
Douglas Gregorfe314812011-06-21 17:03:29 +00007910 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007911 if (const Expr *Result =
7912 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7913 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007914 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007915 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007916
Chris Lattner934edb22007-12-28 05:31:15 +00007917 // Everything else: we simply don't reason about them.
7918 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007919 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007920 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007921}
Mike Stump11289f42009-09-09 15:08:12 +00007922
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007923/// EvalVal - This function is complements EvalAddr in the mutual recursion.
7924/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007925static const Expr *EvalVal(const Expr *E,
7926 SmallVectorImpl<const DeclRefExpr *> &refVars,
7927 const Decl *ParentDecl) {
7928 do {
7929 // We should only be called for evaluating non-pointer expressions, or
7930 // expressions with a pointer type that are not used as references but
7931 // instead
7932 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00007933
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007934 // Our "symbolic interpreter" is just a dispatch off the currently
7935 // viewed AST node. We then recursively traverse the AST by calling
7936 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00007937
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007938 E = E->IgnoreParens();
7939 switch (E->getStmtClass()) {
7940 case Stmt::ImplicitCastExprClass: {
7941 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7942 if (IE->getValueKind() == VK_LValue) {
7943 E = IE->getSubExpr();
7944 continue;
7945 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007946 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007947 }
Richard Smith40f08eb2014-01-30 22:05:38 +00007948
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007949 case Stmt::ExprWithCleanupsClass:
7950 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7951 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007952
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007953 case Stmt::DeclRefExprClass: {
7954 // When we hit a DeclRefExpr we are looking at code that refers to a
7955 // variable's name. If it's not a reference variable we check if it has
7956 // local storage within the function, and if so, return the expression.
7957 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7958
7959 // If we leave the immediate function, the lifetime isn't about to end.
7960 if (DR->refersToEnclosingVariableOrCapture())
7961 return nullptr;
7962
7963 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7964 // Check if it refers to itself, e.g. "int& i = i;".
7965 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007966 return DR;
7967
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007968 if (V->hasLocalStorage()) {
7969 if (!V->getType()->isReferenceType())
7970 return DR;
7971
7972 // Reference variable, follow through to the expression that
7973 // it points to.
7974 if (V->hasInit()) {
7975 // Add the reference variable to the "trail".
7976 refVars.push_back(DR);
7977 return EvalVal(V->getInit(), refVars, V);
7978 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007979 }
7980 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007981
7982 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007983 }
Mike Stump11289f42009-09-09 15:08:12 +00007984
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007985 case Stmt::UnaryOperatorClass: {
7986 // The only unary operator that make sense to handle here
7987 // is Deref. All others don't resolve to a "name." This includes
7988 // handling all sorts of rvalues passed to a unary operator.
7989 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007990
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007991 if (U->getOpcode() == UO_Deref)
7992 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007993
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007994 return nullptr;
7995 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007996
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007997 case Stmt::ArraySubscriptExprClass: {
7998 // Array subscripts are potential references to data on the stack. We
7999 // retrieve the DeclRefExpr* for the array variable if it indeed
8000 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008001 const auto *ASE = cast<ArraySubscriptExpr>(E);
8002 if (ASE->isTypeDependent())
8003 return nullptr;
8004 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008005 }
Mike Stump11289f42009-09-09 15:08:12 +00008006
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008007 case Stmt::OMPArraySectionExprClass: {
8008 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8009 ParentDecl);
8010 }
Mike Stump11289f42009-09-09 15:08:12 +00008011
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008012 case Stmt::ConditionalOperatorClass: {
8013 // For conditional operators we need to see if either the LHS or RHS are
8014 // non-NULL Expr's. If one is non-NULL, we return it.
8015 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008016
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008017 // Handle the GNU extension for missing LHS.
8018 if (const Expr *LHSExpr = C->getLHS()) {
8019 // In C++, we can have a throw-expression, which has 'void' type.
8020 if (!LHSExpr->getType()->isVoidType())
8021 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8022 return LHS;
8023 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008024
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008025 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008026 if (C->getRHS()->getType()->isVoidType())
8027 return nullptr;
8028
8029 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008030 }
8031
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008032 // Accesses to members are potential references to data on the stack.
8033 case Stmt::MemberExprClass: {
8034 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008035
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008036 // Check for indirect access. We only want direct field accesses.
8037 if (M->isArrow())
8038 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008039
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008040 // Check whether the member type is itself a reference, in which case
8041 // we're not going to refer to the member, but to what the member refers
8042 // to.
8043 if (M->getMemberDecl()->getType()->isReferenceType())
8044 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008045
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008046 return EvalVal(M->getBase(), refVars, ParentDecl);
8047 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008048
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008049 case Stmt::MaterializeTemporaryExprClass:
8050 if (const Expr *Result =
8051 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8052 refVars, ParentDecl))
8053 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008054 return E;
8055
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008056 default:
8057 // Check that we don't return or take the address of a reference to a
8058 // temporary. This is only useful in C++.
8059 if (!E->isTypeDependent() && E->isRValue())
8060 return E;
8061
8062 // Everything else: we simply don't reason about them.
8063 return nullptr;
8064 }
8065 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008066}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008067
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008068void
8069Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8070 SourceLocation ReturnLoc,
8071 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008072 const AttrVec *Attrs,
8073 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008074 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8075
8076 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008077 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8078 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008079 CheckNonNullExpr(*this, RetValExp))
8080 Diag(ReturnLoc, diag::warn_null_ret)
8081 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008082
8083 // C++11 [basic.stc.dynamic.allocation]p4:
8084 // If an allocation function declared with a non-throwing
8085 // exception-specification fails to allocate storage, it shall return
8086 // a null pointer. Any other allocation function that fails to allocate
8087 // storage shall indicate failure only by throwing an exception [...]
8088 if (FD) {
8089 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8090 if (Op == OO_New || Op == OO_Array_New) {
8091 const FunctionProtoType *Proto
8092 = FD->getType()->castAs<FunctionProtoType>();
8093 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8094 CheckNonNullExpr(*this, RetValExp))
8095 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8096 << FD << getLangOpts().CPlusPlus11;
8097 }
8098 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008099}
8100
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008101//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8102
8103/// Check for comparisons of floating point operands using != and ==.
8104/// Issue a warning if these are no self-comparisons, as they are not likely
8105/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008106void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008107 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8108 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008109
8110 // Special case: check for x == x (which is OK).
8111 // Do not emit warnings for such cases.
8112 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8113 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8114 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008115 return;
Mike Stump11289f42009-09-09 15:08:12 +00008116
Ted Kremenekeda40e22007-11-29 00:59:04 +00008117 // Special case: check for comparisons against literals that can be exactly
8118 // represented by APFloat. In such cases, do not emit a warning. This
8119 // is a heuristic: often comparison against such literals are used to
8120 // detect if a value in a variable has not changed. This clearly can
8121 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008122 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8123 if (FLL->isExact())
8124 return;
8125 } else
8126 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8127 if (FLR->isExact())
8128 return;
Mike Stump11289f42009-09-09 15:08:12 +00008129
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008130 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008131 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008132 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008133 return;
Mike Stump11289f42009-09-09 15:08:12 +00008134
David Blaikie1f4ff152012-07-16 20:47:22 +00008135 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008136 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008137 return;
Mike Stump11289f42009-09-09 15:08:12 +00008138
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008139 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008140 Diag(Loc, diag::warn_floatingpoint_eq)
8141 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008142}
John McCallca01b222010-01-04 23:21:16 +00008143
John McCall70aa5392010-01-06 05:24:50 +00008144//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8145//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008146
John McCall70aa5392010-01-06 05:24:50 +00008147namespace {
John McCallca01b222010-01-04 23:21:16 +00008148
John McCall70aa5392010-01-06 05:24:50 +00008149/// Structure recording the 'active' range of an integer-valued
8150/// expression.
8151struct IntRange {
8152 /// The number of bits active in the int.
8153 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008154
John McCall70aa5392010-01-06 05:24:50 +00008155 /// True if the int is known not to have negative values.
8156 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008157
John McCall70aa5392010-01-06 05:24:50 +00008158 IntRange(unsigned Width, bool NonNegative)
8159 : Width(Width), NonNegative(NonNegative)
8160 {}
John McCallca01b222010-01-04 23:21:16 +00008161
John McCall817d4af2010-11-10 23:38:19 +00008162 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008163 static IntRange forBoolType() {
8164 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008165 }
8166
John McCall817d4af2010-11-10 23:38:19 +00008167 /// Returns the range of an opaque value of the given integral type.
8168 static IntRange forValueOfType(ASTContext &C, QualType T) {
8169 return forValueOfCanonicalType(C,
8170 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008171 }
8172
John McCall817d4af2010-11-10 23:38:19 +00008173 /// Returns the range of an opaque value of a canonical integral type.
8174 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008175 assert(T->isCanonicalUnqualified());
8176
8177 if (const VectorType *VT = dyn_cast<VectorType>(T))
8178 T = VT->getElementType().getTypePtr();
8179 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8180 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008181 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8182 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008183
David Majnemer6a426652013-06-07 22:07:20 +00008184 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00008185 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00008186 EnumDecl *Enum = ET->getDecl();
Erich Keane69dbbb02017-09-21 19:58:55 +00008187 // In C++11, enums without definitions can have an explicitly specified
8188 // underlying type. Use this type to compute the range.
David Majnemer6a426652013-06-07 22:07:20 +00008189 if (!Enum->isCompleteDefinition())
Erich Keane69dbbb02017-09-21 19:58:55 +00008190 return IntRange(C.getIntWidth(QualType(T, 0)),
8191 !ET->isSignedIntegerOrEnumerationType());
John McCall18a2c2c2010-11-09 22:22:12 +00008192
David Majnemer6a426652013-06-07 22:07:20 +00008193 unsigned NumPositive = Enum->getNumPositiveBits();
8194 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008195
David Majnemer6a426652013-06-07 22:07:20 +00008196 if (NumNegative == 0)
8197 return IntRange(NumPositive, true/*NonNegative*/);
8198 else
8199 return IntRange(std::max(NumPositive + 1, NumNegative),
8200 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008201 }
John McCall70aa5392010-01-06 05:24:50 +00008202
8203 const BuiltinType *BT = cast<BuiltinType>(T);
8204 assert(BT->isInteger());
8205
8206 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8207 }
8208
John McCall817d4af2010-11-10 23:38:19 +00008209 /// Returns the "target" range of a canonical integral type, i.e.
8210 /// the range of values expressible in the type.
8211 ///
8212 /// This matches forValueOfCanonicalType except that enums have the
8213 /// full range of their type, not the range of their enumerators.
8214 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8215 assert(T->isCanonicalUnqualified());
8216
8217 if (const VectorType *VT = dyn_cast<VectorType>(T))
8218 T = VT->getElementType().getTypePtr();
8219 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8220 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008221 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8222 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008223 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008224 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008225
8226 const BuiltinType *BT = cast<BuiltinType>(T);
8227 assert(BT->isInteger());
8228
8229 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8230 }
8231
8232 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008233 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008234 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008235 L.NonNegative && R.NonNegative);
8236 }
8237
John McCall817d4af2010-11-10 23:38:19 +00008238 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008239 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008240 return IntRange(std::min(L.Width, R.Width),
8241 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008242 }
8243};
8244
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008245IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008246 if (value.isSigned() && value.isNegative())
8247 return IntRange(value.getMinSignedBits(), false);
8248
8249 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008250 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008251
8252 // isNonNegative() just checks the sign bit without considering
8253 // signedness.
8254 return IntRange(value.getActiveBits(), true);
8255}
8256
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008257IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8258 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008259 if (result.isInt())
8260 return GetValueRange(C, result.getInt(), MaxWidth);
8261
8262 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008263 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8264 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8265 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8266 R = IntRange::join(R, El);
8267 }
John McCall70aa5392010-01-06 05:24:50 +00008268 return R;
8269 }
8270
8271 if (result.isComplexInt()) {
8272 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8273 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8274 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008275 }
8276
8277 // This can happen with lossless casts to intptr_t of "based" lvalues.
8278 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008279 // FIXME: The only reason we need to pass the type in here is to get
8280 // the sign right on this one case. It would be nice if APValue
8281 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008282 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008283 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008284}
John McCall70aa5392010-01-06 05:24:50 +00008285
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008286QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008287 QualType Ty = E->getType();
8288 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8289 Ty = AtomicRHS->getValueType();
8290 return Ty;
8291}
8292
John McCall70aa5392010-01-06 05:24:50 +00008293/// Pseudo-evaluate the given integer expression, estimating the
8294/// range of values it might take.
8295///
8296/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008297IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008298 E = E->IgnoreParens();
8299
8300 // Try a full evaluation first.
8301 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008302 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008303 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008304
8305 // I think we only want to look through implicit casts here; if the
8306 // user has an explicit widening cast, we should treat the value as
8307 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008308 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008309 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008310 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8311
Eli Friedmane6d33952013-07-08 20:20:06 +00008312 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008313
George Burgess IVdf1ed002016-01-13 01:52:39 +00008314 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8315 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008316
John McCall70aa5392010-01-06 05:24:50 +00008317 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008318 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008319 return OutputTypeRange;
8320
8321 IntRange SubRange
8322 = GetExprRange(C, CE->getSubExpr(),
8323 std::min(MaxWidth, OutputTypeRange.Width));
8324
8325 // Bail out if the subexpr's range is as wide as the cast type.
8326 if (SubRange.Width >= OutputTypeRange.Width)
8327 return OutputTypeRange;
8328
8329 // Otherwise, we take the smaller width, and we're non-negative if
8330 // either the output type or the subexpr is.
8331 return IntRange(SubRange.Width,
8332 SubRange.NonNegative || OutputTypeRange.NonNegative);
8333 }
8334
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008335 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008336 // If we can fold the condition, just take that operand.
8337 bool CondResult;
8338 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8339 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8340 : CO->getFalseExpr(),
8341 MaxWidth);
8342
8343 // Otherwise, conservatively merge.
8344 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8345 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8346 return IntRange::join(L, R);
8347 }
8348
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008349 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008350 switch (BO->getOpcode()) {
8351
8352 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008353 case BO_LAnd:
8354 case BO_LOr:
8355 case BO_LT:
8356 case BO_GT:
8357 case BO_LE:
8358 case BO_GE:
8359 case BO_EQ:
8360 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008361 return IntRange::forBoolType();
8362
John McCallc3688382011-07-13 06:35:24 +00008363 // The type of the assignments is the type of the LHS, so the RHS
8364 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008365 case BO_MulAssign:
8366 case BO_DivAssign:
8367 case BO_RemAssign:
8368 case BO_AddAssign:
8369 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008370 case BO_XorAssign:
8371 case BO_OrAssign:
8372 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008373 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008374
John McCallc3688382011-07-13 06:35:24 +00008375 // Simple assignments just pass through the RHS, which will have
8376 // been coerced to the LHS type.
8377 case BO_Assign:
8378 // TODO: bitfields?
8379 return GetExprRange(C, BO->getRHS(), MaxWidth);
8380
John McCall70aa5392010-01-06 05:24:50 +00008381 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008382 case BO_PtrMemD:
8383 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008384 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008385
John McCall2ce81ad2010-01-06 22:07:33 +00008386 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008387 case BO_And:
8388 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008389 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8390 GetExprRange(C, BO->getRHS(), MaxWidth));
8391
John McCall70aa5392010-01-06 05:24:50 +00008392 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008393 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008394 // ...except that we want to treat '1 << (blah)' as logically
8395 // positive. It's an important idiom.
8396 if (IntegerLiteral *I
8397 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8398 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008399 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008400 return IntRange(R.Width, /*NonNegative*/ true);
8401 }
8402 }
8403 // fallthrough
8404
John McCalle3027922010-08-25 11:45:40 +00008405 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008406 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008407
John McCall2ce81ad2010-01-06 22:07:33 +00008408 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008409 case BO_Shr:
8410 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008411 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8412
8413 // If the shift amount is a positive constant, drop the width by
8414 // that much.
8415 llvm::APSInt shift;
8416 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8417 shift.isNonNegative()) {
8418 unsigned zext = shift.getZExtValue();
8419 if (zext >= L.Width)
8420 L.Width = (L.NonNegative ? 0 : 1);
8421 else
8422 L.Width -= zext;
8423 }
8424
8425 return L;
8426 }
8427
8428 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008429 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008430 return GetExprRange(C, BO->getRHS(), MaxWidth);
8431
John McCall2ce81ad2010-01-06 22:07:33 +00008432 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008433 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008434 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008435 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008436 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008437
John McCall51431812011-07-14 22:39:48 +00008438 // The width of a division result is mostly determined by the size
8439 // of the LHS.
8440 case BO_Div: {
8441 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008442 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008443 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8444
8445 // If the divisor is constant, use that.
8446 llvm::APSInt divisor;
8447 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8448 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8449 if (log2 >= L.Width)
8450 L.Width = (L.NonNegative ? 0 : 1);
8451 else
8452 L.Width = std::min(L.Width - log2, MaxWidth);
8453 return L;
8454 }
8455
8456 // Otherwise, just use the LHS's width.
8457 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8458 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8459 }
8460
8461 // The result of a remainder can't be larger than the result of
8462 // either side.
8463 case BO_Rem: {
8464 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008465 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008466 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8467 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8468
8469 IntRange meet = IntRange::meet(L, R);
8470 meet.Width = std::min(meet.Width, MaxWidth);
8471 return meet;
8472 }
8473
8474 // The default behavior is okay for these.
8475 case BO_Mul:
8476 case BO_Add:
8477 case BO_Xor:
8478 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008479 break;
8480 }
8481
John McCall51431812011-07-14 22:39:48 +00008482 // The default case is to treat the operation as if it were closed
8483 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008484 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8485 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8486 return IntRange::join(L, R);
8487 }
8488
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008489 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008490 switch (UO->getOpcode()) {
8491 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008492 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008493 return IntRange::forBoolType();
8494
8495 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008496 case UO_Deref:
8497 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008498 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008499
8500 default:
8501 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8502 }
8503 }
8504
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008505 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008506 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8507
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008508 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008509 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008510 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008511
Eli Friedmane6d33952013-07-08 20:20:06 +00008512 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008513}
John McCall263a48b2010-01-04 23:31:57 +00008514
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008515IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008516 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008517}
8518
John McCall263a48b2010-01-04 23:31:57 +00008519/// Checks whether the given value, which currently has the given
8520/// source semantics, has the same value when coerced through the
8521/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008522bool IsSameFloatAfterCast(const llvm::APFloat &value,
8523 const llvm::fltSemantics &Src,
8524 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008525 llvm::APFloat truncated = value;
8526
8527 bool ignored;
8528 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8529 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8530
8531 return truncated.bitwiseIsEqual(value);
8532}
8533
8534/// Checks whether the given value, which currently has the given
8535/// source semantics, has the same value when coerced through the
8536/// target semantics.
8537///
8538/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008539bool IsSameFloatAfterCast(const APValue &value,
8540 const llvm::fltSemantics &Src,
8541 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008542 if (value.isFloat())
8543 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8544
8545 if (value.isVector()) {
8546 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8547 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8548 return false;
8549 return true;
8550 }
8551
8552 assert(value.isComplexFloat());
8553 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8554 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8555}
8556
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008557void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008558
Roman Lebedev6de129e2017-10-15 20:13:17 +00008559bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008560 // Suppress cases where we are comparing against an enum constant.
8561 if (const DeclRefExpr *DR =
8562 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8563 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008564 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008565
8566 // Suppress cases where the '0' value is expanded from a macro.
8567 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008568 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008569
Roman Lebedev6de129e2017-10-15 20:13:17 +00008570 return false;
8571}
8572
8573bool isNonBooleanIntegerValue(Expr *E) {
8574 return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
8575}
8576
8577bool isNonBooleanUnsignedValue(Expr *E) {
8578 // We are checking that the expression is not known to have boolean value,
8579 // is an integer type; and is either unsigned after implicit casts,
8580 // or was unsigned before implicit casts.
8581 return isNonBooleanIntegerValue(E) &&
8582 (!E->getType()->isSignedIntegerType() ||
8583 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8584}
8585
8586enum class LimitType {
8587 Max, // e.g. 32767 for short
8588 Min // e.g. -32768 for short
8589};
8590
8591/// Checks whether Expr 'Constant' may be the
8592/// std::numeric_limits<>::max() or std::numeric_limits<>::min()
8593/// of the Expr 'Other'. If true, then returns the limit type (min or max).
8594/// The Value is the evaluation of Constant
8595llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other,
8596 const llvm::APSInt &Value) {
8597 if (IsEnumConstOrFromMacro(S, Constant))
8598 return llvm::Optional<LimitType>();
8599
8600 if (isNonBooleanUnsignedValue(Other) && Value == 0)
8601 return LimitType::Min;
8602
8603 // TODO: Investigate using GetExprRange() to get tighter bounds
8604 // on the bit ranges.
8605 QualType OtherT = Other->IgnoreParenImpCasts()->getType();
8606 if (const auto *AT = OtherT->getAs<AtomicType>())
8607 OtherT = AT->getValueType();
8608
8609 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8610
8611 if (llvm::APSInt::isSameValue(
8612 llvm::APSInt::getMaxValue(OtherRange.Width,
8613 OtherT->isUnsignedIntegerType()),
8614 Value))
8615 return LimitType::Max;
8616
8617 if (llvm::APSInt::isSameValue(
8618 llvm::APSInt::getMinValue(OtherRange.Width,
8619 OtherT->isUnsignedIntegerType()),
8620 Value))
8621 return LimitType::Min;
8622
8623 return llvm::Optional<LimitType>();
John McCallcc7e5bf2010-05-06 08:58:33 +00008624}
8625
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008626bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008627 // Strip off implicit integral promotions.
8628 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008629 if (ICE->getCastKind() != CK_IntegralCast &&
8630 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008631 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008632 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008633 }
8634
8635 return E->getType()->isEnumeralType();
8636}
8637
Roman Lebedev6de129e2017-10-15 20:13:17 +00008638bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8639 Expr *Other, const llvm::APSInt &Value,
8640 bool RhsConstant) {
8641 // Disable warning in template instantiations
8642 // and only analyze <, >, <= and >= operations.
8643 if (S.inTemplateInstantiation() || !E->isRelationalOp())
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008644 return false;
8645
Roman Lebedev6f405db2017-10-12 22:03:20 +00008646 BinaryOperatorKind Op = E->getOpcode();
Roman Lebedev6de129e2017-10-15 20:13:17 +00008647
8648 QualType OType = Other->IgnoreParenImpCasts()->getType();
8649
8650 llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
8651
8652 if (!(isNonBooleanIntegerValue(Other) &&
8653 (ValueType = IsTypeLimit(S, Constant, Other, Value))))
Roman Lebedev6f405db2017-10-12 22:03:20 +00008654 return false;
8655
Roman Lebedev6de129e2017-10-15 20:13:17 +00008656 bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
8657 bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
8658 bool ResultWhenConstNeOther =
8659 ConstIsLowerBound ^ (ValueType == LimitType::Max);
8660 if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
8661 return false; // The comparison is not tautological.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008662
Roman Lebedev6de129e2017-10-15 20:13:17 +00008663 const bool Result = ResultWhenConstEqualsOther;
Roman Lebedev6f405db2017-10-12 22:03:20 +00008664
Roman Lebedev6de129e2017-10-15 20:13:17 +00008665 unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
8666 ? (HasEnumType(Other)
8667 ? diag::warn_unsigned_enum_always_true_comparison
8668 : diag::warn_unsigned_always_true_comparison)
8669 : diag::warn_tautological_constant_compare;
Roman Lebedev6f405db2017-10-12 22:03:20 +00008670
Roman Lebedev6de129e2017-10-15 20:13:17 +00008671 // Should be enough for uint128 (39 decimal digits)
8672 SmallString<64> PrettySourceValue;
8673 llvm::raw_svector_ostream OS(PrettySourceValue);
8674 OS << Value;
8675
8676 S.Diag(E->getOperatorLoc(), Diag)
8677 << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
8678 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8679
8680 return true;
Roman Lebedev6f405db2017-10-12 22:03:20 +00008681}
8682
Roman Lebedev6de129e2017-10-15 20:13:17 +00008683bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
Roman Lebedev6f405db2017-10-12 22:03:20 +00008684 Expr *Other, const llvm::APSInt &Value,
8685 bool RhsConstant) {
8686 // Disable warning in template instantiations.
8687 if (S.inTemplateInstantiation())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008688 return false;
8689
8690 Constant = Constant->IgnoreParenImpCasts();
8691 Other = Other->IgnoreParenImpCasts();
Richard Trieudd51d742013-11-01 21:19:43 +00008692
Richard Trieu0f097742014-04-04 04:13:47 +00008693 // TODO: Investigate using GetExprRange() to get tighter bounds
8694 // on the bit ranges.
8695 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00008696 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00008697 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00008698 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8699 unsigned OtherWidth = OtherRange.Width;
8700
8701 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8702
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008703 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00008704 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008705
Richard Trieu0f097742014-04-04 04:13:47 +00008706 // Used for diagnostic printout.
8707 enum {
8708 LiteralConstant = 0,
8709 CXXBoolLiteralTrue,
8710 CXXBoolLiteralFalse
8711 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008712
Richard Trieu0f097742014-04-04 04:13:47 +00008713 if (!OtherIsBooleanType) {
8714 QualType ConstantT = Constant->getType();
8715 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00008716
Richard Trieu0f097742014-04-04 04:13:47 +00008717 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008718 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008719 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8720 "comparison with non-integer type");
8721
8722 bool ConstantSigned = ConstantT->isSignedIntegerType();
8723 bool CommonSigned = CommonT->isSignedIntegerType();
8724
8725 bool EqualityOnly = false;
8726
8727 if (CommonSigned) {
8728 // The common type is signed, therefore no signed to unsigned conversion.
8729 if (!OtherRange.NonNegative) {
8730 // Check that the constant is representable in type OtherT.
8731 if (ConstantSigned) {
8732 if (OtherWidth >= Value.getMinSignedBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008733 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008734 } else { // !ConstantSigned
8735 if (OtherWidth >= Value.getActiveBits() + 1)
Roman Lebedev6de129e2017-10-15 20:13:17 +00008736 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008737 }
8738 } else { // !OtherSigned
8739 // Check that the constant is representable in type OtherT.
8740 // Negative values are out of range.
8741 if (ConstantSigned) {
8742 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008743 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008744 } else { // !ConstantSigned
8745 if (OtherWidth >= Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008746 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008747 }
Richard Trieu560910c2012-11-14 22:50:24 +00008748 }
Richard Trieu0f097742014-04-04 04:13:47 +00008749 } else { // !CommonSigned
8750 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00008751 if (OtherWidth >= Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008752 return false;
Craig Toppercf360162014-06-18 05:13:11 +00008753 } else { // OtherSigned
8754 assert(!ConstantSigned &&
8755 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00008756 // Check to see if the constant is representable in OtherT.
8757 if (OtherWidth > Value.getActiveBits())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008758 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008759 // Check to see if the constant is equivalent to a negative value
8760 // cast to CommonT.
8761 if (S.Context.getIntWidth(ConstantT) ==
8762 S.Context.getIntWidth(CommonT) &&
8763 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Roman Lebedev6de129e2017-10-15 20:13:17 +00008764 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008765 // The constant value rests between values that OtherT can represent
8766 // after conversion. Relational comparison still works, but equality
8767 // comparisons will be tautological.
8768 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00008769 }
8770 }
Richard Trieu0f097742014-04-04 04:13:47 +00008771
8772 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8773
8774 if (op == BO_EQ || op == BO_NE) {
8775 IsTrue = op == BO_NE;
8776 } else if (EqualityOnly) {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008777 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008778 } else if (RhsConstant) {
8779 if (op == BO_GT || op == BO_GE)
8780 IsTrue = !PositiveConstant;
8781 else // op == BO_LT || op == BO_LE
8782 IsTrue = PositiveConstant;
8783 } else {
8784 if (op == BO_LT || op == BO_LE)
8785 IsTrue = !PositiveConstant;
8786 else // op == BO_GT || op == BO_GE
8787 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00008788 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00008789 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00008790 // Other isKnownToHaveBooleanValue
8791 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8792 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8793 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8794
8795 static const struct LinkedConditions {
8796 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8797 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8798 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8799 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8800 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8801 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8802
8803 } TruthTable = {
8804 // Constant on LHS. | Constant on RHS. |
8805 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
8806 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8807 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8808 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8809 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8810 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8811 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8812 };
8813
8814 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8815
8816 enum ConstantValue ConstVal = Zero;
8817 if (Value.isUnsigned() || Value.isNonNegative()) {
8818 if (Value == 0) {
8819 LiteralOrBoolConstant =
8820 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8821 ConstVal = Zero;
8822 } else if (Value == 1) {
8823 LiteralOrBoolConstant =
8824 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8825 ConstVal = One;
8826 } else {
8827 LiteralOrBoolConstant = LiteralConstant;
8828 ConstVal = GT_One;
8829 }
8830 } else {
8831 ConstVal = LT_Zero;
8832 }
8833
8834 CompareBoolWithConstantResult CmpRes;
8835
8836 switch (op) {
8837 case BO_LT:
8838 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8839 break;
8840 case BO_GT:
8841 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8842 break;
8843 case BO_LE:
8844 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8845 break;
8846 case BO_GE:
8847 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8848 break;
8849 case BO_EQ:
8850 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8851 break;
8852 case BO_NE:
8853 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8854 break;
8855 default:
8856 CmpRes = Unkwn;
8857 break;
8858 }
8859
8860 if (CmpRes == AFals) {
8861 IsTrue = false;
8862 } else if (CmpRes == ATrue) {
8863 IsTrue = true;
8864 } else {
Roman Lebedev6de129e2017-10-15 20:13:17 +00008865 return false;
Richard Trieu0f097742014-04-04 04:13:47 +00008866 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008867 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008868
8869 // If this is a comparison to an enum constant, include that
8870 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008871 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008872 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8873 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8874
8875 SmallString<64> PrettySourceValue;
8876 llvm::raw_svector_ostream OS(PrettySourceValue);
8877 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008878 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008879 else
8880 OS << Value;
8881
Richard Trieu0f097742014-04-04 04:13:47 +00008882 S.DiagRuntimeBehavior(
8883 E->getOperatorLoc(), E,
8884 S.PDiag(diag::warn_out_of_range_compare)
8885 << OS.str() << LiteralOrBoolConstant
8886 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8887 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Roman Lebedev6de129e2017-10-15 20:13:17 +00008888
8889 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008890}
8891
John McCallcc7e5bf2010-05-06 08:58:33 +00008892/// Analyze the operands of the given comparison. Implements the
8893/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008894void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8896 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008897}
John McCall263a48b2010-01-04 23:31:57 +00008898
John McCallca01b222010-01-04 23:21:16 +00008899/// \brief Implements -Wsign-compare.
8900///
Richard Trieu82402a02011-09-15 21:56:47 +00008901/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008902void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008903 // The type the comparison is being performed in.
8904 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008905
8906 // Only analyze comparison operators where both sides have been converted to
8907 // the same type.
8908 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8909 return AnalyzeImpConvsInComparison(S, E);
8910
8911 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008912 if (E->isValueDependent())
8913 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008914
Roman Lebedev6de129e2017-10-15 20:13:17 +00008915 Expr *LHS = E->getLHS();
8916 Expr *RHS = E->getRHS();
8917
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008918 if (T->isIntegralType(S.Context)) {
8919 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008920 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008921
Roman Lebedev6de129e2017-10-15 20:13:17 +00008922 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8923 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008924
Roman Lebedev6de129e2017-10-15 20:13:17 +00008925 // We don't care about expressions whose result is a constant.
8926 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8927 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00008928
Roman Lebedev6de129e2017-10-15 20:13:17 +00008929 // We only care about expressions where just one side is literal
8930 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8931 // Is the constant on the RHS or LHS?
8932 const bool RhsConstant = IsRHSIntegralLiteral;
8933 Expr *Const = RhsConstant ? RHS : LHS;
8934 Expr *Other = RhsConstant ? LHS : RHS;
8935 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8936
8937 // Check whether an integer constant comparison results in a value
8938 // of 'true' or 'false'.
8939
8940 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8941 return AnalyzeImpConvsInComparison(S, E);
8942
8943 if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
8944 return AnalyzeImpConvsInComparison(S, E);
8945 }
8946 }
8947
8948 if (!T->hasUnsignedIntegerRepresentation()) {
8949 // We don't do anything special if this isn't an unsigned integral
8950 // comparison: we're only interested in integral comparisons, and
8951 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008952 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008953 }
8954
8955 LHS = LHS->IgnoreParenImpCasts();
8956 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008957
John McCallcc7e5bf2010-05-06 08:58:33 +00008958 // Check to see if one of the (unmodified) operands is of different
8959 // signedness.
8960 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008961 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8962 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008963 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008964 signedOperand = LHS;
8965 unsignedOperand = RHS;
8966 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8967 signedOperand = RHS;
8968 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008969 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008970 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008971 }
8972
John McCallcc7e5bf2010-05-06 08:58:33 +00008973 // Otherwise, calculate the effective range of the signed operand.
8974 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008975
John McCallcc7e5bf2010-05-06 08:58:33 +00008976 // Go ahead and analyze implicit conversions in the operands. Note
8977 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008978 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8979 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008980
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008981 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008982 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008983 return;
John McCallca01b222010-01-04 23:21:16 +00008984
8985 // For (in)equality comparisons, if the unsigned operand is a
8986 // constant which cannot collide with a overflowed signed operand,
8987 // then reinterpreting the signed operand as unsigned will not
8988 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008989 if (E->isEqualityOp()) {
8990 unsigned comparisonWidth = S.Context.getIntWidth(T);
8991 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008992
John McCallcc7e5bf2010-05-06 08:58:33 +00008993 // We should never be unable to prove that the unsigned operand is
8994 // non-negative.
8995 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8996
8997 if (unsignedRange.Width < comparisonWidth)
8998 return;
8999 }
9000
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009001 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9002 S.PDiag(diag::warn_mixed_sign_comparison)
9003 << LHS->getType() << RHS->getType()
9004 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009005}
9006
John McCall1f425642010-11-11 03:21:53 +00009007/// Analyzes an attempt to assign the given value to a bitfield.
9008///
9009/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009010bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9011 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009012 assert(Bitfield->isBitField());
9013 if (Bitfield->isInvalidDecl())
9014 return false;
9015
John McCalldeebbcf2010-11-11 05:33:51 +00009016 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009017 QualType BitfieldType = Bitfield->getType();
9018 if (BitfieldType->isBooleanType())
9019 return false;
9020
9021 if (BitfieldType->isEnumeralType()) {
9022 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9023 // If the underlying enum type was not explicitly specified as an unsigned
9024 // type and the enum contain only positive values, MSVC++ will cause an
9025 // inconsistency by storing this as a signed type.
9026 if (S.getLangOpts().CPlusPlus11 &&
9027 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9028 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9029 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9030 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9031 << BitfieldEnumDecl->getNameAsString();
9032 }
9033 }
9034
John McCalldeebbcf2010-11-11 05:33:51 +00009035 if (Bitfield->getType()->isBooleanType())
9036 return false;
9037
Douglas Gregor789adec2011-02-04 13:09:01 +00009038 // Ignore value- or type-dependent expressions.
9039 if (Bitfield->getBitWidth()->isValueDependent() ||
9040 Bitfield->getBitWidth()->isTypeDependent() ||
9041 Init->isValueDependent() ||
9042 Init->isTypeDependent())
9043 return false;
9044
John McCall1f425642010-11-11 03:21:53 +00009045 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009046 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009047
Richard Smith5fab0c92011-12-28 19:48:30 +00009048 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009049 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9050 Expr::SE_AllowSideEffects)) {
9051 // The RHS is not constant. If the RHS has an enum type, make sure the
9052 // bitfield is wide enough to hold all the values of the enum without
9053 // truncation.
9054 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9055 EnumDecl *ED = EnumTy->getDecl();
9056 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9057
9058 // Enum types are implicitly signed on Windows, so check if there are any
9059 // negative enumerators to see if the enum was intended to be signed or
9060 // not.
9061 bool SignedEnum = ED->getNumNegativeBits() > 0;
9062
9063 // Check for surprising sign changes when assigning enum values to a
9064 // bitfield of different signedness. If the bitfield is signed and we
9065 // have exactly the right number of bits to store this unsigned enum,
9066 // suggest changing the enum to an unsigned type. This typically happens
9067 // on Windows where unfixed enums always use an underlying type of 'int'.
9068 unsigned DiagID = 0;
9069 if (SignedEnum && !SignedBitfield) {
9070 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9071 } else if (SignedBitfield && !SignedEnum &&
9072 ED->getNumPositiveBits() == FieldWidth) {
9073 DiagID = diag::warn_signed_bitfield_enum_conversion;
9074 }
9075
9076 if (DiagID) {
9077 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9078 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9079 SourceRange TypeRange =
9080 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9081 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9082 << SignedEnum << TypeRange;
9083 }
9084
9085 // Compute the required bitwidth. If the enum has negative values, we need
9086 // one more bit than the normal number of positive bits to represent the
9087 // sign bit.
9088 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9089 ED->getNumNegativeBits())
9090 : ED->getNumPositiveBits();
9091
9092 // Check the bitwidth.
9093 if (BitsNeeded > FieldWidth) {
9094 Expr *WidthExpr = Bitfield->getBitWidth();
9095 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9096 << Bitfield << ED;
9097 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9098 << BitsNeeded << ED << WidthExpr->getSourceRange();
9099 }
9100 }
9101
John McCall1f425642010-11-11 03:21:53 +00009102 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009103 }
John McCall1f425642010-11-11 03:21:53 +00009104
John McCall1f425642010-11-11 03:21:53 +00009105 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009106
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009107 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009108 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009109 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9110 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009111
John McCall1f425642010-11-11 03:21:53 +00009112 if (OriginalWidth <= FieldWidth)
9113 return false;
9114
Eli Friedmanc267a322012-01-26 23:11:39 +00009115 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009116 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009117 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009118
Eli Friedmanc267a322012-01-26 23:11:39 +00009119 // Check whether the stored value is equal to the original value.
9120 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009121 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009122 return false;
9123
Eli Friedmanc267a322012-01-26 23:11:39 +00009124 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009125 // therefore don't strictly fit into a signed bitfield of width 1.
9126 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009127 return false;
9128
John McCall1f425642010-11-11 03:21:53 +00009129 std::string PrettyValue = Value.toString(10);
9130 std::string PrettyTrunc = TruncatedValue.toString(10);
9131
9132 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9133 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9134 << Init->getSourceRange();
9135
9136 return true;
9137}
9138
John McCalld2a53122010-11-09 23:24:47 +00009139/// Analyze the given simple or compound assignment for warning-worthy
9140/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009141void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009142 // Just recurse on the LHS.
9143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9144
9145 // We want to recurse on the RHS as normal unless we're assigning to
9146 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009147 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009148 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009149 E->getOperatorLoc())) {
9150 // Recurse, ignoring any implicit conversions on the RHS.
9151 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9152 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009153 }
9154 }
9155
9156 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9157}
9158
John McCall263a48b2010-01-04 23:31:57 +00009159/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009160void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9161 SourceLocation CContext, unsigned diag,
9162 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009163 if (pruneControlFlow) {
9164 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9165 S.PDiag(diag)
9166 << SourceType << T << E->getSourceRange()
9167 << SourceRange(CContext));
9168 return;
9169 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009170 S.Diag(E->getExprLoc(), diag)
9171 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9172}
9173
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009174/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009175void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9176 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009177 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009178}
9179
Richard Trieube234c32016-04-21 21:04:55 +00009180
9181/// Diagnose an implicit cast from a floating point value to an integer value.
9182void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9183
9184 SourceLocation CContext) {
9185 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009186 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009187
9188 Expr *InnerE = E->IgnoreParenImpCasts();
9189 // We also want to warn on, e.g., "int i = -1.234"
9190 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9191 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9192 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9193
9194 const bool IsLiteral =
9195 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9196
9197 llvm::APFloat Value(0.0);
9198 bool IsConstant =
9199 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9200 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009201 return DiagnoseImpCast(S, E, T, CContext,
9202 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009203 }
9204
Chandler Carruth016ef402011-04-10 08:36:24 +00009205 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009206
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009207 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9208 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009209 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9210 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009211 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009212 if (IsLiteral) return;
9213 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9214 PruneWarnings);
9215 }
9216
9217 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009218 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009219 // Warn on floating point literal to integer.
9220 DiagID = diag::warn_impcast_literal_float_to_integer;
9221 } else if (IntegerValue == 0) {
9222 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9223 return DiagnoseImpCast(S, E, T, CContext,
9224 diag::warn_impcast_float_integer, PruneWarnings);
9225 }
9226 // Warn on non-zero to zero conversion.
9227 DiagID = diag::warn_impcast_float_to_integer_zero;
9228 } else {
9229 if (IntegerValue.isUnsigned()) {
9230 if (!IntegerValue.isMaxValue()) {
9231 return DiagnoseImpCast(S, E, T, CContext,
9232 diag::warn_impcast_float_integer, PruneWarnings);
9233 }
9234 } else { // IntegerValue.isSigned()
9235 if (!IntegerValue.isMaxSignedValue() &&
9236 !IntegerValue.isMinSignedValue()) {
9237 return DiagnoseImpCast(S, E, T, CContext,
9238 diag::warn_impcast_float_integer, PruneWarnings);
9239 }
9240 }
9241 // Warn on evaluatable floating point expression to integer conversion.
9242 DiagID = diag::warn_impcast_float_to_integer;
9243 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009244
Eli Friedman07185912013-08-29 23:44:43 +00009245 // FIXME: Force the precision of the source value down so we don't print
9246 // digits which are usually useless (we don't really care here if we
9247 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9248 // would automatically print the shortest representation, but it's a bit
9249 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009250 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009251 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9252 precision = (precision * 59 + 195) / 196;
9253 Value.toString(PrettySourceValue, precision);
9254
David Blaikie9b88cc02012-05-15 17:18:27 +00009255 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009256 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009257 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009258 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009259 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009260
Richard Trieube234c32016-04-21 21:04:55 +00009261 if (PruneWarnings) {
9262 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9263 S.PDiag(DiagID)
9264 << E->getType() << T.getUnqualifiedType()
9265 << PrettySourceValue << PrettyTargetValue
9266 << E->getSourceRange() << SourceRange(CContext));
9267 } else {
9268 S.Diag(E->getExprLoc(), DiagID)
9269 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9270 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9271 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009272}
9273
John McCall18a2c2c2010-11-09 22:22:12 +00009274std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9275 if (!Range.Width) return "0";
9276
9277 llvm::APSInt ValueInRange = Value;
9278 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009279 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009280 return ValueInRange.toString(10);
9281}
9282
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009283bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009284 if (!isa<ImplicitCastExpr>(Ex))
9285 return false;
9286
9287 Expr *InnerE = Ex->IgnoreParenImpCasts();
9288 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9289 const Type *Source =
9290 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9291 if (Target->isDependentType())
9292 return false;
9293
9294 const BuiltinType *FloatCandidateBT =
9295 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9296 const Type *BoolCandidateType = ToBool ? Target : Source;
9297
9298 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9299 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9300}
9301
9302void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9303 SourceLocation CC) {
9304 unsigned NumArgs = TheCall->getNumArgs();
9305 for (unsigned i = 0; i < NumArgs; ++i) {
9306 Expr *CurrA = TheCall->getArg(i);
9307 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9308 continue;
9309
9310 bool IsSwapped = ((i > 0) &&
9311 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9312 IsSwapped |= ((i < (NumArgs - 1)) &&
9313 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9314 if (IsSwapped) {
9315 // Warn on this floating-point to bool conversion.
9316 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9317 CurrA->getType(), CC,
9318 diag::warn_impcast_floating_point_to_bool);
9319 }
9320 }
9321}
9322
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009323void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009324 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9325 E->getExprLoc()))
9326 return;
9327
Richard Trieu09d6b802016-01-08 23:35:06 +00009328 // Don't warn on functions which have return type nullptr_t.
9329 if (isa<CallExpr>(E))
9330 return;
9331
Richard Trieu5b993502014-10-15 03:42:06 +00009332 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9333 const Expr::NullPointerConstantKind NullKind =
9334 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9335 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9336 return;
9337
9338 // Return if target type is a safe conversion.
9339 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9340 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9341 return;
9342
9343 SourceLocation Loc = E->getSourceRange().getBegin();
9344
Richard Trieu0a5e1662016-02-13 00:58:53 +00009345 // Venture through the macro stacks to get to the source of macro arguments.
9346 // The new location is a better location than the complete location that was
9347 // passed in.
9348 while (S.SourceMgr.isMacroArgExpansion(Loc))
9349 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9350
9351 while (S.SourceMgr.isMacroArgExpansion(CC))
9352 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9353
Richard Trieu5b993502014-10-15 03:42:06 +00009354 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009355 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9356 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9357 Loc, S.SourceMgr, S.getLangOpts());
9358 if (MacroName == "NULL")
9359 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009360 }
9361
9362 // Only warn if the null and context location are in the same macro expansion.
9363 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9364 return;
9365
9366 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9367 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9368 << FixItHint::CreateReplacement(Loc,
9369 S.getFixItZeroLiteralForType(T, Loc));
9370}
9371
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009372void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9373 ObjCArrayLiteral *ArrayLiteral);
9374void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9375 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009376
9377/// Check a single element within a collection literal against the
9378/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009379void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9380 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009381 // Skip a bitcast to 'id' or qualified 'id'.
9382 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9383 if (ICE->getCastKind() == CK_BitCast &&
9384 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9385 Element = ICE->getSubExpr();
9386 }
9387
9388 QualType ElementType = Element->getType();
9389 ExprResult ElementResult(Element);
9390 if (ElementType->getAs<ObjCObjectPointerType>() &&
9391 S.CheckSingleAssignmentConstraints(TargetElementType,
9392 ElementResult,
9393 false, false)
9394 != Sema::Compatible) {
9395 S.Diag(Element->getLocStart(),
9396 diag::warn_objc_collection_literal_element)
9397 << ElementType << ElementKind << TargetElementType
9398 << Element->getSourceRange();
9399 }
9400
9401 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9402 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9403 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9404 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9405}
9406
9407/// Check an Objective-C array literal being converted to the given
9408/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009409void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9410 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009411 if (!S.NSArrayDecl)
9412 return;
9413
9414 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9415 if (!TargetObjCPtr)
9416 return;
9417
9418 if (TargetObjCPtr->isUnspecialized() ||
9419 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9420 != S.NSArrayDecl->getCanonicalDecl())
9421 return;
9422
9423 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9424 if (TypeArgs.size() != 1)
9425 return;
9426
9427 QualType TargetElementType = TypeArgs[0];
9428 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9429 checkObjCCollectionLiteralElement(S, TargetElementType,
9430 ArrayLiteral->getElement(I),
9431 0);
9432 }
9433}
9434
9435/// Check an Objective-C dictionary literal being converted to the given
9436/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009437void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9438 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009439 if (!S.NSDictionaryDecl)
9440 return;
9441
9442 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9443 if (!TargetObjCPtr)
9444 return;
9445
9446 if (TargetObjCPtr->isUnspecialized() ||
9447 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9448 != S.NSDictionaryDecl->getCanonicalDecl())
9449 return;
9450
9451 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9452 if (TypeArgs.size() != 2)
9453 return;
9454
9455 QualType TargetKeyType = TypeArgs[0];
9456 QualType TargetObjectType = TypeArgs[1];
9457 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9458 auto Element = DictionaryLiteral->getKeyValueElement(I);
9459 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9460 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9461 }
9462}
9463
Richard Trieufc404c72016-02-05 23:02:38 +00009464// Helper function to filter out cases for constant width constant conversion.
9465// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009466bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9467 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009468 // If initializing from a constant, and the constant starts with '0',
9469 // then it is a binary, octal, or hexadecimal. Allow these constants
9470 // to fill all the bits, even if there is a sign change.
9471 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9472 const char FirstLiteralCharacter =
9473 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9474 if (FirstLiteralCharacter == '0')
9475 return false;
9476 }
9477
9478 // If the CC location points to a '{', and the type is char, then assume
9479 // assume it is an array initialization.
9480 if (CC.isValid() && T->isCharType()) {
9481 const char FirstContextCharacter =
9482 S.getSourceManager().getCharacterData(CC)[0];
9483 if (FirstContextCharacter == '{')
9484 return false;
9485 }
9486
9487 return true;
9488}
9489
John McCallcc7e5bf2010-05-06 08:58:33 +00009490void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00009491 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009492 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009493
John McCallcc7e5bf2010-05-06 08:58:33 +00009494 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9495 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9496 if (Source == Target) return;
9497 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009498
Chandler Carruthc22845a2011-07-26 05:40:03 +00009499 // If the conversion context location is invalid don't complain. We also
9500 // don't want to emit a warning if the issue occurs from the expansion of
9501 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9502 // delay this check as long as possible. Once we detect we are in that
9503 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009504 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009505 return;
9506
Richard Trieu021baa32011-09-23 20:10:00 +00009507 // Diagnose implicit casts to bool.
9508 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9509 if (isa<StringLiteral>(E))
9510 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009511 // and expressions, for instance, assert(0 && "error here"), are
9512 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009513 return DiagnoseImpCast(S, E, T, CC,
9514 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009515 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9516 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9517 // This covers the literal expressions that evaluate to Objective-C
9518 // objects.
9519 return DiagnoseImpCast(S, E, T, CC,
9520 diag::warn_impcast_objective_c_literal_to_bool);
9521 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009522 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9523 // Warn on pointer to bool conversion that is always true.
9524 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9525 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009526 }
Richard Trieu021baa32011-09-23 20:10:00 +00009527 }
John McCall263a48b2010-01-04 23:31:57 +00009528
Douglas Gregor5054cb02015-07-07 03:58:22 +00009529 // Check implicit casts from Objective-C collection literals to specialized
9530 // collection types, e.g., NSArray<NSString *> *.
9531 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9532 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9533 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9534 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9535
John McCall263a48b2010-01-04 23:31:57 +00009536 // Strip vector types.
9537 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009538 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009539 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009540 return;
John McCallacf0ee52010-10-08 02:01:28 +00009541 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009542 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009543
9544 // If the vector cast is cast between two vectors of the same size, it is
9545 // a bitcast, not a conversion.
9546 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9547 return;
John McCall263a48b2010-01-04 23:31:57 +00009548
9549 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9550 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9551 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009552 if (auto VecTy = dyn_cast<VectorType>(Target))
9553 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009554
9555 // Strip complex types.
9556 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009557 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009558 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009559 return;
9560
Tim Northover02416372017-08-08 23:18:05 +00009561 return DiagnoseImpCast(S, E, T, CC,
9562 S.getLangOpts().CPlusPlus
9563 ? diag::err_impcast_complex_scalar
9564 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009565 }
John McCall263a48b2010-01-04 23:31:57 +00009566
9567 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9568 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9569 }
9570
9571 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9572 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9573
9574 // If the source is floating point...
9575 if (SourceBT && SourceBT->isFloatingPoint()) {
9576 // ...and the target is floating point...
9577 if (TargetBT && TargetBT->isFloatingPoint()) {
9578 // ...then warn if we're dropping FP rank.
9579
9580 // Builtin FP kinds are ordered by increasing FP rank.
9581 if (SourceBT->getKind() > TargetBT->getKind()) {
9582 // Don't warn about float constants that are precisely
9583 // representable in the target type.
9584 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009585 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009586 // Value might be a float, a float vector, or a float complex.
9587 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009588 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9589 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009590 return;
9591 }
9592
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009593 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009594 return;
9595
John McCallacf0ee52010-10-08 02:01:28 +00009596 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009597 }
9598 // ... or possibly if we're increasing rank, too
9599 else if (TargetBT->getKind() > SourceBT->getKind()) {
9600 if (S.SourceMgr.isInSystemMacro(CC))
9601 return;
9602
9603 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009604 }
9605 return;
9606 }
9607
Richard Trieube234c32016-04-21 21:04:55 +00009608 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009609 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009610 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009611 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009612
Richard Trieube234c32016-04-21 21:04:55 +00009613 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009614 }
John McCall263a48b2010-01-04 23:31:57 +00009615
Richard Smith54894fd2015-12-30 01:06:52 +00009616 // Detect the case where a call result is converted from floating-point to
9617 // to bool, and the final argument to the call is converted from bool, to
9618 // discover this typo:
9619 //
9620 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9621 //
9622 // FIXME: This is an incredibly special case; is there some more general
9623 // way to detect this class of misplaced-parentheses bug?
9624 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009625 // Check last argument of function call to see if it is an
9626 // implicit cast from a type matching the type the result
9627 // is being cast to.
9628 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009629 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009630 Expr *LastA = CEx->getArg(NumArgs - 1);
9631 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009632 if (isa<ImplicitCastExpr>(LastA) &&
9633 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009634 // Warn on this floating-point to bool conversion
9635 DiagnoseImpCast(S, E, T, CC,
9636 diag::warn_impcast_floating_point_to_bool);
9637 }
9638 }
9639 }
John McCall263a48b2010-01-04 23:31:57 +00009640 return;
9641 }
9642
Richard Trieu5b993502014-10-15 03:42:06 +00009643 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009644
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009645 S.DiscardMisalignedMemberAddress(Target, E);
9646
David Blaikie9366d2b2012-06-19 21:19:06 +00009647 if (!Source->isIntegerType() || !Target->isIntegerType())
9648 return;
9649
David Blaikie7555b6a2012-05-15 16:56:36 +00009650 // TODO: remove this early return once the false positives for constant->bool
9651 // in templates, macros, etc, are reduced or removed.
9652 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9653 return;
9654
John McCallcc7e5bf2010-05-06 08:58:33 +00009655 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009656 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009657
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009658 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009659 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009660 // TODO: this should happen for bitfield stores, too.
9661 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009662 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009663 if (S.SourceMgr.isInSystemMacro(CC))
9664 return;
9665
John McCall18a2c2c2010-11-09 22:22:12 +00009666 std::string PrettySourceValue = Value.toString(10);
9667 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009668
Ted Kremenek33ba9952011-10-22 02:37:33 +00009669 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9670 S.PDiag(diag::warn_impcast_integer_precision_constant)
9671 << PrettySourceValue << PrettyTargetValue
9672 << E->getType() << T << E->getSourceRange()
9673 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009674 return;
9675 }
9676
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009677 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9678 if (S.SourceMgr.isInSystemMacro(CC))
9679 return;
9680
David Blaikie9455da02012-04-12 22:40:54 +00009681 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009682 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9683 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009684 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009685 }
9686
Richard Trieudcb55572016-01-29 23:51:16 +00009687 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9688 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9689 // Warn when doing a signed to signed conversion, warn if the positive
9690 // source value is exactly the width of the target type, which will
9691 // cause a negative value to be stored.
9692
9693 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009694 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9695 !S.SourceMgr.isInSystemMacro(CC)) {
9696 if (isSameWidthConstantConversion(S, E, T, CC)) {
9697 std::string PrettySourceValue = Value.toString(10);
9698 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009699
Richard Trieufc404c72016-02-05 23:02:38 +00009700 S.DiagRuntimeBehavior(
9701 E->getExprLoc(), E,
9702 S.PDiag(diag::warn_impcast_integer_precision_constant)
9703 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9704 << E->getSourceRange() << clang::SourceRange(CC));
9705 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009706 }
9707 }
Richard Trieufc404c72016-02-05 23:02:38 +00009708
Richard Trieudcb55572016-01-29 23:51:16 +00009709 // Fall through for non-constants to give a sign conversion warning.
9710 }
9711
John McCallcc7e5bf2010-05-06 08:58:33 +00009712 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9713 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9714 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009715 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009716 return;
9717
John McCallcc7e5bf2010-05-06 08:58:33 +00009718 unsigned DiagID = diag::warn_impcast_integer_sign;
9719
9720 // Traditionally, gcc has warned about this under -Wsign-compare.
9721 // We also want to warn about it in -Wconversion.
9722 // So if -Wconversion is off, use a completely identical diagnostic
9723 // in the sign-compare group.
9724 // The conditional-checking code will
9725 if (ICContext) {
9726 DiagID = diag::warn_impcast_integer_sign_conditional;
9727 *ICContext = true;
9728 }
9729
John McCallacf0ee52010-10-08 02:01:28 +00009730 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009731 }
9732
Douglas Gregora78f1932011-02-22 02:45:07 +00009733 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009734 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9735 // type, to give us better diagnostics.
9736 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009737 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9739 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9740 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9741 SourceType = S.Context.getTypeDeclType(Enum);
9742 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9743 }
9744 }
9745
Douglas Gregora78f1932011-02-22 02:45:07 +00009746 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9747 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009748 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9749 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009750 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009751 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009752 return;
9753
Douglas Gregor364f7db2011-03-12 00:14:31 +00009754 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009755 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009756 }
John McCall263a48b2010-01-04 23:31:57 +00009757}
9758
David Blaikie18e9ac72012-05-15 21:57:38 +00009759void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9760 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009761
9762void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00009763 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009764 E = E->IgnoreParenImpCasts();
9765
9766 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009767 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009768
John McCallacf0ee52010-10-08 02:01:28 +00009769 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009770 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009771 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009772}
9773
David Blaikie18e9ac72012-05-15 21:57:38 +00009774void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9775 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009776 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009777
9778 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009779 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9780 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009781
9782 // If -Wconversion would have warned about either of the candidates
9783 // for a signedness conversion to the context type...
9784 if (!Suspicious) return;
9785
9786 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009787 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009788 return;
9789
John McCallcc7e5bf2010-05-06 08:58:33 +00009790 // ...then check whether it would have warned about either of the
9791 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009792 if (E->getType() == T) return;
9793
9794 Suspicious = false;
9795 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9796 E->getType(), CC, &Suspicious);
9797 if (!Suspicious)
9798 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009799 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009800}
9801
Richard Trieu65724892014-11-15 06:37:39 +00009802/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9803/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009804void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009805 if (S.getLangOpts().Bool)
9806 return;
9807 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9808}
9809
John McCallcc7e5bf2010-05-06 08:58:33 +00009810/// AnalyzeImplicitConversions - Find and report any interesting
9811/// implicit conversions in the given expression. There are a couple
9812/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00009813void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009814 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009815 Expr *E = OrigE->IgnoreParenImpCasts();
9816
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009817 if (E->isTypeDependent() || E->isValueDependent())
9818 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009819
John McCallcc7e5bf2010-05-06 08:58:33 +00009820 // For conditional operators, we analyze the arguments as if they
9821 // were being fed directly into the output.
9822 if (isa<ConditionalOperator>(E)) {
9823 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009824 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009825 return;
9826 }
9827
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009828 // Check implicit argument conversions for function calls.
9829 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9830 CheckImplicitArgumentConversions(S, Call, CC);
9831
John McCallcc7e5bf2010-05-06 08:58:33 +00009832 // Go ahead and check any implicit conversions we might have skipped.
9833 // The non-canonical typecheck is just an optimization;
9834 // CheckImplicitConversion will filter out dead implicit conversions.
9835 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009836 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009837
9838 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009839
9840 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9841 // The bound subexpressions in a PseudoObjectExpr are not reachable
9842 // as transitive children.
9843 // FIXME: Use a more uniform representation for this.
9844 for (auto *SE : POE->semantics())
9845 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9846 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009847 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009848
John McCallcc7e5bf2010-05-06 08:58:33 +00009849 // Skip past explicit casts.
9850 if (isa<ExplicitCastExpr>(E)) {
9851 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009852 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009853 }
9854
John McCalld2a53122010-11-09 23:24:47 +00009855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9856 // Do a somewhat different check with comparison operators.
9857 if (BO->isComparisonOp())
9858 return AnalyzeComparison(S, BO);
9859
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009860 // And with simple assignments.
9861 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009862 return AnalyzeAssignment(S, BO);
9863 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009864
9865 // These break the otherwise-useful invariant below. Fortunately,
9866 // we don't really need to recurse into them, because any internal
9867 // expressions should have been analyzed already when they were
9868 // built into statements.
9869 if (isa<StmtExpr>(E)) return;
9870
9871 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009872 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009873
9874 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009875 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009876 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009877 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009878 for (Stmt *SubStmt : E->children()) {
9879 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009880 if (!ChildExpr)
9881 continue;
9882
Richard Trieu955231d2014-01-25 01:10:35 +00009883 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009884 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009885 // Ignore checking string literals that are in logical and operators.
9886 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009887 continue;
9888 AnalyzeImplicitConversions(S, ChildExpr, CC);
9889 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009890
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009891 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009892 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9893 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009894 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009895
9896 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9897 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009898 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009899 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009900
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009901 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9902 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009903 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009904}
9905
9906} // end anonymous namespace
9907
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009908/// Diagnose integer type and any valid implicit convertion to it.
9909static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9910 // Taking into account implicit conversions,
9911 // allow any integer.
9912 if (!E->getType()->isIntegerType()) {
9913 S.Diag(E->getLocStart(),
9914 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9915 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009916 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009917 // Potentially emit standard warnings for implicit conversions if enabled
9918 // using -Wconversion.
9919 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9920 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009921}
9922
Richard Trieuc1888e02014-06-28 23:25:37 +00009923// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9924// Returns true when emitting a warning about taking the address of a reference.
9925static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009926 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009927 E = E->IgnoreParenImpCasts();
9928
9929 const FunctionDecl *FD = nullptr;
9930
9931 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9932 if (!DRE->getDecl()->getType()->isReferenceType())
9933 return false;
9934 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9935 if (!M->getMemberDecl()->getType()->isReferenceType())
9936 return false;
9937 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009938 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009939 return false;
9940 FD = Call->getDirectCallee();
9941 } else {
9942 return false;
9943 }
9944
9945 SemaRef.Diag(E->getExprLoc(), PD);
9946
9947 // If possible, point to location of function.
9948 if (FD) {
9949 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9950 }
9951
9952 return true;
9953}
9954
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009955// Returns true if the SourceLocation is expanded from any macro body.
9956// Returns false if the SourceLocation is invalid, is from not in a macro
9957// expansion, or is from expanded from a top-level macro argument.
9958static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9959 if (Loc.isInvalid())
9960 return false;
9961
9962 while (Loc.isMacroID()) {
9963 if (SM.isMacroBodyExpansion(Loc))
9964 return true;
9965 Loc = SM.getImmediateMacroCallerLoc(Loc);
9966 }
9967
9968 return false;
9969}
9970
Richard Trieu3bb8b562014-02-26 02:36:06 +00009971/// \brief Diagnose pointers that are always non-null.
9972/// \param E the expression containing the pointer
9973/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9974/// compared to a null pointer
9975/// \param IsEqual True when the comparison is equal to a null pointer
9976/// \param Range Extra SourceRange to highlight in the diagnostic
9977void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9978 Expr::NullPointerConstantKind NullKind,
9979 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009980 if (!E)
9981 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009982
9983 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009984 if (E->getExprLoc().isMacroID()) {
9985 const SourceManager &SM = getSourceManager();
9986 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9987 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00009988 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009989 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009990 E = E->IgnoreImpCasts();
9991
9992 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9993
Richard Trieuf7432752014-06-06 21:39:26 +00009994 if (isa<CXXThisExpr>(E)) {
9995 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9996 : diag::warn_this_bool_conversion;
9997 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9998 return;
9999 }
10000
Richard Trieu3bb8b562014-02-26 02:36:06 +000010001 bool IsAddressOf = false;
10002
10003 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10004 if (UO->getOpcode() != UO_AddrOf)
10005 return;
10006 IsAddressOf = true;
10007 E = UO->getSubExpr();
10008 }
10009
Richard Trieuc1888e02014-06-28 23:25:37 +000010010 if (IsAddressOf) {
10011 unsigned DiagID = IsCompare
10012 ? diag::warn_address_of_reference_null_compare
10013 : diag::warn_address_of_reference_bool_conversion;
10014 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10015 << IsEqual;
10016 if (CheckForReference(*this, E, PD)) {
10017 return;
10018 }
10019 }
10020
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010021 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10022 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010023 std::string Str;
10024 llvm::raw_string_ostream S(Str);
10025 E->printPretty(S, nullptr, getPrintingPolicy());
10026 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10027 : diag::warn_cast_nonnull_to_bool;
10028 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10029 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010030 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010031 };
10032
10033 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10034 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10035 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010036 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10037 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010038 return;
10039 }
10040 }
10041 }
10042
Richard Trieu3bb8b562014-02-26 02:36:06 +000010043 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010044 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010045 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10046 D = R->getDecl();
10047 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10048 D = M->getMemberDecl();
10049 }
10050
10051 // Weak Decls can be null.
10052 if (!D || D->isWeak())
10053 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010054
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010055 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010056 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10057 if (getCurFunction() &&
10058 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010059 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10060 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010061 return;
10062 }
10063
10064 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010065 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010066 assert(ParamIter != FD->param_end());
10067 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10068
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010069 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10070 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010071 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010072 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010073 }
George Burgess IV850269a2015-12-08 22:02:00 +000010074
10075 for (unsigned ArgNo : NonNull->args()) {
10076 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010077 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010078 return;
10079 }
George Burgess IV850269a2015-12-08 22:02:00 +000010080 }
10081 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010082 }
10083 }
George Burgess IV850269a2015-12-08 22:02:00 +000010084 }
10085
Richard Trieu3bb8b562014-02-26 02:36:06 +000010086 QualType T = D->getType();
10087 const bool IsArray = T->isArrayType();
10088 const bool IsFunction = T->isFunctionType();
10089
Richard Trieuc1888e02014-06-28 23:25:37 +000010090 // Address of function is used to silence the function warning.
10091 if (IsAddressOf && IsFunction) {
10092 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010093 }
10094
10095 // Found nothing.
10096 if (!IsAddressOf && !IsFunction && !IsArray)
10097 return;
10098
10099 // Pretty print the expression for the diagnostic.
10100 std::string Str;
10101 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010102 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010103
10104 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10105 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010106 enum {
10107 AddressOf,
10108 FunctionPointer,
10109 ArrayPointer
10110 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010111 if (IsAddressOf)
10112 DiagType = AddressOf;
10113 else if (IsFunction)
10114 DiagType = FunctionPointer;
10115 else if (IsArray)
10116 DiagType = ArrayPointer;
10117 else
10118 llvm_unreachable("Could not determine diagnostic.");
10119 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10120 << Range << IsEqual;
10121
10122 if (!IsFunction)
10123 return;
10124
10125 // Suggest '&' to silence the function warning.
10126 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10127 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10128
10129 // Check to see if '()' fixit should be emitted.
10130 QualType ReturnType;
10131 UnresolvedSet<4> NonTemplateOverloads;
10132 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10133 if (ReturnType.isNull())
10134 return;
10135
10136 if (IsCompare) {
10137 // There are two cases here. If there is null constant, the only suggest
10138 // for a pointer return type. If the null is 0, then suggest if the return
10139 // type is a pointer or an integer type.
10140 if (!ReturnType->isPointerType()) {
10141 if (NullKind == Expr::NPCK_ZeroExpression ||
10142 NullKind == Expr::NPCK_ZeroLiteral) {
10143 if (!ReturnType->isIntegerType())
10144 return;
10145 } else {
10146 return;
10147 }
10148 }
10149 } else { // !IsCompare
10150 // For function to bool, only suggest if the function pointer has bool
10151 // return type.
10152 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10153 return;
10154 }
10155 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010156 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010157}
10158
John McCallcc7e5bf2010-05-06 08:58:33 +000010159/// Diagnoses "dangerous" implicit conversions within the given
10160/// expression (which is a full expression). Implements -Wconversion
10161/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010162///
10163/// \param CC the "context" location of the implicit conversion, i.e.
10164/// the most location of the syntactic entity requiring the implicit
10165/// conversion
10166void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010167 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010168 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010169 return;
10170
10171 // Don't diagnose for value- or type-dependent expressions.
10172 if (E->isTypeDependent() || E->isValueDependent())
10173 return;
10174
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010175 // Check for array bounds violations in cases where the check isn't triggered
10176 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10177 // ArraySubscriptExpr is on the RHS of a variable initialization.
10178 CheckArrayAccess(E);
10179
John McCallacf0ee52010-10-08 02:01:28 +000010180 // This is not the right CC for (e.g.) a variable initialization.
10181 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010182}
10183
Richard Trieu65724892014-11-15 06:37:39 +000010184/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10185/// Input argument E is a logical expression.
10186void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10187 ::CheckBoolLikeConversion(*this, E, CC);
10188}
10189
Richard Smith9f7df0c2017-06-26 23:19:32 +000010190/// Diagnose when expression is an integer constant expression and its evaluation
10191/// results in integer overflow
10192void Sema::CheckForIntOverflow (Expr *E) {
10193 // Use a work list to deal with nested struct initializers.
10194 SmallVector<Expr *, 2> Exprs(1, E);
10195
10196 do {
10197 Expr *E = Exprs.pop_back_val();
10198
10199 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10200 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10201 continue;
10202 }
10203
10204 if (auto InitList = dyn_cast<InitListExpr>(E))
10205 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10206
10207 if (isa<ObjCBoxedExpr>(E))
10208 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10209 } while (!Exprs.empty());
10210}
10211
Richard Smithc406cb72013-01-17 01:17:56 +000010212namespace {
10213/// \brief Visitor for expressions which looks for unsequenced operations on the
10214/// same object.
10215class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010216 typedef EvaluatedExprVisitor<SequenceChecker> Base;
10217
Richard Smithc406cb72013-01-17 01:17:56 +000010218 /// \brief A tree of sequenced regions within an expression. Two regions are
10219 /// unsequenced if one is an ancestor or a descendent of the other. When we
10220 /// finish processing an expression with sequencing, such as a comma
10221 /// expression, we fold its tree nodes into its parent, since they are
10222 /// unsequenced with respect to nodes we will visit later.
10223 class SequenceTree {
10224 struct Value {
10225 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10226 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010227 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010228 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010229 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010230
10231 public:
10232 /// \brief A region within an expression which may be sequenced with respect
10233 /// to some other region.
10234 class Seq {
10235 explicit Seq(unsigned N) : Index(N) {}
10236 unsigned Index;
10237 friend class SequenceTree;
10238 public:
10239 Seq() : Index(0) {}
10240 };
10241
10242 SequenceTree() { Values.push_back(Value(0)); }
10243 Seq root() const { return Seq(0); }
10244
10245 /// \brief Create a new sequence of operations, which is an unsequenced
10246 /// subset of \p Parent. This sequence of operations is sequenced with
10247 /// respect to other children of \p Parent.
10248 Seq allocate(Seq Parent) {
10249 Values.push_back(Value(Parent.Index));
10250 return Seq(Values.size() - 1);
10251 }
10252
10253 /// \brief Merge a sequence of operations into its parent.
10254 void merge(Seq S) {
10255 Values[S.Index].Merged = true;
10256 }
10257
10258 /// \brief Determine whether two operations are unsequenced. This operation
10259 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10260 /// should have been merged into its parent as appropriate.
10261 bool isUnsequenced(Seq Cur, Seq Old) {
10262 unsigned C = representative(Cur.Index);
10263 unsigned Target = representative(Old.Index);
10264 while (C >= Target) {
10265 if (C == Target)
10266 return true;
10267 C = Values[C].Parent;
10268 }
10269 return false;
10270 }
10271
10272 private:
10273 /// \brief Pick a representative for a sequence.
10274 unsigned representative(unsigned K) {
10275 if (Values[K].Merged)
10276 // Perform path compression as we go.
10277 return Values[K].Parent = representative(Values[K].Parent);
10278 return K;
10279 }
10280 };
10281
10282 /// An object for which we can track unsequenced uses.
10283 typedef NamedDecl *Object;
10284
10285 /// Different flavors of object usage which we track. We only track the
10286 /// least-sequenced usage of each kind.
10287 enum UsageKind {
10288 /// A read of an object. Multiple unsequenced reads are OK.
10289 UK_Use,
10290 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010291 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010292 UK_ModAsValue,
10293 /// A modification of an object which is not sequenced before the value
10294 /// computation of the expression, such as n++.
10295 UK_ModAsSideEffect,
10296
10297 UK_Count = UK_ModAsSideEffect + 1
10298 };
10299
10300 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +000010301 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000010302 Expr *Use;
10303 SequenceTree::Seq Seq;
10304 };
10305
10306 struct UsageInfo {
10307 UsageInfo() : Diagnosed(false) {}
10308 Usage Uses[UK_Count];
10309 /// Have we issued a diagnostic for this variable already?
10310 bool Diagnosed;
10311 };
10312 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10313
10314 Sema &SemaRef;
10315 /// Sequenced regions within the expression.
10316 SequenceTree Tree;
10317 /// Declaration modifications and references which we have seen.
10318 UsageInfoMap UsageMap;
10319 /// The region we are currently within.
10320 SequenceTree::Seq Region;
10321 /// Filled in with declarations which were modified as a side-effect
10322 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010323 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +000010324 /// Expressions to check later. We defer checking these to reduce
10325 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010326 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010327
10328 /// RAII object wrapping the visitation of a sequenced subexpression of an
10329 /// expression. At the end of this process, the side-effects of the evaluation
10330 /// become sequenced with respect to the value computation of the result, so
10331 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10332 /// UK_ModAsValue.
10333 struct SequencedSubexpression {
10334 SequencedSubexpression(SequenceChecker &Self)
10335 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10336 Self.ModAsSideEffect = &ModAsSideEffect;
10337 }
10338 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010339 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10340 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010341 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010342 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10343 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010344 }
10345 Self.ModAsSideEffect = OldModAsSideEffect;
10346 }
10347
10348 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010349 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10350 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010351 };
10352
Richard Smith40238f02013-06-20 22:21:56 +000010353 /// RAII object wrapping the visitation of a subexpression which we might
10354 /// choose to evaluate as a constant. If any subexpression is evaluated and
10355 /// found to be non-constant, this allows us to suppress the evaluation of
10356 /// the outer expression.
10357 class EvaluationTracker {
10358 public:
10359 EvaluationTracker(SequenceChecker &Self)
10360 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10361 Self.EvalTracker = this;
10362 }
10363 ~EvaluationTracker() {
10364 Self.EvalTracker = Prev;
10365 if (Prev)
10366 Prev->EvalOK &= EvalOK;
10367 }
10368
10369 bool evaluate(const Expr *E, bool &Result) {
10370 if (!EvalOK || E->isValueDependent())
10371 return false;
10372 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10373 return EvalOK;
10374 }
10375
10376 private:
10377 SequenceChecker &Self;
10378 EvaluationTracker *Prev;
10379 bool EvalOK;
10380 } *EvalTracker;
10381
Richard Smithc406cb72013-01-17 01:17:56 +000010382 /// \brief Find the object which is produced by the specified expression,
10383 /// if any.
10384 Object getObject(Expr *E, bool Mod) const {
10385 E = E->IgnoreParenCasts();
10386 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10387 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10388 return getObject(UO->getSubExpr(), Mod);
10389 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10390 if (BO->getOpcode() == BO_Comma)
10391 return getObject(BO->getRHS(), Mod);
10392 if (Mod && BO->isAssignmentOp())
10393 return getObject(BO->getLHS(), Mod);
10394 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10395 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10396 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10397 return ME->getMemberDecl();
10398 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10399 // FIXME: If this is a reference, map through to its value.
10400 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010401 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010402 }
10403
10404 /// \brief Note that an object was modified or used by an expression.
10405 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10406 Usage &U = UI.Uses[UK];
10407 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10408 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10409 ModAsSideEffect->push_back(std::make_pair(O, U));
10410 U.Use = Ref;
10411 U.Seq = Region;
10412 }
10413 }
10414 /// \brief Check whether a modification or use conflicts with a prior usage.
10415 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10416 bool IsModMod) {
10417 if (UI.Diagnosed)
10418 return;
10419
10420 const Usage &U = UI.Uses[OtherKind];
10421 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10422 return;
10423
10424 Expr *Mod = U.Use;
10425 Expr *ModOrUse = Ref;
10426 if (OtherKind == UK_Use)
10427 std::swap(Mod, ModOrUse);
10428
10429 SemaRef.Diag(Mod->getExprLoc(),
10430 IsModMod ? diag::warn_unsequenced_mod_mod
10431 : diag::warn_unsequenced_mod_use)
10432 << O << SourceRange(ModOrUse->getExprLoc());
10433 UI.Diagnosed = true;
10434 }
10435
10436 void notePreUse(Object O, Expr *Use) {
10437 UsageInfo &U = UsageMap[O];
10438 // Uses conflict with other modifications.
10439 checkUsage(O, U, Use, UK_ModAsValue, false);
10440 }
10441 void notePostUse(Object O, Expr *Use) {
10442 UsageInfo &U = UsageMap[O];
10443 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10444 addUsage(U, O, Use, UK_Use);
10445 }
10446
10447 void notePreMod(Object O, Expr *Mod) {
10448 UsageInfo &U = UsageMap[O];
10449 // Modifications conflict with other modifications and with uses.
10450 checkUsage(O, U, Mod, UK_ModAsValue, true);
10451 checkUsage(O, U, Mod, UK_Use, false);
10452 }
10453 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10454 UsageInfo &U = UsageMap[O];
10455 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10456 addUsage(U, O, Use, UK);
10457 }
10458
10459public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010460 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +000010461 : Base(S.Context), SemaRef(S), Region(Tree.root()),
10462 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010463 Visit(E);
10464 }
10465
10466 void VisitStmt(Stmt *S) {
10467 // Skip all statements which aren't expressions for now.
10468 }
10469
10470 void VisitExpr(Expr *E) {
10471 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010472 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010473 }
10474
10475 void VisitCastExpr(CastExpr *E) {
10476 Object O = Object();
10477 if (E->getCastKind() == CK_LValueToRValue)
10478 O = getObject(E->getSubExpr(), false);
10479
10480 if (O)
10481 notePreUse(O, E);
10482 VisitExpr(E);
10483 if (O)
10484 notePostUse(O, E);
10485 }
10486
10487 void VisitBinComma(BinaryOperator *BO) {
10488 // C++11 [expr.comma]p1:
10489 // Every value computation and side effect associated with the left
10490 // expression is sequenced before every value computation and side
10491 // effect associated with the right expression.
10492 SequenceTree::Seq LHS = Tree.allocate(Region);
10493 SequenceTree::Seq RHS = Tree.allocate(Region);
10494 SequenceTree::Seq OldRegion = Region;
10495
10496 {
10497 SequencedSubexpression SeqLHS(*this);
10498 Region = LHS;
10499 Visit(BO->getLHS());
10500 }
10501
10502 Region = RHS;
10503 Visit(BO->getRHS());
10504
10505 Region = OldRegion;
10506
10507 // Forget that LHS and RHS are sequenced. They are both unsequenced
10508 // with respect to other stuff.
10509 Tree.merge(LHS);
10510 Tree.merge(RHS);
10511 }
10512
10513 void VisitBinAssign(BinaryOperator *BO) {
10514 // The modification is sequenced after the value computation of the LHS
10515 // and RHS, so check it before inspecting the operands and update the
10516 // map afterwards.
10517 Object O = getObject(BO->getLHS(), true);
10518 if (!O)
10519 return VisitExpr(BO);
10520
10521 notePreMod(O, BO);
10522
10523 // C++11 [expr.ass]p7:
10524 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10525 // only once.
10526 //
10527 // Therefore, for a compound assignment operator, O is considered used
10528 // everywhere except within the evaluation of E1 itself.
10529 if (isa<CompoundAssignOperator>(BO))
10530 notePreUse(O, BO);
10531
10532 Visit(BO->getLHS());
10533
10534 if (isa<CompoundAssignOperator>(BO))
10535 notePostUse(O, BO);
10536
10537 Visit(BO->getRHS());
10538
Richard Smith83e37bee2013-06-26 23:16:51 +000010539 // C++11 [expr.ass]p1:
10540 // the assignment is sequenced [...] before the value computation of the
10541 // assignment expression.
10542 // C11 6.5.16/3 has no such rule.
10543 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10544 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010545 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010546
Richard Smithc406cb72013-01-17 01:17:56 +000010547 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10548 VisitBinAssign(CAO);
10549 }
10550
10551 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10552 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10553 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10554 Object O = getObject(UO->getSubExpr(), true);
10555 if (!O)
10556 return VisitExpr(UO);
10557
10558 notePreMod(O, UO);
10559 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010560 // C++11 [expr.pre.incr]p1:
10561 // the expression ++x is equivalent to x+=1
10562 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10563 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010564 }
10565
10566 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10567 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10568 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10569 Object O = getObject(UO->getSubExpr(), true);
10570 if (!O)
10571 return VisitExpr(UO);
10572
10573 notePreMod(O, UO);
10574 Visit(UO->getSubExpr());
10575 notePostMod(O, UO, UK_ModAsSideEffect);
10576 }
10577
10578 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10579 void VisitBinLOr(BinaryOperator *BO) {
10580 // The side-effects of the LHS of an '&&' are sequenced before the
10581 // value computation of the RHS, and hence before the value computation
10582 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10583 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010584 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010585 {
10586 SequencedSubexpression Sequenced(*this);
10587 Visit(BO->getLHS());
10588 }
10589
10590 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010591 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010592 if (!Result)
10593 Visit(BO->getRHS());
10594 } else {
10595 // Check for unsequenced operations in the RHS, treating it as an
10596 // entirely separate evaluation.
10597 //
10598 // FIXME: If there are operations in the RHS which are unsequenced
10599 // with respect to operations outside the RHS, and those operations
10600 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010601 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010602 }
Richard Smithc406cb72013-01-17 01:17:56 +000010603 }
10604 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010605 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010606 {
10607 SequencedSubexpression Sequenced(*this);
10608 Visit(BO->getLHS());
10609 }
10610
10611 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010612 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010613 if (Result)
10614 Visit(BO->getRHS());
10615 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010616 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010617 }
Richard Smithc406cb72013-01-17 01:17:56 +000010618 }
10619
10620 // Only visit the condition, unless we can be sure which subexpression will
10621 // be chosen.
10622 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010623 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010624 {
10625 SequencedSubexpression Sequenced(*this);
10626 Visit(CO->getCond());
10627 }
Richard Smithc406cb72013-01-17 01:17:56 +000010628
10629 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010630 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010631 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010632 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010633 WorkList.push_back(CO->getTrueExpr());
10634 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010635 }
Richard Smithc406cb72013-01-17 01:17:56 +000010636 }
10637
Richard Smithe3dbfe02013-06-30 10:40:20 +000010638 void VisitCallExpr(CallExpr *CE) {
10639 // C++11 [intro.execution]p15:
10640 // When calling a function [...], every value computation and side effect
10641 // associated with any argument expression, or with the postfix expression
10642 // designating the called function, is sequenced before execution of every
10643 // expression or statement in the body of the function [and thus before
10644 // the value computation of its result].
10645 SequencedSubexpression Sequenced(*this);
10646 Base::VisitCallExpr(CE);
10647
10648 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10649 }
10650
Richard Smithc406cb72013-01-17 01:17:56 +000010651 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010652 // This is a call, so all subexpressions are sequenced before the result.
10653 SequencedSubexpression Sequenced(*this);
10654
Richard Smithc406cb72013-01-17 01:17:56 +000010655 if (!CCE->isListInitialization())
10656 return VisitExpr(CCE);
10657
10658 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010659 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010660 SequenceTree::Seq Parent = Region;
10661 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10662 E = CCE->arg_end();
10663 I != E; ++I) {
10664 Region = Tree.allocate(Parent);
10665 Elts.push_back(Region);
10666 Visit(*I);
10667 }
10668
10669 // Forget that the initializers are sequenced.
10670 Region = Parent;
10671 for (unsigned I = 0; I < Elts.size(); ++I)
10672 Tree.merge(Elts[I]);
10673 }
10674
10675 void VisitInitListExpr(InitListExpr *ILE) {
10676 if (!SemaRef.getLangOpts().CPlusPlus11)
10677 return VisitExpr(ILE);
10678
10679 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010680 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010681 SequenceTree::Seq Parent = Region;
10682 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10683 Expr *E = ILE->getInit(I);
10684 if (!E) continue;
10685 Region = Tree.allocate(Parent);
10686 Elts.push_back(Region);
10687 Visit(E);
10688 }
10689
10690 // Forget that the initializers are sequenced.
10691 Region = Parent;
10692 for (unsigned I = 0; I < Elts.size(); ++I)
10693 Tree.merge(Elts[I]);
10694 }
10695};
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010696} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010697
10698void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010699 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010700 WorkList.push_back(E);
10701 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010702 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010703 SequenceChecker(*this, Item, WorkList);
10704 }
Richard Smithc406cb72013-01-17 01:17:56 +000010705}
10706
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010707void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10708 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010709 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010710 if (!E->isInstantiationDependent())
10711 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010712 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010713 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010714 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010715}
10716
John McCall1f425642010-11-11 03:21:53 +000010717void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10718 FieldDecl *BitField,
10719 Expr *Init) {
10720 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10721}
10722
David Majnemer61a5bbf2015-04-07 22:08:51 +000010723static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10724 SourceLocation Loc) {
10725 if (!PType->isVariablyModifiedType())
10726 return;
10727 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10728 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10729 return;
10730 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010731 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10732 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10733 return;
10734 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010735 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10736 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10737 return;
10738 }
10739
10740 const ArrayType *AT = S.Context.getAsArrayType(PType);
10741 if (!AT)
10742 return;
10743
10744 if (AT->getSizeModifier() != ArrayType::Star) {
10745 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10746 return;
10747 }
10748
10749 S.Diag(Loc, diag::err_array_star_in_function_definition);
10750}
10751
Mike Stump0c2ec772010-01-21 03:59:47 +000010752/// CheckParmsForFunctionDef - Check that the parameters of the given
10753/// function are appropriate for the definition of a function. This
10754/// takes care of any checks that cannot be performed on the
10755/// declaration itself, e.g., that the types of each of the function
10756/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010757bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010758 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010759 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010760 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010761 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10762 // function declarator that is part of a function definition of
10763 // that function shall not have incomplete type.
10764 //
10765 // This is also C++ [dcl.fct]p6.
10766 if (!Param->isInvalidDecl() &&
10767 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010768 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010769 Param->setInvalidDecl();
10770 HasInvalidParm = true;
10771 }
10772
10773 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10774 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010775 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010776 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010777 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010778 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010779 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010780
10781 // C99 6.7.5.3p12:
10782 // If the function declarator is not part of a definition of that
10783 // function, parameters may have incomplete type and may use the [*]
10784 // notation in their sequences of declarator specifiers to specify
10785 // variable length array types.
10786 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010787 // FIXME: This diagnostic should point the '[*]' if source-location
10788 // information is added for it.
10789 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010790
10791 // MSVC destroys objects passed by value in the callee. Therefore a
10792 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010793 // object's destructor. However, we don't perform any direct access check
10794 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010795 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10796 .getCXXABI()
10797 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010798 if (!Param->isInvalidDecl()) {
10799 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10800 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10801 if (!ClassDecl->isInvalidDecl() &&
10802 !ClassDecl->hasIrrelevantDestructor() &&
10803 !ClassDecl->isDependentContext()) {
10804 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10805 MarkFunctionReferenced(Param->getLocation(), Destructor);
10806 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10807 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010808 }
10809 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010810 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010811
10812 // Parameters with the pass_object_size attribute only need to be marked
10813 // constant at function definitions. Because we lack information about
10814 // whether we're on a declaration or definition when we're instantiating the
10815 // attribute, we need to check for constness here.
10816 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10817 if (!Param->getType().isConstQualified())
10818 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10819 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010820 }
10821
10822 return HasInvalidParm;
10823}
John McCall2b5c1b22010-08-12 21:44:57 +000010824
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010825/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10826/// or MemberExpr.
10827static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10828 ASTContext &Context) {
10829 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10830 return Context.getDeclAlign(DRE->getDecl());
10831
10832 if (const auto *ME = dyn_cast<MemberExpr>(E))
10833 return Context.getDeclAlign(ME->getMemberDecl());
10834
10835 return TypeAlign;
10836}
10837
John McCall2b5c1b22010-08-12 21:44:57 +000010838/// CheckCastAlign - Implements -Wcast-align, which warns when a
10839/// pointer cast increases the alignment requirements.
10840void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10841 // This is actually a lot of work to potentially be doing on every
10842 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010843 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010844 return;
10845
10846 // Ignore dependent types.
10847 if (T->isDependentType() || Op->getType()->isDependentType())
10848 return;
10849
10850 // Require that the destination be a pointer type.
10851 const PointerType *DestPtr = T->getAs<PointerType>();
10852 if (!DestPtr) return;
10853
10854 // If the destination has alignment 1, we're done.
10855 QualType DestPointee = DestPtr->getPointeeType();
10856 if (DestPointee->isIncompleteType()) return;
10857 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10858 if (DestAlign.isOne()) return;
10859
10860 // Require that the source be a pointer type.
10861 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10862 if (!SrcPtr) return;
10863 QualType SrcPointee = SrcPtr->getPointeeType();
10864
10865 // Whitelist casts from cv void*. We already implicitly
10866 // whitelisted casts to cv void*, since they have alignment 1.
10867 // Also whitelist casts involving incomplete types, which implicitly
10868 // includes 'void'.
10869 if (SrcPointee->isIncompleteType()) return;
10870
10871 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010872
10873 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10874 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10875 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10876 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10877 if (UO->getOpcode() == UO_AddrOf)
10878 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10879 }
10880
John McCall2b5c1b22010-08-12 21:44:57 +000010881 if (SrcAlign >= DestAlign) return;
10882
10883 Diag(TRange.getBegin(), diag::warn_cast_align)
10884 << Op->getType() << T
10885 << static_cast<unsigned>(SrcAlign.getQuantity())
10886 << static_cast<unsigned>(DestAlign.getQuantity())
10887 << TRange << Op->getSourceRange();
10888}
10889
Chandler Carruth28389f02011-08-05 09:10:50 +000010890/// \brief Check whether this array fits the idiom of a size-one tail padded
10891/// array member of a struct.
10892///
10893/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10894/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010895static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010896 const NamedDecl *ND) {
10897 if (Size != 1 || !ND) return false;
10898
10899 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10900 if (!FD) return false;
10901
10902 // Don't consider sizes resulting from macro expansions or template argument
10903 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010904
10905 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010906 while (TInfo) {
10907 TypeLoc TL = TInfo->getTypeLoc();
10908 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010909 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10910 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010911 TInfo = TDL->getTypeSourceInfo();
10912 continue;
10913 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010914 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10915 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010916 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10917 return false;
10918 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010919 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010920 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010921
10922 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010923 if (!RD) return false;
10924 if (RD->isUnion()) return false;
10925 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10926 if (!CRD->isStandardLayout()) return false;
10927 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010928
Benjamin Kramer8c543672011-08-06 03:04:42 +000010929 // See if this is the last field decl in the record.
10930 const Decl *D = FD;
10931 while ((D = D->getNextDeclInContext()))
10932 if (isa<FieldDecl>(D))
10933 return false;
10934 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010935}
10936
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010937void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010938 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010939 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010940 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010941 if (IndexExpr->isValueDependent())
10942 return;
10943
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010944 const Type *EffectiveType =
10945 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010946 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010947 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010948 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010949 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010950 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010951
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010952 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010953 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010954 return;
Richard Smith13f67182011-12-16 19:31:14 +000010955 if (IndexNegated)
10956 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010957
Craig Topperc3ec1492014-05-26 06:22:03 +000010958 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010959 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10960 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010961 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010962 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010963
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010964 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010965 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010966 if (!size.isStrictlyPositive())
10967 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010968
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010969 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000010970 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010971 // Make sure we're comparing apples to apples when comparing index to size
10972 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10973 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000010974 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000010975 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010976 if (ptrarith_typesize != array_typesize) {
10977 // There's a cast to a different size type involved
10978 uint64_t ratio = array_typesize / ptrarith_typesize;
10979 // TODO: Be smarter about handling cases where array_typesize is not a
10980 // multiple of ptrarith_typesize
10981 if (ptrarith_typesize * ratio == array_typesize)
10982 size *= llvm::APInt(size.getBitWidth(), ratio);
10983 }
10984 }
10985
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010986 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010987 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010988 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010989 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010990
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010991 // For array subscripting the index must be less than size, but for pointer
10992 // arithmetic also allow the index (offset) to be equal to size since
10993 // computing the next address after the end of the array is legal and
10994 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010995 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000010996 return;
10997
10998 // Also don't warn for arrays of size 1 which are members of some
10999 // structure. These are often used to approximate flexible arrays in C89
11000 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011001 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011002 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011003
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011004 // Suppress the warning if the subscript expression (as identified by the
11005 // ']' location) and the index expression are both from macro expansions
11006 // within a system header.
11007 if (ASE) {
11008 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11009 ASE->getRBracketLoc());
11010 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11011 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11012 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011013 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011014 return;
11015 }
11016 }
11017
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011018 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011019 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011020 DiagID = diag::warn_array_index_exceeds_bounds;
11021
11022 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11023 PDiag(DiagID) << index.toString(10, true)
11024 << size.toString(10, true)
11025 << (unsigned)size.getLimitedValue(~0U)
11026 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011027 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011028 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011029 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011030 DiagID = diag::warn_ptr_arith_precedes_bounds;
11031 if (index.isNegative()) index = -index;
11032 }
11033
11034 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11035 PDiag(DiagID) << index.toString(10, true)
11036 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011037 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011038
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011039 if (!ND) {
11040 // Try harder to find a NamedDecl to point at in the note.
11041 while (const ArraySubscriptExpr *ASE =
11042 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11043 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11044 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11045 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11046 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11047 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11048 }
11049
Chandler Carruth1af88f12011-02-17 21:10:52 +000011050 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011051 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11052 PDiag(diag::note_array_index_out_of_bounds)
11053 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011054}
11055
Ted Kremenekdf26df72011-03-01 18:41:00 +000011056void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011057 int AllowOnePastEnd = 0;
11058 while (expr) {
11059 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011060 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011061 case Stmt::ArraySubscriptExprClass: {
11062 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011063 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011064 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011065 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011066 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011067 case Stmt::OMPArraySectionExprClass: {
11068 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11069 if (ASE->getLowerBound())
11070 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11071 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11072 return;
11073 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011074 case Stmt::UnaryOperatorClass: {
11075 // Only unwrap the * and & unary operators
11076 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11077 expr = UO->getSubExpr();
11078 switch (UO->getOpcode()) {
11079 case UO_AddrOf:
11080 AllowOnePastEnd++;
11081 break;
11082 case UO_Deref:
11083 AllowOnePastEnd--;
11084 break;
11085 default:
11086 return;
11087 }
11088 break;
11089 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011090 case Stmt::ConditionalOperatorClass: {
11091 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11092 if (const Expr *lhs = cond->getLHS())
11093 CheckArrayAccess(lhs);
11094 if (const Expr *rhs = cond->getRHS())
11095 CheckArrayAccess(rhs);
11096 return;
11097 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011098 case Stmt::CXXOperatorCallExprClass: {
11099 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11100 for (const auto *Arg : OCE->arguments())
11101 CheckArrayAccess(Arg);
11102 return;
11103 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011104 default:
11105 return;
11106 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011107 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011108}
John McCall31168b02011-06-15 23:02:42 +000011109
11110//===--- CHECK: Objective-C retain cycles ----------------------------------//
11111
11112namespace {
11113 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +000011114 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +000011115 VarDecl *Variable;
11116 SourceRange Range;
11117 SourceLocation Loc;
11118 bool Indirect;
11119
11120 void setLocsFrom(Expr *e) {
11121 Loc = e->getExprLoc();
11122 Range = e->getSourceRange();
11123 }
11124 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011125} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011126
11127/// Consider whether capturing the given variable can possibly lead to
11128/// a retain cycle.
11129static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011130 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011131 // lifetime. In MRR, it's captured strongly if the variable is
11132 // __block and has an appropriate type.
11133 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11134 return false;
11135
11136 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011137 if (ref)
11138 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011139 return true;
11140}
11141
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011142static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011143 while (true) {
11144 e = e->IgnoreParens();
11145 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11146 switch (cast->getCastKind()) {
11147 case CK_BitCast:
11148 case CK_LValueBitCast:
11149 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011150 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011151 e = cast->getSubExpr();
11152 continue;
11153
John McCall31168b02011-06-15 23:02:42 +000011154 default:
11155 return false;
11156 }
11157 }
11158
11159 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11160 ObjCIvarDecl *ivar = ref->getDecl();
11161 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11162 return false;
11163
11164 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011165 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011166 return false;
11167
11168 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11169 owner.Indirect = true;
11170 return true;
11171 }
11172
11173 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11174 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11175 if (!var) return false;
11176 return considerVariable(var, ref, owner);
11177 }
11178
John McCall31168b02011-06-15 23:02:42 +000011179 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11180 if (member->isArrow()) return false;
11181
11182 // Don't count this as an indirect ownership.
11183 e = member->getBase();
11184 continue;
11185 }
11186
John McCallfe96e0b2011-11-06 09:01:30 +000011187 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11188 // Only pay attention to pseudo-objects on property references.
11189 ObjCPropertyRefExpr *pre
11190 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11191 ->IgnoreParens());
11192 if (!pre) return false;
11193 if (pre->isImplicitProperty()) return false;
11194 ObjCPropertyDecl *property = pre->getExplicitProperty();
11195 if (!property->isRetaining() &&
11196 !(property->getPropertyIvarDecl() &&
11197 property->getPropertyIvarDecl()->getType()
11198 .getObjCLifetime() == Qualifiers::OCL_Strong))
11199 return false;
11200
11201 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011202 if (pre->isSuperReceiver()) {
11203 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11204 if (!owner.Variable)
11205 return false;
11206 owner.Loc = pre->getLocation();
11207 owner.Range = pre->getSourceRange();
11208 return true;
11209 }
John McCallfe96e0b2011-11-06 09:01:30 +000011210 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11211 ->getSourceExpr());
11212 continue;
11213 }
11214
John McCall31168b02011-06-15 23:02:42 +000011215 // Array ivars?
11216
11217 return false;
11218 }
11219}
11220
11221namespace {
11222 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11223 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11224 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011225 Context(Context), Variable(variable), Capturer(nullptr),
11226 VarWillBeReased(false) {}
11227 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011228 VarDecl *Variable;
11229 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011230 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +000011231
11232 void VisitDeclRefExpr(DeclRefExpr *ref) {
11233 if (ref->getDecl() == Variable && !Capturer)
11234 Capturer = ref;
11235 }
11236
John McCall31168b02011-06-15 23:02:42 +000011237 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11238 if (Capturer) return;
11239 Visit(ref->getBase());
11240 if (Capturer && ref->isFreeIvar())
11241 Capturer = ref;
11242 }
11243
11244 void VisitBlockExpr(BlockExpr *block) {
11245 // Look inside nested blocks
11246 if (block->getBlockDecl()->capturesVariable(Variable))
11247 Visit(block->getBlockDecl()->getBody());
11248 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011249
11250 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11251 if (Capturer) return;
11252 if (OVE->getSourceExpr())
11253 Visit(OVE->getSourceExpr());
11254 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011255 void VisitBinaryOperator(BinaryOperator *BinOp) {
11256 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11257 return;
11258 Expr *LHS = BinOp->getLHS();
11259 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11260 if (DRE->getDecl() != Variable)
11261 return;
11262 if (Expr *RHS = BinOp->getRHS()) {
11263 RHS = RHS->IgnoreParenCasts();
11264 llvm::APSInt Value;
11265 VarWillBeReased =
11266 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11267 }
11268 }
11269 }
John McCall31168b02011-06-15 23:02:42 +000011270 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011271} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +000011272
11273/// Check whether the given argument is a block which captures a
11274/// variable.
11275static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11276 assert(owner.Variable && owner.Loc.isValid());
11277
11278 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011279
11280 // Look through [^{...} copy] and Block_copy(^{...}).
11281 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11282 Selector Cmd = ME->getSelector();
11283 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11284 e = ME->getInstanceReceiver();
11285 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011286 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011287 e = e->IgnoreParenCasts();
11288 }
11289 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11290 if (CE->getNumArgs() == 1) {
11291 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011292 if (Fn) {
11293 const IdentifierInfo *FnI = Fn->getIdentifier();
11294 if (FnI && FnI->isStr("_Block_copy")) {
11295 e = CE->getArg(0)->IgnoreParenCasts();
11296 }
11297 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011298 }
11299 }
11300
John McCall31168b02011-06-15 23:02:42 +000011301 BlockExpr *block = dyn_cast<BlockExpr>(e);
11302 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011303 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011304
11305 FindCaptureVisitor visitor(S.Context, owner.Variable);
11306 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011307 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011308}
11309
11310static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11311 RetainCycleOwner &owner) {
11312 assert(capturer);
11313 assert(owner.Variable && owner.Loc.isValid());
11314
11315 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11316 << owner.Variable << capturer->getSourceRange();
11317 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11318 << owner.Indirect << owner.Range;
11319}
11320
11321/// Check for a keyword selector that starts with the word 'add' or
11322/// 'set'.
11323static bool isSetterLikeSelector(Selector sel) {
11324 if (sel.isUnarySelector()) return false;
11325
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011326 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011327 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011328 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011329 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011330 else if (str.startswith("add")) {
11331 // Specially whitelist 'addOperationWithBlock:'.
11332 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11333 return false;
11334 str = str.substr(3);
11335 }
John McCall31168b02011-06-15 23:02:42 +000011336 else
11337 return false;
11338
11339 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011340 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011341}
11342
Benjamin Kramer3a743452015-03-09 15:03:32 +000011343static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11344 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011345 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11346 Message->getReceiverInterface(),
11347 NSAPI::ClassId_NSMutableArray);
11348 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011349 return None;
11350 }
11351
11352 Selector Sel = Message->getSelector();
11353
11354 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11355 S.NSAPIObj->getNSArrayMethodKind(Sel);
11356 if (!MKOpt) {
11357 return None;
11358 }
11359
11360 NSAPI::NSArrayMethodKind MK = *MKOpt;
11361
11362 switch (MK) {
11363 case NSAPI::NSMutableArr_addObject:
11364 case NSAPI::NSMutableArr_insertObjectAtIndex:
11365 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11366 return 0;
11367 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11368 return 1;
11369
11370 default:
11371 return None;
11372 }
11373
11374 return None;
11375}
11376
11377static
11378Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11379 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011380 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11381 Message->getReceiverInterface(),
11382 NSAPI::ClassId_NSMutableDictionary);
11383 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011384 return None;
11385 }
11386
11387 Selector Sel = Message->getSelector();
11388
11389 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11390 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11391 if (!MKOpt) {
11392 return None;
11393 }
11394
11395 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11396
11397 switch (MK) {
11398 case NSAPI::NSMutableDict_setObjectForKey:
11399 case NSAPI::NSMutableDict_setValueForKey:
11400 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11401 return 0;
11402
11403 default:
11404 return None;
11405 }
11406
11407 return None;
11408}
11409
11410static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011411 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11412 Message->getReceiverInterface(),
11413 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011414
Alex Denisov5dfac812015-08-06 04:51:14 +000011415 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11416 Message->getReceiverInterface(),
11417 NSAPI::ClassId_NSMutableOrderedSet);
11418 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011419 return None;
11420 }
11421
11422 Selector Sel = Message->getSelector();
11423
11424 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11425 if (!MKOpt) {
11426 return None;
11427 }
11428
11429 NSAPI::NSSetMethodKind MK = *MKOpt;
11430
11431 switch (MK) {
11432 case NSAPI::NSMutableSet_addObject:
11433 case NSAPI::NSOrderedSet_setObjectAtIndex:
11434 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11435 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11436 return 0;
11437 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11438 return 1;
11439 }
11440
11441 return None;
11442}
11443
11444void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11445 if (!Message->isInstanceMessage()) {
11446 return;
11447 }
11448
11449 Optional<int> ArgOpt;
11450
11451 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11452 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11453 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11454 return;
11455 }
11456
11457 int ArgIndex = *ArgOpt;
11458
Alex Denisove1d882c2015-03-04 17:55:52 +000011459 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11460 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11461 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11462 }
11463
Alex Denisov5dfac812015-08-06 04:51:14 +000011464 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011465 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011466 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011467 Diag(Message->getSourceRange().getBegin(),
11468 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011469 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011470 }
11471 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011472 } else {
11473 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11474
11475 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11476 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11477 }
11478
11479 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11480 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11481 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11482 ValueDecl *Decl = ReceiverRE->getDecl();
11483 Diag(Message->getSourceRange().getBegin(),
11484 diag::warn_objc_circular_container)
11485 << Decl->getName() << Decl->getName();
11486 if (!ArgRE->isObjCSelfExpr()) {
11487 Diag(Decl->getLocation(),
11488 diag::note_objc_circular_container_declared_here)
11489 << Decl->getName();
11490 }
11491 }
11492 }
11493 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11494 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11495 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11496 ObjCIvarDecl *Decl = IvarRE->getDecl();
11497 Diag(Message->getSourceRange().getBegin(),
11498 diag::warn_objc_circular_container)
11499 << Decl->getName() << Decl->getName();
11500 Diag(Decl->getLocation(),
11501 diag::note_objc_circular_container_declared_here)
11502 << Decl->getName();
11503 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011504 }
11505 }
11506 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011507}
11508
John McCall31168b02011-06-15 23:02:42 +000011509/// Check a message send to see if it's likely to cause a retain cycle.
11510void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11511 // Only check instance methods whose selector looks like a setter.
11512 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11513 return;
11514
11515 // Try to find a variable that the receiver is strongly owned by.
11516 RetainCycleOwner owner;
11517 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011518 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011519 return;
11520 } else {
11521 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11522 owner.Variable = getCurMethodDecl()->getSelfDecl();
11523 owner.Loc = msg->getSuperLoc();
11524 owner.Range = msg->getSuperLoc();
11525 }
11526
11527 // Check whether the receiver is captured by any of the arguments.
11528 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11529 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11530 return diagnoseRetainCycle(*this, capturer, owner);
11531}
11532
11533/// Check a property assign to see if it's likely to cause a retain cycle.
11534void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11535 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011536 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011537 return;
11538
11539 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11540 diagnoseRetainCycle(*this, capturer, owner);
11541}
11542
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011543void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11544 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011545 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011546 return;
11547
11548 // Because we don't have an expression for the variable, we have to set the
11549 // location explicitly here.
11550 Owner.Loc = Var->getLocation();
11551 Owner.Range = Var->getSourceRange();
11552
11553 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11554 diagnoseRetainCycle(*this, Capturer, Owner);
11555}
11556
Ted Kremenek9304da92012-12-21 08:04:28 +000011557static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11558 Expr *RHS, bool isProperty) {
11559 // Check if RHS is an Objective-C object literal, which also can get
11560 // immediately zapped in a weak reference. Note that we explicitly
11561 // allow ObjCStringLiterals, since those are designed to never really die.
11562 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011563
Ted Kremenek64873352012-12-21 22:46:35 +000011564 // This enum needs to match with the 'select' in
11565 // warn_objc_arc_literal_assign (off-by-1).
11566 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11567 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11568 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011569
11570 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011571 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011572 << (isProperty ? 0 : 1)
11573 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011574
11575 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011576}
11577
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011578static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11579 Qualifiers::ObjCLifetime LT,
11580 Expr *RHS, bool isProperty) {
11581 // Strip off any implicit cast added to get to the one ARC-specific.
11582 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11583 if (cast->getCastKind() == CK_ARCConsumeObject) {
11584 S.Diag(Loc, diag::warn_arc_retained_assign)
11585 << (LT == Qualifiers::OCL_ExplicitNone)
11586 << (isProperty ? 0 : 1)
11587 << RHS->getSourceRange();
11588 return true;
11589 }
11590 RHS = cast->getSubExpr();
11591 }
11592
11593 if (LT == Qualifiers::OCL_Weak &&
11594 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11595 return true;
11596
11597 return false;
11598}
11599
Ted Kremenekb36234d2012-12-21 08:04:20 +000011600bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11601 QualType LHS, Expr *RHS) {
11602 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11603
11604 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11605 return false;
11606
11607 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11608 return true;
11609
11610 return false;
11611}
11612
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011613void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11614 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011615 QualType LHSType;
11616 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011617 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011618 ObjCPropertyRefExpr *PRE
11619 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11620 if (PRE && !PRE->isImplicitProperty()) {
11621 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11622 if (PD)
11623 LHSType = PD->getType();
11624 }
11625
11626 if (LHSType.isNull())
11627 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011628
11629 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11630
11631 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011632 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011633 getCurFunction()->markSafeWeakUse(LHS);
11634 }
11635
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011636 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11637 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011638
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011639 // FIXME. Check for other life times.
11640 if (LT != Qualifiers::OCL_None)
11641 return;
11642
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011643 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011644 if (PRE->isImplicitProperty())
11645 return;
11646 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11647 if (!PD)
11648 return;
11649
Bill Wendling44426052012-12-20 19:22:21 +000011650 unsigned Attributes = PD->getPropertyAttributes();
11651 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011652 // when 'assign' attribute was not explicitly specified
11653 // by user, ignore it and rely on property type itself
11654 // for lifetime info.
11655 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11656 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11657 LHSType->isObjCRetainableType())
11658 return;
11659
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011660 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011661 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011662 Diag(Loc, diag::warn_arc_retained_property_assign)
11663 << RHS->getSourceRange();
11664 return;
11665 }
11666 RHS = cast->getSubExpr();
11667 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011668 }
Bill Wendling44426052012-12-20 19:22:21 +000011669 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011670 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11671 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011672 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011673 }
11674}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011675
11676//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11677
11678namespace {
11679bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11680 SourceLocation StmtLoc,
11681 const NullStmt *Body) {
11682 // Do not warn if the body is a macro that expands to nothing, e.g:
11683 //
11684 // #define CALL(x)
11685 // if (condition)
11686 // CALL(0);
11687 //
11688 if (Body->hasLeadingEmptyMacro())
11689 return false;
11690
11691 // Get line numbers of statement and body.
11692 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +000011693 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011694 &StmtLineInvalid);
11695 if (StmtLineInvalid)
11696 return false;
11697
11698 bool BodyLineInvalid;
11699 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11700 &BodyLineInvalid);
11701 if (BodyLineInvalid)
11702 return false;
11703
11704 // Warn if null statement and body are on the same line.
11705 if (StmtLine != BodyLine)
11706 return false;
11707
11708 return true;
11709}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011710} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011711
11712void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11713 const Stmt *Body,
11714 unsigned DiagID) {
11715 // Since this is a syntactic check, don't emit diagnostic for template
11716 // instantiations, this just adds noise.
11717 if (CurrentInstantiationScope)
11718 return;
11719
11720 // The body should be a null statement.
11721 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11722 if (!NBody)
11723 return;
11724
11725 // Do the usual checks.
11726 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11727 return;
11728
11729 Diag(NBody->getSemiLoc(), DiagID);
11730 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11731}
11732
11733void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11734 const Stmt *PossibleBody) {
11735 assert(!CurrentInstantiationScope); // Ensured by caller
11736
11737 SourceLocation StmtLoc;
11738 const Stmt *Body;
11739 unsigned DiagID;
11740 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11741 StmtLoc = FS->getRParenLoc();
11742 Body = FS->getBody();
11743 DiagID = diag::warn_empty_for_body;
11744 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11745 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11746 Body = WS->getBody();
11747 DiagID = diag::warn_empty_while_body;
11748 } else
11749 return; // Neither `for' nor `while'.
11750
11751 // The body should be a null statement.
11752 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11753 if (!NBody)
11754 return;
11755
11756 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011757 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011758 return;
11759
11760 // Do the usual checks.
11761 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11762 return;
11763
11764 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11765 // noise level low, emit diagnostics only if for/while is followed by a
11766 // CompoundStmt, e.g.:
11767 // for (int i = 0; i < n; i++);
11768 // {
11769 // a(i);
11770 // }
11771 // or if for/while is followed by a statement with more indentation
11772 // than for/while itself:
11773 // for (int i = 0; i < n; i++);
11774 // a(i);
11775 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11776 if (!ProbableTypo) {
11777 bool BodyColInvalid;
11778 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11779 PossibleBody->getLocStart(),
11780 &BodyColInvalid);
11781 if (BodyColInvalid)
11782 return;
11783
11784 bool StmtColInvalid;
11785 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11786 S->getLocStart(),
11787 &StmtColInvalid);
11788 if (StmtColInvalid)
11789 return;
11790
11791 if (BodyCol > StmtCol)
11792 ProbableTypo = true;
11793 }
11794
11795 if (ProbableTypo) {
11796 Diag(NBody->getSemiLoc(), DiagID);
11797 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11798 }
11799}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011800
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011801//===--- CHECK: Warn on self move with std::move. -------------------------===//
11802
11803/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11804void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11805 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011806 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11807 return;
11808
Richard Smith51ec0cf2017-02-21 01:17:38 +000011809 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011810 return;
11811
11812 // Strip parens and casts away.
11813 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11814 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11815
11816 // Check for a call expression
11817 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11818 if (!CE || CE->getNumArgs() != 1)
11819 return;
11820
11821 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011822 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011823 return;
11824
11825 // Get argument from std::move
11826 RHSExpr = CE->getArg(0);
11827
11828 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11829 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11830
11831 // Two DeclRefExpr's, check that the decls are the same.
11832 if (LHSDeclRef && RHSDeclRef) {
11833 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11834 return;
11835 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11836 RHSDeclRef->getDecl()->getCanonicalDecl())
11837 return;
11838
11839 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11840 << LHSExpr->getSourceRange()
11841 << RHSExpr->getSourceRange();
11842 return;
11843 }
11844
11845 // Member variables require a different approach to check for self moves.
11846 // MemberExpr's are the same if every nested MemberExpr refers to the same
11847 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11848 // the base Expr's are CXXThisExpr's.
11849 const Expr *LHSBase = LHSExpr;
11850 const Expr *RHSBase = RHSExpr;
11851 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11852 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11853 if (!LHSME || !RHSME)
11854 return;
11855
11856 while (LHSME && RHSME) {
11857 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11858 RHSME->getMemberDecl()->getCanonicalDecl())
11859 return;
11860
11861 LHSBase = LHSME->getBase();
11862 RHSBase = RHSME->getBase();
11863 LHSME = dyn_cast<MemberExpr>(LHSBase);
11864 RHSME = dyn_cast<MemberExpr>(RHSBase);
11865 }
11866
11867 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11868 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11869 if (LHSDeclRef && RHSDeclRef) {
11870 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11871 return;
11872 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11873 RHSDeclRef->getDecl()->getCanonicalDecl())
11874 return;
11875
11876 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11877 << LHSExpr->getSourceRange()
11878 << RHSExpr->getSourceRange();
11879 return;
11880 }
11881
11882 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11883 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11884 << LHSExpr->getSourceRange()
11885 << RHSExpr->getSourceRange();
11886}
11887
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011888//===--- Layout compatibility ----------------------------------------------//
11889
11890namespace {
11891
11892bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11893
11894/// \brief Check if two enumeration types are layout-compatible.
11895bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11896 // C++11 [dcl.enum] p8:
11897 // Two enumeration types are layout-compatible if they have the same
11898 // underlying type.
11899 return ED1->isComplete() && ED2->isComplete() &&
11900 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11901}
11902
11903/// \brief Check if two fields are layout-compatible.
11904bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11905 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11906 return false;
11907
11908 if (Field1->isBitField() != Field2->isBitField())
11909 return false;
11910
11911 if (Field1->isBitField()) {
11912 // Make sure that the bit-fields are the same length.
11913 unsigned Bits1 = Field1->getBitWidthValue(C);
11914 unsigned Bits2 = Field2->getBitWidthValue(C);
11915
11916 if (Bits1 != Bits2)
11917 return false;
11918 }
11919
11920 return true;
11921}
11922
11923/// \brief Check if two standard-layout structs are layout-compatible.
11924/// (C++11 [class.mem] p17)
11925bool isLayoutCompatibleStruct(ASTContext &C,
11926 RecordDecl *RD1,
11927 RecordDecl *RD2) {
11928 // If both records are C++ classes, check that base classes match.
11929 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11930 // If one of records is a CXXRecordDecl we are in C++ mode,
11931 // thus the other one is a CXXRecordDecl, too.
11932 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11933 // Check number of base classes.
11934 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11935 return false;
11936
11937 // Check the base classes.
11938 for (CXXRecordDecl::base_class_const_iterator
11939 Base1 = D1CXX->bases_begin(),
11940 BaseEnd1 = D1CXX->bases_end(),
11941 Base2 = D2CXX->bases_begin();
11942 Base1 != BaseEnd1;
11943 ++Base1, ++Base2) {
11944 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11945 return false;
11946 }
11947 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11948 // If only RD2 is a C++ class, it should have zero base classes.
11949 if (D2CXX->getNumBases() > 0)
11950 return false;
11951 }
11952
11953 // Check the fields.
11954 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11955 Field2End = RD2->field_end(),
11956 Field1 = RD1->field_begin(),
11957 Field1End = RD1->field_end();
11958 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11959 if (!isLayoutCompatible(C, *Field1, *Field2))
11960 return false;
11961 }
11962 if (Field1 != Field1End || Field2 != Field2End)
11963 return false;
11964
11965 return true;
11966}
11967
11968/// \brief Check if two standard-layout unions are layout-compatible.
11969/// (C++11 [class.mem] p18)
11970bool isLayoutCompatibleUnion(ASTContext &C,
11971 RecordDecl *RD1,
11972 RecordDecl *RD2) {
11973 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011974 for (auto *Field2 : RD2->fields())
11975 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011976
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011977 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011978 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11979 I = UnmatchedFields.begin(),
11980 E = UnmatchedFields.end();
11981
11982 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000011983 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011984 bool Result = UnmatchedFields.erase(*I);
11985 (void) Result;
11986 assert(Result);
11987 break;
11988 }
11989 }
11990 if (I == E)
11991 return false;
11992 }
11993
11994 return UnmatchedFields.empty();
11995}
11996
11997bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11998 if (RD1->isUnion() != RD2->isUnion())
11999 return false;
12000
12001 if (RD1->isUnion())
12002 return isLayoutCompatibleUnion(C, RD1, RD2);
12003 else
12004 return isLayoutCompatibleStruct(C, RD1, RD2);
12005}
12006
12007/// \brief Check if two types are layout-compatible in C++11 sense.
12008bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12009 if (T1.isNull() || T2.isNull())
12010 return false;
12011
12012 // C++11 [basic.types] p11:
12013 // If two types T1 and T2 are the same type, then T1 and T2 are
12014 // layout-compatible types.
12015 if (C.hasSameType(T1, T2))
12016 return true;
12017
12018 T1 = T1.getCanonicalType().getUnqualifiedType();
12019 T2 = T2.getCanonicalType().getUnqualifiedType();
12020
12021 const Type::TypeClass TC1 = T1->getTypeClass();
12022 const Type::TypeClass TC2 = T2->getTypeClass();
12023
12024 if (TC1 != TC2)
12025 return false;
12026
12027 if (TC1 == Type::Enum) {
12028 return isLayoutCompatible(C,
12029 cast<EnumType>(T1)->getDecl(),
12030 cast<EnumType>(T2)->getDecl());
12031 } else if (TC1 == Type::Record) {
12032 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12033 return false;
12034
12035 return isLayoutCompatible(C,
12036 cast<RecordType>(T1)->getDecl(),
12037 cast<RecordType>(T2)->getDecl());
12038 }
12039
12040 return false;
12041}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012042} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012043
12044//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12045
12046namespace {
12047/// \brief Given a type tag expression find the type tag itself.
12048///
12049/// \param TypeExpr Type tag expression, as it appears in user's code.
12050///
12051/// \param VD Declaration of an identifier that appears in a type tag.
12052///
12053/// \param MagicValue Type tag magic value.
12054bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12055 const ValueDecl **VD, uint64_t *MagicValue) {
12056 while(true) {
12057 if (!TypeExpr)
12058 return false;
12059
12060 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12061
12062 switch (TypeExpr->getStmtClass()) {
12063 case Stmt::UnaryOperatorClass: {
12064 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12065 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12066 TypeExpr = UO->getSubExpr();
12067 continue;
12068 }
12069 return false;
12070 }
12071
12072 case Stmt::DeclRefExprClass: {
12073 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12074 *VD = DRE->getDecl();
12075 return true;
12076 }
12077
12078 case Stmt::IntegerLiteralClass: {
12079 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12080 llvm::APInt MagicValueAPInt = IL->getValue();
12081 if (MagicValueAPInt.getActiveBits() <= 64) {
12082 *MagicValue = MagicValueAPInt.getZExtValue();
12083 return true;
12084 } else
12085 return false;
12086 }
12087
12088 case Stmt::BinaryConditionalOperatorClass:
12089 case Stmt::ConditionalOperatorClass: {
12090 const AbstractConditionalOperator *ACO =
12091 cast<AbstractConditionalOperator>(TypeExpr);
12092 bool Result;
12093 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12094 if (Result)
12095 TypeExpr = ACO->getTrueExpr();
12096 else
12097 TypeExpr = ACO->getFalseExpr();
12098 continue;
12099 }
12100 return false;
12101 }
12102
12103 case Stmt::BinaryOperatorClass: {
12104 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12105 if (BO->getOpcode() == BO_Comma) {
12106 TypeExpr = BO->getRHS();
12107 continue;
12108 }
12109 return false;
12110 }
12111
12112 default:
12113 return false;
12114 }
12115 }
12116}
12117
12118/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12119///
12120/// \param TypeExpr Expression that specifies a type tag.
12121///
12122/// \param MagicValues Registered magic values.
12123///
12124/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12125/// kind.
12126///
12127/// \param TypeInfo Information about the corresponding C type.
12128///
12129/// \returns true if the corresponding C type was found.
12130bool GetMatchingCType(
12131 const IdentifierInfo *ArgumentKind,
12132 const Expr *TypeExpr, const ASTContext &Ctx,
12133 const llvm::DenseMap<Sema::TypeTagMagicValue,
12134 Sema::TypeTagData> *MagicValues,
12135 bool &FoundWrongKind,
12136 Sema::TypeTagData &TypeInfo) {
12137 FoundWrongKind = false;
12138
12139 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012140 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012141
12142 uint64_t MagicValue;
12143
12144 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12145 return false;
12146
12147 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012148 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012149 if (I->getArgumentKind() != ArgumentKind) {
12150 FoundWrongKind = true;
12151 return false;
12152 }
12153 TypeInfo.Type = I->getMatchingCType();
12154 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12155 TypeInfo.MustBeNull = I->getMustBeNull();
12156 return true;
12157 }
12158 return false;
12159 }
12160
12161 if (!MagicValues)
12162 return false;
12163
12164 llvm::DenseMap<Sema::TypeTagMagicValue,
12165 Sema::TypeTagData>::const_iterator I =
12166 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12167 if (I == MagicValues->end())
12168 return false;
12169
12170 TypeInfo = I->second;
12171 return true;
12172}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012173} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012174
12175void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12176 uint64_t MagicValue, QualType Type,
12177 bool LayoutCompatible,
12178 bool MustBeNull) {
12179 if (!TypeTagForDatatypeMagicValues)
12180 TypeTagForDatatypeMagicValues.reset(
12181 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12182
12183 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12184 (*TypeTagForDatatypeMagicValues)[Magic] =
12185 TypeTagData(Type, LayoutCompatible, MustBeNull);
12186}
12187
12188namespace {
12189bool IsSameCharType(QualType T1, QualType T2) {
12190 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12191 if (!BT1)
12192 return false;
12193
12194 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12195 if (!BT2)
12196 return false;
12197
12198 BuiltinType::Kind T1Kind = BT1->getKind();
12199 BuiltinType::Kind T2Kind = BT2->getKind();
12200
12201 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12202 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12203 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12204 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12205}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012206} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012207
12208void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12209 const Expr * const *ExprArgs) {
12210 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12211 bool IsPointerAttr = Attr->getIsPointer();
12212
12213 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12214 bool FoundWrongKind;
12215 TypeTagData TypeInfo;
12216 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12217 TypeTagForDatatypeMagicValues.get(),
12218 FoundWrongKind, TypeInfo)) {
12219 if (FoundWrongKind)
12220 Diag(TypeTagExpr->getExprLoc(),
12221 diag::warn_type_tag_for_datatype_wrong_kind)
12222 << TypeTagExpr->getSourceRange();
12223 return;
12224 }
12225
12226 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12227 if (IsPointerAttr) {
12228 // Skip implicit cast of pointer to `void *' (as a function argument).
12229 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012230 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012231 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012232 ArgumentExpr = ICE->getSubExpr();
12233 }
12234 QualType ArgumentType = ArgumentExpr->getType();
12235
12236 // Passing a `void*' pointer shouldn't trigger a warning.
12237 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12238 return;
12239
12240 if (TypeInfo.MustBeNull) {
12241 // Type tag with matching void type requires a null pointer.
12242 if (!ArgumentExpr->isNullPointerConstant(Context,
12243 Expr::NPC_ValueDependentIsNotNull)) {
12244 Diag(ArgumentExpr->getExprLoc(),
12245 diag::warn_type_safety_null_pointer_required)
12246 << ArgumentKind->getName()
12247 << ArgumentExpr->getSourceRange()
12248 << TypeTagExpr->getSourceRange();
12249 }
12250 return;
12251 }
12252
12253 QualType RequiredType = TypeInfo.Type;
12254 if (IsPointerAttr)
12255 RequiredType = Context.getPointerType(RequiredType);
12256
12257 bool mismatch = false;
12258 if (!TypeInfo.LayoutCompatible) {
12259 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12260
12261 // C++11 [basic.fundamental] p1:
12262 // Plain char, signed char, and unsigned char are three distinct types.
12263 //
12264 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12265 // char' depending on the current char signedness mode.
12266 if (mismatch)
12267 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12268 RequiredType->getPointeeType())) ||
12269 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12270 mismatch = false;
12271 } else
12272 if (IsPointerAttr)
12273 mismatch = !isLayoutCompatible(Context,
12274 ArgumentType->getPointeeType(),
12275 RequiredType->getPointeeType());
12276 else
12277 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12278
12279 if (mismatch)
12280 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012281 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012282 << TypeInfo.LayoutCompatible << RequiredType
12283 << ArgumentExpr->getSourceRange()
12284 << TypeTagExpr->getSourceRange();
12285}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012286
12287void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12288 CharUnits Alignment) {
12289 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12290}
12291
12292void Sema::DiagnoseMisalignedMembers() {
12293 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012294 const NamedDecl *ND = m.RD;
12295 if (ND->getName().empty()) {
12296 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12297 ND = TD;
12298 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012299 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012300 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012301 }
12302 MisalignedMembers.clear();
12303}
12304
12305void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012306 E = E->IgnoreParens();
12307 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012308 return;
12309 if (isa<UnaryOperator>(E) &&
12310 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12311 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12312 if (isa<MemberExpr>(Op)) {
12313 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12314 MisalignedMember(Op));
12315 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012316 (T->isIntegerType() ||
12317 (T->isPointerType() &&
12318 Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012319 MisalignedMembers.erase(MA);
12320 }
12321 }
12322}
12323
12324void Sema::RefersToMemberWithReducedAlignment(
12325 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012326 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12327 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012328 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012329 if (!ME)
12330 return;
12331
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012332 // No need to check expressions with an __unaligned-qualified type.
12333 if (E->getType().getQualifiers().hasUnaligned())
12334 return;
12335
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012336 // For a chain of MemberExpr like "a.b.c.d" this list
12337 // will keep FieldDecl's like [d, c, b].
12338 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12339 const MemberExpr *TopME = nullptr;
12340 bool AnyIsPacked = false;
12341 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012342 QualType BaseType = ME->getBase()->getType();
12343 if (ME->isArrow())
12344 BaseType = BaseType->getPointeeType();
12345 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012346 if (RD->isInvalidDecl())
12347 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012348
12349 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012350 auto *FD = dyn_cast<FieldDecl>(MD);
12351 // We do not care about non-data members.
12352 if (!FD || FD->isInvalidDecl())
12353 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012354
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012355 AnyIsPacked =
12356 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12357 ReverseMemberChain.push_back(FD);
12358
12359 TopME = ME;
12360 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12361 } while (ME);
12362 assert(TopME && "We did not compute a topmost MemberExpr!");
12363
12364 // Not the scope of this diagnostic.
12365 if (!AnyIsPacked)
12366 return;
12367
12368 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12369 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12370 // TODO: The innermost base of the member expression may be too complicated.
12371 // For now, just disregard these cases. This is left for future
12372 // improvement.
12373 if (!DRE && !isa<CXXThisExpr>(TopBase))
12374 return;
12375
12376 // Alignment expected by the whole expression.
12377 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12378
12379 // No need to do anything else with this case.
12380 if (ExpectedAlignment.isOne())
12381 return;
12382
12383 // Synthesize offset of the whole access.
12384 CharUnits Offset;
12385 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12386 I++) {
12387 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12388 }
12389
12390 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12391 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12392 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12393
12394 // The base expression of the innermost MemberExpr may give
12395 // stronger guarantees than the class containing the member.
12396 if (DRE && !TopME->isArrow()) {
12397 const ValueDecl *VD = DRE->getDecl();
12398 if (!VD->getType()->isReferenceType())
12399 CompleteObjectAlignment =
12400 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12401 }
12402
12403 // Check if the synthesized offset fulfills the alignment.
12404 if (Offset % ExpectedAlignment != 0 ||
12405 // It may fulfill the offset it but the effective alignment may still be
12406 // lower than the expected expression alignment.
12407 CompleteObjectAlignment < ExpectedAlignment) {
12408 // If this happens, we want to determine a sensible culprit of this.
12409 // Intuitively, watching the chain of member expressions from right to
12410 // left, we start with the required alignment (as required by the field
12411 // type) but some packed attribute in that chain has reduced the alignment.
12412 // It may happen that another packed structure increases it again. But if
12413 // we are here such increase has not been enough. So pointing the first
12414 // FieldDecl that either is packed or else its RecordDecl is,
12415 // seems reasonable.
12416 FieldDecl *FD = nullptr;
12417 CharUnits Alignment;
12418 for (FieldDecl *FDI : ReverseMemberChain) {
12419 if (FDI->hasAttr<PackedAttr>() ||
12420 FDI->getParent()->hasAttr<PackedAttr>()) {
12421 FD = FDI;
12422 Alignment = std::min(
12423 Context.getTypeAlignInChars(FD->getType()),
12424 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12425 break;
12426 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012427 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012428 assert(FD && "We did not find a packed FieldDecl!");
12429 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012430 }
12431}
12432
12433void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12434 using namespace std::placeholders;
12435 RefersToMemberWithReducedAlignment(
12436 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12437 _2, _3, _4));
12438}
12439