blob: 9ed21daad603aa9b45957ee3fa6d3e02e50e2596 [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
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
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
31#include "clang/AST/OperationKinds.h"
32#include "clang/AST/Stmt.h"
33#include "clang/AST/TemplateBase.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Analysis/Analyses/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000038#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000039#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000040#include "clang/Basic/Diagnostic.h"
41#include "clang/Basic/IdentifierTable.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/OpenCLOptions.h"
45#include "clang/Basic/OperatorKinds.h"
46#include "clang/Basic/PartialDiagnostic.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
49#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000050#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000051#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000052#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000053#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000054#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000055#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000058#include "clang/Sema/Ownership.h"
59#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Sema/ScopeInfo.h"
61#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000062#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000063#include "llvm/ADT/APFloat.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/FoldingSet.h"
69#include "llvm/ADT/None.h"
70#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000071#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000072#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000073#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000074#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000075#include "llvm/ADT/SmallVector.h"
76#include "llvm/ADT/StringRef.h"
77#include "llvm/ADT/StringSwitch.h"
78#include "llvm/ADT/Triple.h"
79#include "llvm/Support/AtomicOrdering.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000082#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000083#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000084#include "llvm/Support/Format.h"
85#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000086#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000087#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000088#include <algorithm>
89#include <cassert>
90#include <cstddef>
91#include <cstdint>
92#include <functional>
93#include <limits>
94#include <string>
95#include <tuple>
96#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000097
Chris Lattnerb87b1b32007-08-10 20:18:51 +000098using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000099using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000100
Chris Lattnera26fb342009-02-18 17:49:48 +0000101SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000103 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000105}
106
John McCallbebede42011-02-26 05:39:39 +0000107/// Checks that a call expression's argument count is the desired number.
108/// This is useful when doing custom type-checking. Returns true on error.
109static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110 unsigned argCount = call->getNumArgs();
111 if (argCount == desiredArgCount) return false;
112
113 if (argCount < desiredArgCount)
114 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115 << 0 /*function call*/ << desiredArgCount << argCount
116 << call->getSourceRange();
117
118 // Highlight all the excess arguments.
119 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120 call->getArg(argCount - 1)->getLocEnd());
121
122 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123 << 0 /*function call*/ << desiredArgCount << argCount
124 << call->getArg(1)->getSourceRange();
125}
126
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000127/// Check that the first argument to __builtin_annotation is an integer
128/// and the second argument is a non-wide string literal.
129static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130 if (checkArgCount(S, TheCall, 2))
131 return true;
132
133 // First argument should be an integer.
134 Expr *ValArg = TheCall->getArg(0);
135 QualType Ty = ValArg->getType();
136 if (!Ty->isIntegerType()) {
137 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000139 return true;
140 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000141
142 // Second argument should be a constant string.
143 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145 if (!Literal || !Literal->isAscii()) {
146 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147 << StrArg->getSourceRange();
148 return true;
149 }
150
151 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000152 return false;
153}
154
Reid Kleckner30701ed2017-09-05 20:27:35 +0000155static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156 // We need at least one argument.
157 if (TheCall->getNumArgs() < 1) {
158 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159 << 0 << 1 << TheCall->getNumArgs()
160 << TheCall->getCallee()->getSourceRange();
161 return true;
162 }
163
164 // All arguments should be wide string literals.
165 for (Expr *Arg : TheCall->arguments()) {
166 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167 if (!Literal || !Literal->isWide()) {
168 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169 << Arg->getSourceRange();
170 return true;
171 }
172 }
173
174 return false;
175}
176
Richard Smith6cbd65d2013-07-11 02:27:57 +0000177/// Check that the argument to __builtin_addressof is a glvalue, and set the
178/// result type to the corresponding pointer type.
179static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180 if (checkArgCount(S, TheCall, 1))
181 return true;
182
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000183 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000184 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185 if (ResultType.isNull())
186 return true;
187
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000188 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000189 TheCall->setType(ResultType);
190 return false;
191}
192
John McCall03107a42015-10-29 20:48:01 +0000193static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194 if (checkArgCount(S, TheCall, 3))
195 return true;
196
197 // First two arguments should be integers.
198 for (unsigned I = 0; I < 2; ++I) {
199 Expr *Arg = TheCall->getArg(I);
200 QualType Ty = Arg->getType();
201 if (!Ty->isIntegerType()) {
202 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203 << Ty << Arg->getSourceRange();
204 return true;
205 }
206 }
207
208 // Third argument should be a pointer to a non-const integer.
209 // IRGen correctly handles volatile, restrict, and address spaces, and
210 // the other qualifiers aren't possible.
211 {
212 Expr *Arg = TheCall->getArg(2);
213 QualType Ty = Arg->getType();
214 const auto *PtrTy = Ty->getAs<PointerType>();
215 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216 !PtrTy->getPointeeType().isConstQualified())) {
217 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218 << Ty << Arg->getSourceRange();
219 return true;
220 }
221 }
222
223 return false;
224}
225
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000226static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227 CallExpr *TheCall, unsigned SizeIdx,
228 unsigned DstSizeIdx) {
229 if (TheCall->getNumArgs() <= SizeIdx ||
230 TheCall->getNumArgs() <= DstSizeIdx)
231 return;
232
233 const Expr *SizeArg = TheCall->getArg(SizeIdx);
234 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235
236 llvm::APSInt Size, DstSize;
237
238 // find out if both sizes are known at compile time
239 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241 return;
242
243 if (Size.ule(DstSize))
244 return;
245
246 // confirmed overflow so generate the diagnostic.
247 IdentifierInfo *FnName = FDecl->getIdentifier();
248 SourceLocation SL = TheCall->getLocStart();
249 SourceRange SR = TheCall->getSourceRange();
250
251 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252}
253
Peter Collingbournef7706832014-12-12 23:41:25 +0000254static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255 if (checkArgCount(S, BuiltinCall, 2))
256 return true;
257
258 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260 Expr *Call = BuiltinCall->getArg(0);
261 Expr *Chain = BuiltinCall->getArg(1);
262
263 if (Call->getStmtClass() != Stmt::CallExprClass) {
264 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265 << Call->getSourceRange();
266 return true;
267 }
268
269 auto CE = cast<CallExpr>(Call);
270 if (CE->getCallee()->getType()->isBlockPointerType()) {
271 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272 << Call->getSourceRange();
273 return true;
274 }
275
276 const Decl *TargetDecl = CE->getCalleeDecl();
277 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278 if (FD->getBuiltinID()) {
279 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280 << Call->getSourceRange();
281 return true;
282 }
283
284 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286 << Call->getSourceRange();
287 return true;
288 }
289
290 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291 if (ChainResult.isInvalid())
292 return true;
293 if (!ChainResult.get()->getType()->isPointerType()) {
294 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295 << Chain->getSourceRange();
296 return true;
297 }
298
David Majnemerced8bdf2015-02-25 17:36:15 +0000299 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000300 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301 QualType BuiltinTy = S.Context.getFunctionType(
302 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304
305 Builtin =
306 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307
308 BuiltinCall->setType(CE->getType());
309 BuiltinCall->setValueKind(CE->getValueKind());
310 BuiltinCall->setObjectKind(CE->getObjectKind());
311 BuiltinCall->setCallee(Builtin);
312 BuiltinCall->setArg(1, ChainResult.get());
313
314 return false;
315}
316
Reid Kleckner1d59f992015-01-22 01:36:17 +0000317static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318 Scope::ScopeFlags NeededScopeFlags,
319 unsigned DiagID) {
320 // Scopes aren't available during instantiation. Fortunately, builtin
321 // functions cannot be template args so they cannot be formed through template
322 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000323 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000324 return false;
325
326 Scope *S = SemaRef.getCurScope();
327 while (S && !S->isSEHExceptScope())
328 S = S->getParent();
329 if (!S || !(S->getFlags() & NeededScopeFlags)) {
330 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332 << DRE->getDecl()->getIdentifier();
333 return true;
334 }
335
336 return false;
337}
338
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000339static inline bool isBlockPointer(Expr *Arg) {
340 return Arg->getType()->isBlockPointerType();
341}
342
343/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344/// void*, which is a requirement of device side enqueue.
345static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346 const BlockPointerType *BPT =
347 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348 ArrayRef<QualType> Params =
349 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350 unsigned ArgCounter = 0;
351 bool IllegalParams = false;
352 // Iterate through the block parameters until either one is found that is not
353 // a local void*, or the block is valid.
354 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355 I != E; ++I, ++ArgCounter) {
356 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358 LangAS::opencl_local) {
359 // Get the location of the error. If a block literal has been passed
360 // (BlockExpr) then we can point straight to the offending argument,
361 // else we just point to the variable reference.
362 SourceLocation ErrorLoc;
363 if (isa<BlockExpr>(BlockArg)) {
364 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366 } else if (isa<DeclRefExpr>(BlockArg)) {
367 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368 }
369 S.Diag(ErrorLoc,
370 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371 IllegalParams = true;
372 }
373 }
374
375 return IllegalParams;
376}
377
Joey Gouly84ae3362017-07-31 15:15:59 +0000378static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382 return true;
383 }
384 return false;
385}
386
Joey Goulyfa76b492017-08-01 13:27:09 +0000387static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388 if (checkArgCount(S, TheCall, 2))
389 return true;
390
391 if (checkOpenCLSubgroupExt(S, TheCall))
392 return true;
393
394 // First argument is an ndrange_t type.
395 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000396 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000397 S.Diag(NDRangeArg->getLocStart(),
398 diag::err_opencl_builtin_expected_type)
399 << TheCall->getDirectCallee() << "'ndrange_t'";
400 return true;
401 }
402
403 Expr *BlockArg = TheCall->getArg(1);
404 if (!isBlockPointer(BlockArg)) {
405 S.Diag(BlockArg->getLocStart(),
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->getDirectCallee() << "block";
408 return true;
409 }
410 return checkOpenCLBlockArgs(S, BlockArg);
411}
412
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000413/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414/// get_kernel_work_group_size
415/// and get_kernel_preferred_work_group_size_multiple builtin functions.
416static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417 if (checkArgCount(S, TheCall, 1))
418 return true;
419
420 Expr *BlockArg = TheCall->getArg(0);
421 if (!isBlockPointer(BlockArg)) {
422 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000423 diag::err_opencl_builtin_expected_type)
424 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000425 return true;
426 }
427 return checkOpenCLBlockArgs(S, BlockArg);
428}
429
Simon Pilgrim2c518802017-03-30 14:13:19 +0000430/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000431static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432 const QualType &IntType);
433
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000434static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000435 unsigned Start, unsigned End) {
436 bool IllegalParams = false;
437 for (unsigned I = Start; I <= End; ++I)
438 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439 S.Context.getSizeType());
440 return IllegalParams;
441}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000442
443/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444/// 'local void*' parameter of passed block.
445static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446 Expr *BlockArg,
447 unsigned NumNonVarArgs) {
448 const BlockPointerType *BPT =
449 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450 unsigned NumBlockParams =
451 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452 unsigned TotalNumArgs = TheCall->getNumArgs();
453
454 // For each argument passed to the block, a corresponding uint needs to
455 // be passed to describe the size of the local memory.
456 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457 S.Diag(TheCall->getLocStart(),
458 diag::err_opencl_enqueue_kernel_local_size_args);
459 return true;
460 }
461
462 // Check that the sizes of the local memory are specified by integers.
463 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464 TotalNumArgs - 1);
465}
466
467/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468/// overload formats specified in Table 6.13.17.1.
469/// int enqueue_kernel(queue_t queue,
470/// kernel_enqueue_flags_t flags,
471/// const ndrange_t ndrange,
472/// void (^block)(void))
473/// int enqueue_kernel(queue_t queue,
474/// kernel_enqueue_flags_t flags,
475/// const ndrange_t ndrange,
476/// uint num_events_in_wait_list,
477/// clk_event_t *event_wait_list,
478/// clk_event_t *event_ret,
479/// void (^block)(void))
480/// int enqueue_kernel(queue_t queue,
481/// kernel_enqueue_flags_t flags,
482/// const ndrange_t ndrange,
483/// void (^block)(local void*, ...),
484/// uint size0, ...)
485/// int enqueue_kernel(queue_t queue,
486/// kernel_enqueue_flags_t flags,
487/// const ndrange_t ndrange,
488/// uint num_events_in_wait_list,
489/// clk_event_t *event_wait_list,
490/// clk_event_t *event_ret,
491/// void (^block)(local void*, ...),
492/// uint size0, ...)
493static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494 unsigned NumArgs = TheCall->getNumArgs();
495
496 if (NumArgs < 4) {
497 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498 return true;
499 }
500
501 Expr *Arg0 = TheCall->getArg(0);
502 Expr *Arg1 = TheCall->getArg(1);
503 Expr *Arg2 = TheCall->getArg(2);
504 Expr *Arg3 = TheCall->getArg(3);
505
506 // First argument always needs to be a queue_t type.
507 if (!Arg0->getType()->isQueueT()) {
508 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000509 diag::err_opencl_builtin_expected_type)
510 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000511 return true;
512 }
513
514 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515 if (!Arg1->getType()->isIntegerType()) {
516 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000517 diag::err_opencl_builtin_expected_type)
518 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000519 return true;
520 }
521
522 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000523 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000525 diag::err_opencl_builtin_expected_type)
526 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000527 return true;
528 }
529
530 // With four arguments, there is only one form that the function could be
531 // called in: no events and no variable arguments.
532 if (NumArgs == 4) {
533 // check that the last argument is the right block type.
534 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000535 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 return true;
538 }
539 // we have a block type, check the prototype
540 const BlockPointerType *BPT =
541 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543 S.Diag(Arg3->getLocStart(),
544 diag::err_opencl_enqueue_kernel_blocks_no_args);
545 return true;
546 }
547 return false;
548 }
549 // we can have block + varargs.
550 if (isBlockPointer(Arg3))
551 return (checkOpenCLBlockArgs(S, Arg3) ||
552 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553 // last two cases with either exactly 7 args or 7 args and varargs.
554 if (NumArgs >= 7) {
555 // check common block argument.
556 Expr *Arg6 = TheCall->getArg(6);
557 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000558 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000560 return true;
561 }
562 if (checkOpenCLBlockArgs(S, Arg6))
563 return true;
564
565 // Forth argument has to be any integer type.
566 if (!Arg3->getType()->isIntegerType()) {
567 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000568 diag::err_opencl_builtin_expected_type)
569 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000570 return true;
571 }
572 // check remaining common arguments.
573 Expr *Arg4 = TheCall->getArg(4);
574 Expr *Arg5 = TheCall->getArg(5);
575
Anastasia Stulova2b461202016-11-14 15:34:01 +0000576 // Fifth argument is always passed as a pointer to clk_event_t.
577 if (!Arg4->isNullPointerConstant(S.Context,
578 Expr::NPC_ValueDependentIsNotNull) &&
579 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000580 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 << S.Context.getPointerType(S.Context.OCLClkEventTy);
584 return true;
585 }
586
Anastasia Stulova2b461202016-11-14 15:34:01 +0000587 // Sixth argument is always passed as a pointer to clk_event_t.
588 if (!Arg5->isNullPointerConstant(S.Context,
589 Expr::NPC_ValueDependentIsNotNull) &&
590 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000591 Arg5->getType()->getPointeeType()->isClkEventT())) {
592 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000593 diag::err_opencl_builtin_expected_type)
594 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000595 << S.Context.getPointerType(S.Context.OCLClkEventTy);
596 return true;
597 }
598
599 if (NumArgs == 7)
600 return false;
601
602 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603 }
604
605 // None of the specific case has been detected, give generic error
606 S.Diag(TheCall->getLocStart(),
607 diag::err_opencl_enqueue_kernel_incorrect_args);
608 return true;
609}
610
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000611/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000612static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000614}
615
616/// Returns true if pipe element type is different from the pointer.
617static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618 const Expr *Arg0 = Call->getArg(0);
619 // First argument type should always be pipe.
620 if (!Arg0->getType()->isPipeType()) {
621 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000622 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000623 return true;
624 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000626 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627 // Validates the access qualifier is compatible with the call.
628 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629 // read_only and write_only, and assumed to be read_only if no qualifier is
630 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000631 switch (Call->getDirectCallee()->getBuiltinID()) {
632 case Builtin::BIread_pipe:
633 case Builtin::BIreserve_read_pipe:
634 case Builtin::BIcommit_read_pipe:
635 case Builtin::BIwork_group_reserve_read_pipe:
636 case Builtin::BIsub_group_reserve_read_pipe:
637 case Builtin::BIwork_group_commit_read_pipe:
638 case Builtin::BIsub_group_commit_read_pipe:
639 if (!(!AccessQual || AccessQual->isReadOnly())) {
640 S.Diag(Arg0->getLocStart(),
641 diag::err_opencl_builtin_pipe_invalid_access_modifier)
642 << "read_only" << Arg0->getSourceRange();
643 return true;
644 }
645 break;
646 case Builtin::BIwrite_pipe:
647 case Builtin::BIreserve_write_pipe:
648 case Builtin::BIcommit_write_pipe:
649 case Builtin::BIwork_group_reserve_write_pipe:
650 case Builtin::BIsub_group_reserve_write_pipe:
651 case Builtin::BIwork_group_commit_write_pipe:
652 case Builtin::BIsub_group_commit_write_pipe:
653 if (!(AccessQual && AccessQual->isWriteOnly())) {
654 S.Diag(Arg0->getLocStart(),
655 diag::err_opencl_builtin_pipe_invalid_access_modifier)
656 << "write_only" << Arg0->getSourceRange();
657 return true;
658 }
659 break;
660 default:
661 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000662 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 return false;
664}
665
666/// Returns true if pipe element type is different from the pointer.
667static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668 const Expr *Arg0 = Call->getArg(0);
669 const Expr *ArgIdx = Call->getArg(Idx);
670 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000671 const QualType EltTy = PipeTy->getElementType();
672 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000673 // The Idx argument should be a pointer and the type of the pointer and
674 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000675 if (!ArgTy ||
676 !S.Context.hasSameType(
677 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000678 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000679 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000680 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000681 return true;
682 }
683 return false;
684}
685
686// \brief Performs semantic analysis for the read/write_pipe call.
687// \param S Reference to the semantic analyzer.
688// \param Call A pointer to the builtin call.
689// \return True if a semantic error has been found, false otherwise.
690static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000691 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000693 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000694 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000695 if (checkOpenCLPipeArg(S, Call))
696 return true;
697 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000698 // read/write_pipe(pipe T, T*).
699 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700 if (checkOpenCLPipePacketType(S, Call, 1))
701 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000702 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000703
704 case 4: {
705 if (checkOpenCLPipeArg(S, Call))
706 return true;
707 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000708 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000710 if (!Call->getArg(1)->getType()->isReserveIDT()) {
711 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000712 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000713 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000714 return true;
715 }
716
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000717 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000718 const Expr *Arg2 = Call->getArg(2);
719 if (!Arg2->getType()->isIntegerType() &&
720 !Arg2->getType()->isUnsignedIntegerType()) {
721 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000722 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000723 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000724 return true;
725 }
726
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000727 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000728 if (checkOpenCLPipePacketType(S, Call, 3))
729 return true;
730 } break;
731 default:
732 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000733 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000734 return true;
735 }
736
737 return false;
738}
739
740// \brief Performs a semantic analysis on the {work_group_/sub_group_
741// /_}reserve_{read/write}_pipe
742// \param S Reference to the semantic analyzer.
743// \param Call The call to the builtin function to be analyzed.
744// \return True if a semantic error was found, false otherwise.
745static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746 if (checkArgCount(S, Call, 2))
747 return true;
748
749 if (checkOpenCLPipeArg(S, Call))
750 return true;
751
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000752 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000753 if (!Call->getArg(1)->getType()->isIntegerType() &&
754 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000756 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000757 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000758 return true;
759 }
760
Joey Gouly922ca232017-08-09 14:52:47 +0000761 // Since return type of reserve_read/write_pipe built-in function is
762 // reserve_id_t, which is not defined in the builtin def file , we used int
763 // as return type and need to override the return type of these functions.
764 Call->setType(S.Context.OCLReserveIDTy);
765
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 return false;
767}
768
769// \brief Performs a semantic analysis on {work_group_/sub_group_
770// /_}commit_{read/write}_pipe
771// \param S Reference to the semantic analyzer.
772// \param Call The call to the builtin function to be analyzed.
773// \return True if a semantic error was found, false otherwise.
774static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775 if (checkArgCount(S, Call, 2))
776 return true;
777
778 if (checkOpenCLPipeArg(S, Call))
779 return true;
780
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000781 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000782 if (!Call->getArg(1)->getType()->isReserveIDT()) {
783 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000784 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000785 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000786 return true;
787 }
788
789 return false;
790}
791
792// \brief Performs a semantic analysis on the call to built-in Pipe
793// Query Functions.
794// \param S Reference to the semantic analyzer.
795// \param Call The call to the builtin function to be analyzed.
796// \return True if a semantic error was found, false otherwise.
797static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798 if (checkArgCount(S, Call, 1))
799 return true;
800
801 if (!Call->getArg(0)->getType()->isPipeType()) {
802 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000803 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000804 return true;
805 }
806
807 return false;
808}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000809
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000810// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000811// \brief Performs semantic analysis for the to_global/local/private call.
812// \param S Reference to the semantic analyzer.
813// \param BuiltinID ID of the builtin function.
814// \param Call A pointer to the builtin call.
815// \return True if a semantic error has been found, false otherwise.
816static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000818 if (Call->getNumArgs() != 1) {
819 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820 << Call->getDirectCallee() << Call->getSourceRange();
821 return true;
822 }
823
824 auto RT = Call->getArg(0)->getType();
825 if (!RT->isPointerType() || RT->getPointeeType()
826 .getAddressSpace() == LangAS::opencl_constant) {
827 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829 return true;
830 }
831
832 RT = RT->getPointeeType();
833 auto Qual = RT.getQualifiers();
834 switch (BuiltinID) {
835 case Builtin::BIto_global:
836 Qual.setAddressSpace(LangAS::opencl_global);
837 break;
838 case Builtin::BIto_local:
839 Qual.setAddressSpace(LangAS::opencl_local);
840 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000841 case Builtin::BIto_private:
842 Qual.setAddressSpace(LangAS::opencl_private);
843 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000844 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000845 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000846 }
847 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848 RT.getUnqualifiedType(), Qual)));
849
850 return false;
851}
852
John McCalldadc5752010-08-24 06:29:42 +0000853ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000854Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000856 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000857
Chris Lattner3be167f2010-10-01 23:23:24 +0000858 // Find out if any arguments are required to be integer constant expressions.
859 unsigned ICEArguments = 0;
860 ASTContext::GetBuiltinTypeError Error;
861 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862 if (Error != ASTContext::GE_None)
863 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
864
865 // If any arguments are required to be ICE's, check and diagnose.
866 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867 // Skip arguments not required to be ICE's.
868 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869
870 llvm::APSInt Result;
871 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872 return true;
873 ICEArguments &= ~(1 << ArgNo);
874 }
875
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000877 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000878 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000879 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000880 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000881 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000883 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000884 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000885 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000886 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000887 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000888 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000889 case Builtin::BI__va_start: {
890 switch (Context.getTargetInfo().getTriple().getArch()) {
891 case llvm::Triple::arm:
892 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000893 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000894 return ExprError();
895 break;
896 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000897 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000898 return ExprError();
899 break;
900 }
901 break;
902 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000903 case Builtin::BI__builtin_isgreater:
904 case Builtin::BI__builtin_isgreaterequal:
905 case Builtin::BI__builtin_isless:
906 case Builtin::BI__builtin_islessequal:
907 case Builtin::BI__builtin_islessgreater:
908 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000909 if (SemaBuiltinUnorderedCompare(TheCall))
910 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000911 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000912 case Builtin::BI__builtin_fpclassify:
913 if (SemaBuiltinFPClassification(TheCall, 6))
914 return ExprError();
915 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000916 case Builtin::BI__builtin_isfinite:
917 case Builtin::BI__builtin_isinf:
918 case Builtin::BI__builtin_isinf_sign:
919 case Builtin::BI__builtin_isnan:
920 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000921 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000922 return ExprError();
923 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000924 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000925 return SemaBuiltinShuffleVector(TheCall);
926 // TheCall will be freed by the smart pointer here, but that's fine, since
927 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000928 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000929 if (SemaBuiltinPrefetch(TheCall))
930 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000931 break;
David Majnemer51169932016-10-31 05:37:48 +0000932 case Builtin::BI__builtin_alloca_with_align:
933 if (SemaBuiltinAllocaWithAlign(TheCall))
934 return ExprError();
935 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000936 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000937 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000938 if (SemaBuiltinAssume(TheCall))
939 return ExprError();
940 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000941 case Builtin::BI__builtin_assume_aligned:
942 if (SemaBuiltinAssumeAligned(TheCall))
943 return ExprError();
944 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000945 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000946 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000947 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000948 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000949 case Builtin::BI__builtin_longjmp:
950 if (SemaBuiltinLongjmp(TheCall))
951 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000952 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000953 case Builtin::BI__builtin_setjmp:
954 if (SemaBuiltinSetjmp(TheCall))
955 return ExprError();
956 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000957 case Builtin::BI_setjmp:
958 case Builtin::BI_setjmpex:
959 if (checkArgCount(*this, TheCall, 1))
960 return true;
961 break;
John McCallbebede42011-02-26 05:39:39 +0000962 case Builtin::BI__builtin_classify_type:
963 if (checkArgCount(*this, TheCall, 1)) return true;
964 TheCall->setType(Context.IntTy);
965 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000966 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000967 if (checkArgCount(*this, TheCall, 1)) return true;
968 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000969 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000970 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000971 case Builtin::BI__sync_fetch_and_add_1:
972 case Builtin::BI__sync_fetch_and_add_2:
973 case Builtin::BI__sync_fetch_and_add_4:
974 case Builtin::BI__sync_fetch_and_add_8:
975 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000976 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000977 case Builtin::BI__sync_fetch_and_sub_1:
978 case Builtin::BI__sync_fetch_and_sub_2:
979 case Builtin::BI__sync_fetch_and_sub_4:
980 case Builtin::BI__sync_fetch_and_sub_8:
981 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000982 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000983 case Builtin::BI__sync_fetch_and_or_1:
984 case Builtin::BI__sync_fetch_and_or_2:
985 case Builtin::BI__sync_fetch_and_or_4:
986 case Builtin::BI__sync_fetch_and_or_8:
987 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000988 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000989 case Builtin::BI__sync_fetch_and_and_1:
990 case Builtin::BI__sync_fetch_and_and_2:
991 case Builtin::BI__sync_fetch_and_and_4:
992 case Builtin::BI__sync_fetch_and_and_8:
993 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000994 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000995 case Builtin::BI__sync_fetch_and_xor_1:
996 case Builtin::BI__sync_fetch_and_xor_2:
997 case Builtin::BI__sync_fetch_and_xor_4:
998 case Builtin::BI__sync_fetch_and_xor_8:
999 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001000 case Builtin::BI__sync_fetch_and_nand:
1001 case Builtin::BI__sync_fetch_and_nand_1:
1002 case Builtin::BI__sync_fetch_and_nand_2:
1003 case Builtin::BI__sync_fetch_and_nand_4:
1004 case Builtin::BI__sync_fetch_and_nand_8:
1005 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001006 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001007 case Builtin::BI__sync_add_and_fetch_1:
1008 case Builtin::BI__sync_add_and_fetch_2:
1009 case Builtin::BI__sync_add_and_fetch_4:
1010 case Builtin::BI__sync_add_and_fetch_8:
1011 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001012 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001013 case Builtin::BI__sync_sub_and_fetch_1:
1014 case Builtin::BI__sync_sub_and_fetch_2:
1015 case Builtin::BI__sync_sub_and_fetch_4:
1016 case Builtin::BI__sync_sub_and_fetch_8:
1017 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001018 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001019 case Builtin::BI__sync_and_and_fetch_1:
1020 case Builtin::BI__sync_and_and_fetch_2:
1021 case Builtin::BI__sync_and_and_fetch_4:
1022 case Builtin::BI__sync_and_and_fetch_8:
1023 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001024 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001025 case Builtin::BI__sync_or_and_fetch_1:
1026 case Builtin::BI__sync_or_and_fetch_2:
1027 case Builtin::BI__sync_or_and_fetch_4:
1028 case Builtin::BI__sync_or_and_fetch_8:
1029 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001030 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001031 case Builtin::BI__sync_xor_and_fetch_1:
1032 case Builtin::BI__sync_xor_and_fetch_2:
1033 case Builtin::BI__sync_xor_and_fetch_4:
1034 case Builtin::BI__sync_xor_and_fetch_8:
1035 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001036 case Builtin::BI__sync_nand_and_fetch:
1037 case Builtin::BI__sync_nand_and_fetch_1:
1038 case Builtin::BI__sync_nand_and_fetch_2:
1039 case Builtin::BI__sync_nand_and_fetch_4:
1040 case Builtin::BI__sync_nand_and_fetch_8:
1041 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001042 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001043 case Builtin::BI__sync_val_compare_and_swap_1:
1044 case Builtin::BI__sync_val_compare_and_swap_2:
1045 case Builtin::BI__sync_val_compare_and_swap_4:
1046 case Builtin::BI__sync_val_compare_and_swap_8:
1047 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001048 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001049 case Builtin::BI__sync_bool_compare_and_swap_1:
1050 case Builtin::BI__sync_bool_compare_and_swap_2:
1051 case Builtin::BI__sync_bool_compare_and_swap_4:
1052 case Builtin::BI__sync_bool_compare_and_swap_8:
1053 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001054 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001055 case Builtin::BI__sync_lock_test_and_set_1:
1056 case Builtin::BI__sync_lock_test_and_set_2:
1057 case Builtin::BI__sync_lock_test_and_set_4:
1058 case Builtin::BI__sync_lock_test_and_set_8:
1059 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001060 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001061 case Builtin::BI__sync_lock_release_1:
1062 case Builtin::BI__sync_lock_release_2:
1063 case Builtin::BI__sync_lock_release_4:
1064 case Builtin::BI__sync_lock_release_8:
1065 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001066 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001067 case Builtin::BI__sync_swap_1:
1068 case Builtin::BI__sync_swap_2:
1069 case Builtin::BI__sync_swap_4:
1070 case Builtin::BI__sync_swap_8:
1071 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001072 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001073 case Builtin::BI__builtin_nontemporal_load:
1074 case Builtin::BI__builtin_nontemporal_store:
1075 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001076#define BUILTIN(ID, TYPE, ATTRS)
1077#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001079 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001080#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001081 case Builtin::BI__annotation:
1082 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083 return ExprError();
1084 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001085 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001086 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001087 return ExprError();
1088 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001089 case Builtin::BI__builtin_addressof:
1090 if (SemaBuiltinAddressof(*this, TheCall))
1091 return ExprError();
1092 break;
John McCall03107a42015-10-29 20:48:01 +00001093 case Builtin::BI__builtin_add_overflow:
1094 case Builtin::BI__builtin_sub_overflow:
1095 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001096 if (SemaBuiltinOverflow(*this, TheCall))
1097 return ExprError();
1098 break;
Richard Smith760520b2014-06-03 23:27:44 +00001099 case Builtin::BI__builtin_operator_new:
1100 case Builtin::BI__builtin_operator_delete:
1101 if (!getLangOpts().CPlusPlus) {
1102 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1103 << (BuiltinID == Builtin::BI__builtin_operator_new
1104 ? "__builtin_operator_new"
1105 : "__builtin_operator_delete")
1106 << "C++";
1107 return ExprError();
1108 }
1109 // CodeGen assumes it can find the global new and delete to call,
1110 // so ensure that they are declared.
1111 DeclareGlobalNewDelete();
1112 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001113
1114 // check secure string manipulation functions where overflows
1115 // are detectable at compile time
1116 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001117 case Builtin::BI__builtin___memmove_chk:
1118 case Builtin::BI__builtin___memset_chk:
1119 case Builtin::BI__builtin___strlcat_chk:
1120 case Builtin::BI__builtin___strlcpy_chk:
1121 case Builtin::BI__builtin___strncat_chk:
1122 case Builtin::BI__builtin___strncpy_chk:
1123 case Builtin::BI__builtin___stpncpy_chk:
1124 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1125 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001126 case Builtin::BI__builtin___memccpy_chk:
1127 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1128 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001129 case Builtin::BI__builtin___snprintf_chk:
1130 case Builtin::BI__builtin___vsnprintf_chk:
1131 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1132 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001133 case Builtin::BI__builtin_call_with_static_chain:
1134 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1135 return ExprError();
1136 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001137 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001138 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001139 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140 diag::err_seh___except_block))
1141 return ExprError();
1142 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001143 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001144 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001145 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146 diag::err_seh___except_filter))
1147 return ExprError();
1148 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001149 case Builtin::BI__GetExceptionInfo:
1150 if (checkArgCount(*this, TheCall, 1))
1151 return ExprError();
1152
1153 if (CheckCXXThrowOperand(
1154 TheCall->getLocStart(),
1155 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1156 TheCall))
1157 return ExprError();
1158
1159 TheCall->setType(Context.VoidPtrTy);
1160 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001161 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001162 case Builtin::BIread_pipe:
1163 case Builtin::BIwrite_pipe:
1164 // Since those two functions are declared with var args, we need a semantic
1165 // check for the argument.
1166 if (SemaBuiltinRWPipe(*this, TheCall))
1167 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001168 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001169 break;
1170 case Builtin::BIreserve_read_pipe:
1171 case Builtin::BIreserve_write_pipe:
1172 case Builtin::BIwork_group_reserve_read_pipe:
1173 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001174 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1175 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001176 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001177 case Builtin::BIsub_group_reserve_read_pipe:
1178 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001179 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001181 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001182 break;
1183 case Builtin::BIcommit_read_pipe:
1184 case Builtin::BIcommit_write_pipe:
1185 case Builtin::BIwork_group_commit_read_pipe:
1186 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001187 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1188 return ExprError();
1189 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001190 case Builtin::BIsub_group_commit_read_pipe:
1191 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001192 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001194 return ExprError();
1195 break;
1196 case Builtin::BIget_pipe_num_packets:
1197 case Builtin::BIget_pipe_max_packets:
1198 if (SemaBuiltinPipePackets(*this, TheCall))
1199 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001200 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001201 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001202 case Builtin::BIto_global:
1203 case Builtin::BIto_local:
1204 case Builtin::BIto_private:
1205 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1206 return ExprError();
1207 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001208 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1209 case Builtin::BIenqueue_kernel:
1210 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1211 return ExprError();
1212 break;
1213 case Builtin::BIget_kernel_work_group_size:
1214 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1215 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1216 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001217 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001218 break;
1219 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1221 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1222 return ExprError();
1223 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001224 case Builtin::BI__builtin_os_log_format:
1225 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001226 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001227 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001228 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001229 }
Richard Smith760520b2014-06-03 23:27:44 +00001230
Nate Begeman4904e322010-06-08 02:47:44 +00001231 // Since the target specific builtins for each arch overlap, only check those
1232 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001233 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001234 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001235 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001236 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001237 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001238 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001239 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1240 return ExprError();
1241 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001242 case llvm::Triple::aarch64:
1243 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001244 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001245 return ExprError();
1246 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001247 case llvm::Triple::mips:
1248 case llvm::Triple::mipsel:
1249 case llvm::Triple::mips64:
1250 case llvm::Triple::mips64el:
1251 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1252 return ExprError();
1253 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001254 case llvm::Triple::systemz:
1255 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1256 return ExprError();
1257 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001258 case llvm::Triple::x86:
1259 case llvm::Triple::x86_64:
1260 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1261 return ExprError();
1262 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001263 case llvm::Triple::ppc:
1264 case llvm::Triple::ppc64:
1265 case llvm::Triple::ppc64le:
1266 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1267 return ExprError();
1268 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001269 default:
1270 break;
1271 }
1272 }
1273
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001274 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001275}
1276
Nate Begeman91e1fea2010-06-14 05:21:25 +00001277// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001278static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001279 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001280 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001281 switch (Type.getEltType()) {
1282 case NeonTypeFlags::Int8:
1283 case NeonTypeFlags::Poly8:
1284 return shift ? 7 : (8 << IsQuad) - 1;
1285 case NeonTypeFlags::Int16:
1286 case NeonTypeFlags::Poly16:
1287 return shift ? 15 : (4 << IsQuad) - 1;
1288 case NeonTypeFlags::Int32:
1289 return shift ? 31 : (2 << IsQuad) - 1;
1290 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001291 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001292 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001293 case NeonTypeFlags::Poly128:
1294 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001295 case NeonTypeFlags::Float16:
1296 assert(!shift && "cannot shift float types!");
1297 return (4 << IsQuad) - 1;
1298 case NeonTypeFlags::Float32:
1299 assert(!shift && "cannot shift float types!");
1300 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001301 case NeonTypeFlags::Float64:
1302 assert(!shift && "cannot shift float types!");
1303 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001304 }
David Blaikie8a40f702012-01-17 06:56:22 +00001305 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001306}
1307
Bob Wilsone4d77232011-11-08 05:04:11 +00001308/// getNeonEltType - Return the QualType corresponding to the elements of
1309/// the vector type specified by the NeonTypeFlags. This is used to check
1310/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001311static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001312 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001313 switch (Flags.getEltType()) {
1314 case NeonTypeFlags::Int8:
1315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1316 case NeonTypeFlags::Int16:
1317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1318 case NeonTypeFlags::Int32:
1319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1320 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001321 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1323 else
1324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001326 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001328 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001330 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001331 if (IsInt64Long)
1332 return Context.UnsignedLongTy;
1333 else
1334 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001335 case NeonTypeFlags::Poly128:
1336 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001337 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001338 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001339 case NeonTypeFlags::Float32:
1340 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001341 case NeonTypeFlags::Float64:
1342 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001343 }
David Blaikie8a40f702012-01-17 06:56:22 +00001344 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001345}
1346
Tim Northover12670412014-02-19 10:37:05 +00001347bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001348 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001349 uint64_t mask = 0;
1350 unsigned TV = 0;
1351 int PtrArgNum = -1;
1352 bool HasConstPtr = false;
1353 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001354#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001355#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001356#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001357 }
1358
1359 // For NEON intrinsics which are overloaded on vector element type, validate
1360 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001361 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001362 if (mask) {
1363 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1364 return true;
1365
1366 TV = Result.getLimitedValue(64);
1367 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1368 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001369 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001370 }
1371
1372 if (PtrArgNum >= 0) {
1373 // Check that pointer arguments have the specified type.
1374 Expr *Arg = TheCall->getArg(PtrArgNum);
1375 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1376 Arg = ICE->getSubExpr();
1377 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1378 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001379
Tim Northovera2ee4332014-03-29 15:09:45 +00001380 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001381 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001383 bool IsInt64Long =
1384 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1385 QualType EltTy =
1386 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001387 if (HasConstPtr)
1388 EltTy = EltTy.withConst();
1389 QualType LHSTy = Context.getPointerType(EltTy);
1390 AssignConvertType ConvTy;
1391 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1392 if (RHS.isInvalid())
1393 return true;
1394 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1395 RHS.get(), AA_Assigning))
1396 return true;
1397 }
1398
1399 // For NEON intrinsics which take an immediate value as part of the
1400 // instruction, range check them here.
1401 unsigned i = 0, l = 0, u = 0;
1402 switch (BuiltinID) {
1403 default:
1404 return false;
Tim Northover12670412014-02-19 10:37:05 +00001405#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001406#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +00001407#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001408 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001409
Richard Sandiford28940af2014-04-16 08:47:51 +00001410 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001411}
1412
Tim Northovera2ee4332014-03-29 15:09:45 +00001413bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1414 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001415 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001416 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001417 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001418 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001419 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001420 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421 BuiltinID == AArch64::BI__builtin_arm_strex ||
1422 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001423 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001424 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001425 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001428
1429 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1430
1431 // Ensure that we have the proper number of arguments.
1432 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1433 return true;
1434
1435 // Inspect the pointer argument of the atomic builtin. This should always be
1436 // a pointer type, whose element is an integral scalar or pointer type.
1437 // Because it is a pointer type, we don't have to worry about any implicit
1438 // casts here.
1439 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1440 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1441 if (PointerArgRes.isInvalid())
1442 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001443 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001444
1445 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1446 if (!pointerType) {
1447 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1448 << PointerArg->getType() << PointerArg->getSourceRange();
1449 return true;
1450 }
1451
1452 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1453 // task is to insert the appropriate casts into the AST. First work out just
1454 // what the appropriate type is.
1455 QualType ValType = pointerType->getPointeeType();
1456 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1457 if (IsLdrex)
1458 AddrType.addConst();
1459
1460 // Issue a warning if the cast is dodgy.
1461 CastKind CastNeeded = CK_NoOp;
1462 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1463 CastNeeded = CK_BitCast;
1464 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1465 << PointerArg->getType()
1466 << Context.getPointerType(AddrType)
1467 << AA_Passing << PointerArg->getSourceRange();
1468 }
1469
1470 // Finally, do the cast and replace the argument with the corrected version.
1471 AddrType = Context.getPointerType(AddrType);
1472 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1473 if (PointerArgRes.isInvalid())
1474 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001475 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001476
1477 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1478
1479 // In general, we allow ints, floats and pointers to be loaded and stored.
1480 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1481 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1482 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1483 << PointerArg->getType() << PointerArg->getSourceRange();
1484 return true;
1485 }
1486
1487 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001488 if (Context.getTypeSize(ValType) > MaxWidth) {
1489 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001490 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1491 << PointerArg->getType() << PointerArg->getSourceRange();
1492 return true;
1493 }
1494
1495 switch (ValType.getObjCLifetime()) {
1496 case Qualifiers::OCL_None:
1497 case Qualifiers::OCL_ExplicitNone:
1498 // okay
1499 break;
1500
1501 case Qualifiers::OCL_Weak:
1502 case Qualifiers::OCL_Strong:
1503 case Qualifiers::OCL_Autoreleasing:
1504 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1505 << ValType << PointerArg->getSourceRange();
1506 return true;
1507 }
1508
Tim Northover6aacd492013-07-16 09:47:53 +00001509 if (IsLdrex) {
1510 TheCall->setType(ValType);
1511 return false;
1512 }
1513
1514 // Initialize the argument to be stored.
1515 ExprResult ValArg = TheCall->getArg(0);
1516 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1517 Context, ValType, /*consume*/ false);
1518 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1519 if (ValArg.isInvalid())
1520 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001521 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001522
1523 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1524 // but the custom checker bypasses all default analysis.
1525 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001526 return false;
1527}
1528
Nate Begeman4904e322010-06-08 02:47:44 +00001529bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001530 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001531 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532 BuiltinID == ARM::BI__builtin_arm_strex ||
1533 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001534 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001535 }
1536
Yi Kong26d104a2014-08-13 19:18:14 +00001537 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1540 }
1541
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001542 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543 BuiltinID == ARM::BI__builtin_arm_wsr64)
1544 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1545
1546 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548 BuiltinID == ARM::BI__builtin_arm_wsr ||
1549 BuiltinID == ARM::BI__builtin_arm_wsrp)
1550 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1551
Tim Northover12670412014-02-19 10:37:05 +00001552 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1553 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001554
Yi Kong4efadfb2014-07-03 16:01:25 +00001555 // For intrinsics which take an immediate value as part of the instruction,
1556 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001557 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001558 switch (BuiltinID) {
1559 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001560 case ARM::BI__builtin_arm_ssat:
1561 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1562 case ARM::BI__builtin_arm_usat:
1563 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1564 case ARM::BI__builtin_arm_ssat16:
1565 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1566 case ARM::BI__builtin_arm_usat16:
1567 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001568 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001569 case ARM::BI__builtin_arm_vcvtr_d:
1570 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001571 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001572 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001573 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001574 case ARM::BI__builtin_arm_dbg:
1575 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001576 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001577}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001578
Tim Northover573cbee2014-05-24 12:52:07 +00001579bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001580 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001581 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001582 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1583 BuiltinID == AArch64::BI__builtin_arm_strex ||
1584 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001585 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1586 }
1587
Yi Konga5548432014-08-13 19:18:20 +00001588 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1589 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1590 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1591 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1592 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1593 }
1594
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001595 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1596 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001598
1599 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1600 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1601 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1602 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1604
Tim Northovera2ee4332014-03-29 15:09:45 +00001605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1606 return true;
1607
Yi Kong19a29ac2014-07-17 10:52:06 +00001608 // For intrinsics which take an immediate value as part of the instruction,
1609 // range check them here.
1610 unsigned i = 0, l = 0, u = 0;
1611 switch (BuiltinID) {
1612 default: return false;
1613 case AArch64::BI__builtin_arm_dmb:
1614 case AArch64::BI__builtin_arm_dsb:
1615 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1616 }
1617
Yi Kong19a29ac2014-07-17 10:52:06 +00001618 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001619}
1620
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001621// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1622// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1623// ordering for DSP is unspecified. MSA is ordered by the data format used
1624// by the underlying instruction i.e., df/m, df/n and then by size.
1625//
1626// FIXME: The size tests here should instead be tablegen'd along with the
1627// definitions from include/clang/Basic/BuiltinsMips.def.
1628// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1629// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001630bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001631 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001632 switch (BuiltinID) {
1633 default: return false;
1634 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1635 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001636 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1637 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1638 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1639 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1640 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001641 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1642 // df/m field.
1643 // These intrinsics take an unsigned 3 bit immediate.
1644 case Mips::BI__builtin_msa_bclri_b:
1645 case Mips::BI__builtin_msa_bnegi_b:
1646 case Mips::BI__builtin_msa_bseti_b:
1647 case Mips::BI__builtin_msa_sat_s_b:
1648 case Mips::BI__builtin_msa_sat_u_b:
1649 case Mips::BI__builtin_msa_slli_b:
1650 case Mips::BI__builtin_msa_srai_b:
1651 case Mips::BI__builtin_msa_srari_b:
1652 case Mips::BI__builtin_msa_srli_b:
1653 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1654 case Mips::BI__builtin_msa_binsli_b:
1655 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1656 // These intrinsics take an unsigned 4 bit immediate.
1657 case Mips::BI__builtin_msa_bclri_h:
1658 case Mips::BI__builtin_msa_bnegi_h:
1659 case Mips::BI__builtin_msa_bseti_h:
1660 case Mips::BI__builtin_msa_sat_s_h:
1661 case Mips::BI__builtin_msa_sat_u_h:
1662 case Mips::BI__builtin_msa_slli_h:
1663 case Mips::BI__builtin_msa_srai_h:
1664 case Mips::BI__builtin_msa_srari_h:
1665 case Mips::BI__builtin_msa_srli_h:
1666 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1667 case Mips::BI__builtin_msa_binsli_h:
1668 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1669 // These intrinsics take an unsigned 5 bit immedate.
1670 // The first block of intrinsics actually have an unsigned 5 bit field,
1671 // not a df/n field.
1672 case Mips::BI__builtin_msa_clei_u_b:
1673 case Mips::BI__builtin_msa_clei_u_h:
1674 case Mips::BI__builtin_msa_clei_u_w:
1675 case Mips::BI__builtin_msa_clei_u_d:
1676 case Mips::BI__builtin_msa_clti_u_b:
1677 case Mips::BI__builtin_msa_clti_u_h:
1678 case Mips::BI__builtin_msa_clti_u_w:
1679 case Mips::BI__builtin_msa_clti_u_d:
1680 case Mips::BI__builtin_msa_maxi_u_b:
1681 case Mips::BI__builtin_msa_maxi_u_h:
1682 case Mips::BI__builtin_msa_maxi_u_w:
1683 case Mips::BI__builtin_msa_maxi_u_d:
1684 case Mips::BI__builtin_msa_mini_u_b:
1685 case Mips::BI__builtin_msa_mini_u_h:
1686 case Mips::BI__builtin_msa_mini_u_w:
1687 case Mips::BI__builtin_msa_mini_u_d:
1688 case Mips::BI__builtin_msa_addvi_b:
1689 case Mips::BI__builtin_msa_addvi_h:
1690 case Mips::BI__builtin_msa_addvi_w:
1691 case Mips::BI__builtin_msa_addvi_d:
1692 case Mips::BI__builtin_msa_bclri_w:
1693 case Mips::BI__builtin_msa_bnegi_w:
1694 case Mips::BI__builtin_msa_bseti_w:
1695 case Mips::BI__builtin_msa_sat_s_w:
1696 case Mips::BI__builtin_msa_sat_u_w:
1697 case Mips::BI__builtin_msa_slli_w:
1698 case Mips::BI__builtin_msa_srai_w:
1699 case Mips::BI__builtin_msa_srari_w:
1700 case Mips::BI__builtin_msa_srli_w:
1701 case Mips::BI__builtin_msa_srlri_w:
1702 case Mips::BI__builtin_msa_subvi_b:
1703 case Mips::BI__builtin_msa_subvi_h:
1704 case Mips::BI__builtin_msa_subvi_w:
1705 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1706 case Mips::BI__builtin_msa_binsli_w:
1707 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1708 // These intrinsics take an unsigned 6 bit immediate.
1709 case Mips::BI__builtin_msa_bclri_d:
1710 case Mips::BI__builtin_msa_bnegi_d:
1711 case Mips::BI__builtin_msa_bseti_d:
1712 case Mips::BI__builtin_msa_sat_s_d:
1713 case Mips::BI__builtin_msa_sat_u_d:
1714 case Mips::BI__builtin_msa_slli_d:
1715 case Mips::BI__builtin_msa_srai_d:
1716 case Mips::BI__builtin_msa_srari_d:
1717 case Mips::BI__builtin_msa_srli_d:
1718 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1719 case Mips::BI__builtin_msa_binsli_d:
1720 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1721 // These intrinsics take a signed 5 bit immediate.
1722 case Mips::BI__builtin_msa_ceqi_b:
1723 case Mips::BI__builtin_msa_ceqi_h:
1724 case Mips::BI__builtin_msa_ceqi_w:
1725 case Mips::BI__builtin_msa_ceqi_d:
1726 case Mips::BI__builtin_msa_clti_s_b:
1727 case Mips::BI__builtin_msa_clti_s_h:
1728 case Mips::BI__builtin_msa_clti_s_w:
1729 case Mips::BI__builtin_msa_clti_s_d:
1730 case Mips::BI__builtin_msa_clei_s_b:
1731 case Mips::BI__builtin_msa_clei_s_h:
1732 case Mips::BI__builtin_msa_clei_s_w:
1733 case Mips::BI__builtin_msa_clei_s_d:
1734 case Mips::BI__builtin_msa_maxi_s_b:
1735 case Mips::BI__builtin_msa_maxi_s_h:
1736 case Mips::BI__builtin_msa_maxi_s_w:
1737 case Mips::BI__builtin_msa_maxi_s_d:
1738 case Mips::BI__builtin_msa_mini_s_b:
1739 case Mips::BI__builtin_msa_mini_s_h:
1740 case Mips::BI__builtin_msa_mini_s_w:
1741 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1742 // These intrinsics take an unsigned 8 bit immediate.
1743 case Mips::BI__builtin_msa_andi_b:
1744 case Mips::BI__builtin_msa_nori_b:
1745 case Mips::BI__builtin_msa_ori_b:
1746 case Mips::BI__builtin_msa_shf_b:
1747 case Mips::BI__builtin_msa_shf_h:
1748 case Mips::BI__builtin_msa_shf_w:
1749 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1750 case Mips::BI__builtin_msa_bseli_b:
1751 case Mips::BI__builtin_msa_bmnzi_b:
1752 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1753 // df/n format
1754 // These intrinsics take an unsigned 4 bit immediate.
1755 case Mips::BI__builtin_msa_copy_s_b:
1756 case Mips::BI__builtin_msa_copy_u_b:
1757 case Mips::BI__builtin_msa_insve_b:
1758 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001759 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1760 // These intrinsics take an unsigned 3 bit immediate.
1761 case Mips::BI__builtin_msa_copy_s_h:
1762 case Mips::BI__builtin_msa_copy_u_h:
1763 case Mips::BI__builtin_msa_insve_h:
1764 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001765 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1766 // These intrinsics take an unsigned 2 bit immediate.
1767 case Mips::BI__builtin_msa_copy_s_w:
1768 case Mips::BI__builtin_msa_copy_u_w:
1769 case Mips::BI__builtin_msa_insve_w:
1770 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001771 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1772 // These intrinsics take an unsigned 1 bit immediate.
1773 case Mips::BI__builtin_msa_copy_s_d:
1774 case Mips::BI__builtin_msa_copy_u_d:
1775 case Mips::BI__builtin_msa_insve_d:
1776 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001777 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1778 // Memory offsets and immediate loads.
1779 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001780 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001781 case Mips::BI__builtin_msa_ldi_h:
1782 case Mips::BI__builtin_msa_ldi_w:
1783 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1784 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1785 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1786 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1787 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1788 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1789 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1790 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1791 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001792 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001793
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001794 if (!m)
1795 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1796
1797 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1798 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001799}
1800
Kit Bartone50adcb2015-03-30 19:40:59 +00001801bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1802 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001803 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1804 BuiltinID == PPC::BI__builtin_divdeu ||
1805 BuiltinID == PPC::BI__builtin_bpermd;
1806 bool IsTarget64Bit = Context.getTargetInfo()
1807 .getTypeWidth(Context
1808 .getTargetInfo()
1809 .getIntPtrType()) == 64;
1810 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1811 BuiltinID == PPC::BI__builtin_divweu ||
1812 BuiltinID == PPC::BI__builtin_divde ||
1813 BuiltinID == PPC::BI__builtin_divdeu;
1814
1815 if (Is64BitBltin && !IsTarget64Bit)
1816 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1817 << TheCall->getSourceRange();
1818
1819 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1820 (BuiltinID == PPC::BI__builtin_bpermd &&
1821 !Context.getTargetInfo().hasFeature("bpermd")))
1822 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1823 << TheCall->getSourceRange();
1824
Kit Bartone50adcb2015-03-30 19:40:59 +00001825 switch (BuiltinID) {
1826 default: return false;
1827 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1828 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1829 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1830 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1831 case PPC::BI__builtin_tbegin:
1832 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1833 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1834 case PPC::BI__builtin_tabortwc:
1835 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1836 case PPC::BI__builtin_tabortwci:
1837 case PPC::BI__builtin_tabortdci:
1838 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1839 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001840 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001841 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001842 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001843 }
1844 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1845}
1846
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001847bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1848 CallExpr *TheCall) {
1849 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1850 Expr *Arg = TheCall->getArg(0);
1851 llvm::APSInt AbortCode(32);
1852 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1853 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1854 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1855 << Arg->getSourceRange();
1856 }
1857
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001858 // For intrinsics which take an immediate value as part of the instruction,
1859 // range check them here.
1860 unsigned i = 0, l = 0, u = 0;
1861 switch (BuiltinID) {
1862 default: return false;
1863 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1864 case SystemZ::BI__builtin_s390_verimb:
1865 case SystemZ::BI__builtin_s390_verimh:
1866 case SystemZ::BI__builtin_s390_verimf:
1867 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1868 case SystemZ::BI__builtin_s390_vfaeb:
1869 case SystemZ::BI__builtin_s390_vfaeh:
1870 case SystemZ::BI__builtin_s390_vfaef:
1871 case SystemZ::BI__builtin_s390_vfaebs:
1872 case SystemZ::BI__builtin_s390_vfaehs:
1873 case SystemZ::BI__builtin_s390_vfaefs:
1874 case SystemZ::BI__builtin_s390_vfaezb:
1875 case SystemZ::BI__builtin_s390_vfaezh:
1876 case SystemZ::BI__builtin_s390_vfaezf:
1877 case SystemZ::BI__builtin_s390_vfaezbs:
1878 case SystemZ::BI__builtin_s390_vfaezhs:
1879 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001880 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001881 case SystemZ::BI__builtin_s390_vfidb:
1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001884 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001885 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1886 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1887 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1888 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1889 case SystemZ::BI__builtin_s390_vstrcb:
1890 case SystemZ::BI__builtin_s390_vstrch:
1891 case SystemZ::BI__builtin_s390_vstrcf:
1892 case SystemZ::BI__builtin_s390_vstrczb:
1893 case SystemZ::BI__builtin_s390_vstrczh:
1894 case SystemZ::BI__builtin_s390_vstrczf:
1895 case SystemZ::BI__builtin_s390_vstrcbs:
1896 case SystemZ::BI__builtin_s390_vstrchs:
1897 case SystemZ::BI__builtin_s390_vstrcfs:
1898 case SystemZ::BI__builtin_s390_vstrczbs:
1899 case SystemZ::BI__builtin_s390_vstrczhs:
1900 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001901 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1902 case SystemZ::BI__builtin_s390_vfminsb:
1903 case SystemZ::BI__builtin_s390_vfmaxsb:
1904 case SystemZ::BI__builtin_s390_vfmindb:
1905 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001906 }
1907 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001908}
1909
Craig Topper5ba2c502015-11-07 08:08:31 +00001910/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1911/// This checks that the target supports __builtin_cpu_supports and
1912/// that the string argument is constant and valid.
1913static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1914 Expr *Arg = TheCall->getArg(0);
1915
1916 // Check if the argument is a string literal.
1917 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1918 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1919 << Arg->getSourceRange();
1920
1921 // Check the contents of the string.
1922 StringRef Feature =
1923 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1924 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1925 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1926 << Arg->getSourceRange();
1927 return false;
1928}
1929
Craig Topper699ae0c2017-08-10 20:28:30 +00001930/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1931/// This checks that the target supports __builtin_cpu_is and
1932/// that the string argument is constant and valid.
1933static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1934 Expr *Arg = TheCall->getArg(0);
1935
1936 // Check if the argument is a string literal.
1937 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1938 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1939 << Arg->getSourceRange();
1940
1941 // Check the contents of the string.
1942 StringRef Feature =
1943 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1944 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1945 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1946 << Arg->getSourceRange();
1947 return false;
1948}
1949
Craig Toppera7e253e2016-09-23 04:48:31 +00001950// Check if the rounding mode is legal.
1951bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1952 // Indicates if this instruction has rounding control or just SAE.
1953 bool HasRC = false;
1954
1955 unsigned ArgNum = 0;
1956 switch (BuiltinID) {
1957 default:
1958 return false;
1959 case X86::BI__builtin_ia32_vcvttsd2si32:
1960 case X86::BI__builtin_ia32_vcvttsd2si64:
1961 case X86::BI__builtin_ia32_vcvttsd2usi32:
1962 case X86::BI__builtin_ia32_vcvttsd2usi64:
1963 case X86::BI__builtin_ia32_vcvttss2si32:
1964 case X86::BI__builtin_ia32_vcvttss2si64:
1965 case X86::BI__builtin_ia32_vcvttss2usi32:
1966 case X86::BI__builtin_ia32_vcvttss2usi64:
1967 ArgNum = 1;
1968 break;
1969 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1970 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1971 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1972 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1973 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1974 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1975 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1976 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1977 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1978 case X86::BI__builtin_ia32_exp2pd_mask:
1979 case X86::BI__builtin_ia32_exp2ps_mask:
1980 case X86::BI__builtin_ia32_getexppd512_mask:
1981 case X86::BI__builtin_ia32_getexpps512_mask:
1982 case X86::BI__builtin_ia32_rcp28pd_mask:
1983 case X86::BI__builtin_ia32_rcp28ps_mask:
1984 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1985 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1986 case X86::BI__builtin_ia32_vcomisd:
1987 case X86::BI__builtin_ia32_vcomiss:
1988 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1989 ArgNum = 3;
1990 break;
1991 case X86::BI__builtin_ia32_cmppd512_mask:
1992 case X86::BI__builtin_ia32_cmpps512_mask:
1993 case X86::BI__builtin_ia32_cmpsd_mask:
1994 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001995 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00001996 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1997 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00001998 case X86::BI__builtin_ia32_maxpd512_mask:
1999 case X86::BI__builtin_ia32_maxps512_mask:
2000 case X86::BI__builtin_ia32_maxsd_round_mask:
2001 case X86::BI__builtin_ia32_maxss_round_mask:
2002 case X86::BI__builtin_ia32_minpd512_mask:
2003 case X86::BI__builtin_ia32_minps512_mask:
2004 case X86::BI__builtin_ia32_minsd_round_mask:
2005 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002006 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2007 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2008 case X86::BI__builtin_ia32_reducepd512_mask:
2009 case X86::BI__builtin_ia32_reduceps512_mask:
2010 case X86::BI__builtin_ia32_rndscalepd_mask:
2011 case X86::BI__builtin_ia32_rndscaleps_mask:
2012 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2013 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2014 ArgNum = 4;
2015 break;
2016 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002017 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002018 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002019 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002020 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002021 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002022 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002023 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002024 case X86::BI__builtin_ia32_rangepd512_mask:
2025 case X86::BI__builtin_ia32_rangeps512_mask:
2026 case X86::BI__builtin_ia32_rangesd128_round_mask:
2027 case X86::BI__builtin_ia32_rangess128_round_mask:
2028 case X86::BI__builtin_ia32_reducesd_mask:
2029 case X86::BI__builtin_ia32_reducess_mask:
2030 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2031 case X86::BI__builtin_ia32_rndscaless_round_mask:
2032 ArgNum = 5;
2033 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002034 case X86::BI__builtin_ia32_vcvtsd2si64:
2035 case X86::BI__builtin_ia32_vcvtsd2si32:
2036 case X86::BI__builtin_ia32_vcvtsd2usi32:
2037 case X86::BI__builtin_ia32_vcvtsd2usi64:
2038 case X86::BI__builtin_ia32_vcvtss2si32:
2039 case X86::BI__builtin_ia32_vcvtss2si64:
2040 case X86::BI__builtin_ia32_vcvtss2usi32:
2041 case X86::BI__builtin_ia32_vcvtss2usi64:
2042 ArgNum = 1;
2043 HasRC = true;
2044 break;
Craig Topper8e066312016-11-07 07:01:09 +00002045 case X86::BI__builtin_ia32_cvtsi2sd64:
2046 case X86::BI__builtin_ia32_cvtsi2ss32:
2047 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002048 case X86::BI__builtin_ia32_cvtusi2sd64:
2049 case X86::BI__builtin_ia32_cvtusi2ss32:
2050 case X86::BI__builtin_ia32_cvtusi2ss64:
2051 ArgNum = 2;
2052 HasRC = true;
2053 break;
2054 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2055 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2056 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2057 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2058 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2059 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2060 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2061 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2062 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2063 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2064 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002065 case X86::BI__builtin_ia32_sqrtpd512_mask:
2066 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002067 ArgNum = 3;
2068 HasRC = true;
2069 break;
2070 case X86::BI__builtin_ia32_addpd512_mask:
2071 case X86::BI__builtin_ia32_addps512_mask:
2072 case X86::BI__builtin_ia32_divpd512_mask:
2073 case X86::BI__builtin_ia32_divps512_mask:
2074 case X86::BI__builtin_ia32_mulpd512_mask:
2075 case X86::BI__builtin_ia32_mulps512_mask:
2076 case X86::BI__builtin_ia32_subpd512_mask:
2077 case X86::BI__builtin_ia32_subps512_mask:
2078 case X86::BI__builtin_ia32_addss_round_mask:
2079 case X86::BI__builtin_ia32_addsd_round_mask:
2080 case X86::BI__builtin_ia32_divss_round_mask:
2081 case X86::BI__builtin_ia32_divsd_round_mask:
2082 case X86::BI__builtin_ia32_mulss_round_mask:
2083 case X86::BI__builtin_ia32_mulsd_round_mask:
2084 case X86::BI__builtin_ia32_subss_round_mask:
2085 case X86::BI__builtin_ia32_subsd_round_mask:
2086 case X86::BI__builtin_ia32_scalefpd512_mask:
2087 case X86::BI__builtin_ia32_scalefps512_mask:
2088 case X86::BI__builtin_ia32_scalefsd_round_mask:
2089 case X86::BI__builtin_ia32_scalefss_round_mask:
2090 case X86::BI__builtin_ia32_getmantpd512_mask:
2091 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002092 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2093 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2094 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002095 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2096 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2097 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2098 case X86::BI__builtin_ia32_vfmaddps512_mask:
2099 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2100 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2101 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2102 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2103 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2104 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2105 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2106 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2107 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2108 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2109 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2110 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2111 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2112 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2113 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2114 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2115 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2116 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2117 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2118 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2119 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2120 case X86::BI__builtin_ia32_vfmaddss3_mask:
2121 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2122 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2123 ArgNum = 4;
2124 HasRC = true;
2125 break;
2126 case X86::BI__builtin_ia32_getmantsd_round_mask:
2127 case X86::BI__builtin_ia32_getmantss_round_mask:
2128 ArgNum = 5;
2129 HasRC = true;
2130 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002131 }
2132
2133 llvm::APSInt Result;
2134
2135 // We can't check the value of a dependent argument.
2136 Expr *Arg = TheCall->getArg(ArgNum);
2137 if (Arg->isTypeDependent() || Arg->isValueDependent())
2138 return false;
2139
2140 // Check constant-ness first.
2141 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2142 return true;
2143
2144 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2145 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2146 // combined with ROUND_NO_EXC.
2147 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2148 Result == 8/*ROUND_NO_EXC*/ ||
2149 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2150 return false;
2151
2152 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2153 << Arg->getSourceRange();
2154}
2155
Craig Topperdf5beb22017-03-13 17:16:50 +00002156// Check if the gather/scatter scale is legal.
2157bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2158 CallExpr *TheCall) {
2159 unsigned ArgNum = 0;
2160 switch (BuiltinID) {
2161 default:
2162 return false;
2163 case X86::BI__builtin_ia32_gatherpfdpd:
2164 case X86::BI__builtin_ia32_gatherpfdps:
2165 case X86::BI__builtin_ia32_gatherpfqpd:
2166 case X86::BI__builtin_ia32_gatherpfqps:
2167 case X86::BI__builtin_ia32_scatterpfdpd:
2168 case X86::BI__builtin_ia32_scatterpfdps:
2169 case X86::BI__builtin_ia32_scatterpfqpd:
2170 case X86::BI__builtin_ia32_scatterpfqps:
2171 ArgNum = 3;
2172 break;
2173 case X86::BI__builtin_ia32_gatherd_pd:
2174 case X86::BI__builtin_ia32_gatherd_pd256:
2175 case X86::BI__builtin_ia32_gatherq_pd:
2176 case X86::BI__builtin_ia32_gatherq_pd256:
2177 case X86::BI__builtin_ia32_gatherd_ps:
2178 case X86::BI__builtin_ia32_gatherd_ps256:
2179 case X86::BI__builtin_ia32_gatherq_ps:
2180 case X86::BI__builtin_ia32_gatherq_ps256:
2181 case X86::BI__builtin_ia32_gatherd_q:
2182 case X86::BI__builtin_ia32_gatherd_q256:
2183 case X86::BI__builtin_ia32_gatherq_q:
2184 case X86::BI__builtin_ia32_gatherq_q256:
2185 case X86::BI__builtin_ia32_gatherd_d:
2186 case X86::BI__builtin_ia32_gatherd_d256:
2187 case X86::BI__builtin_ia32_gatherq_d:
2188 case X86::BI__builtin_ia32_gatherq_d256:
2189 case X86::BI__builtin_ia32_gather3div2df:
2190 case X86::BI__builtin_ia32_gather3div2di:
2191 case X86::BI__builtin_ia32_gather3div4df:
2192 case X86::BI__builtin_ia32_gather3div4di:
2193 case X86::BI__builtin_ia32_gather3div4sf:
2194 case X86::BI__builtin_ia32_gather3div4si:
2195 case X86::BI__builtin_ia32_gather3div8sf:
2196 case X86::BI__builtin_ia32_gather3div8si:
2197 case X86::BI__builtin_ia32_gather3siv2df:
2198 case X86::BI__builtin_ia32_gather3siv2di:
2199 case X86::BI__builtin_ia32_gather3siv4df:
2200 case X86::BI__builtin_ia32_gather3siv4di:
2201 case X86::BI__builtin_ia32_gather3siv4sf:
2202 case X86::BI__builtin_ia32_gather3siv4si:
2203 case X86::BI__builtin_ia32_gather3siv8sf:
2204 case X86::BI__builtin_ia32_gather3siv8si:
2205 case X86::BI__builtin_ia32_gathersiv8df:
2206 case X86::BI__builtin_ia32_gathersiv16sf:
2207 case X86::BI__builtin_ia32_gatherdiv8df:
2208 case X86::BI__builtin_ia32_gatherdiv16sf:
2209 case X86::BI__builtin_ia32_gathersiv8di:
2210 case X86::BI__builtin_ia32_gathersiv16si:
2211 case X86::BI__builtin_ia32_gatherdiv8di:
2212 case X86::BI__builtin_ia32_gatherdiv16si:
2213 case X86::BI__builtin_ia32_scatterdiv2df:
2214 case X86::BI__builtin_ia32_scatterdiv2di:
2215 case X86::BI__builtin_ia32_scatterdiv4df:
2216 case X86::BI__builtin_ia32_scatterdiv4di:
2217 case X86::BI__builtin_ia32_scatterdiv4sf:
2218 case X86::BI__builtin_ia32_scatterdiv4si:
2219 case X86::BI__builtin_ia32_scatterdiv8sf:
2220 case X86::BI__builtin_ia32_scatterdiv8si:
2221 case X86::BI__builtin_ia32_scattersiv2df:
2222 case X86::BI__builtin_ia32_scattersiv2di:
2223 case X86::BI__builtin_ia32_scattersiv4df:
2224 case X86::BI__builtin_ia32_scattersiv4di:
2225 case X86::BI__builtin_ia32_scattersiv4sf:
2226 case X86::BI__builtin_ia32_scattersiv4si:
2227 case X86::BI__builtin_ia32_scattersiv8sf:
2228 case X86::BI__builtin_ia32_scattersiv8si:
2229 case X86::BI__builtin_ia32_scattersiv8df:
2230 case X86::BI__builtin_ia32_scattersiv16sf:
2231 case X86::BI__builtin_ia32_scatterdiv8df:
2232 case X86::BI__builtin_ia32_scatterdiv16sf:
2233 case X86::BI__builtin_ia32_scattersiv8di:
2234 case X86::BI__builtin_ia32_scattersiv16si:
2235 case X86::BI__builtin_ia32_scatterdiv8di:
2236 case X86::BI__builtin_ia32_scatterdiv16si:
2237 ArgNum = 4;
2238 break;
2239 }
2240
2241 llvm::APSInt Result;
2242
2243 // We can't check the value of a dependent argument.
2244 Expr *Arg = TheCall->getArg(ArgNum);
2245 if (Arg->isTypeDependent() || Arg->isValueDependent())
2246 return false;
2247
2248 // Check constant-ness first.
2249 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2250 return true;
2251
2252 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2253 return false;
2254
2255 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2256 << Arg->getSourceRange();
2257}
2258
Craig Topperf0ddc892016-09-23 04:48:27 +00002259bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2260 if (BuiltinID == X86::BI__builtin_cpu_supports)
2261 return SemaBuiltinCpuSupports(*this, TheCall);
2262
Craig Topper699ae0c2017-08-10 20:28:30 +00002263 if (BuiltinID == X86::BI__builtin_cpu_is)
2264 return SemaBuiltinCpuIs(*this, TheCall);
2265
Craig Toppera7e253e2016-09-23 04:48:31 +00002266 // If the intrinsic has rounding or SAE make sure its valid.
2267 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2268 return true;
2269
Craig Topperdf5beb22017-03-13 17:16:50 +00002270 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2271 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2272 return true;
2273
Craig Topperf0ddc892016-09-23 04:48:27 +00002274 // For intrinsics which take an immediate value as part of the instruction,
2275 // range check them here.
2276 int i = 0, l = 0, u = 0;
2277 switch (BuiltinID) {
2278 default:
2279 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002280 case X86::BI_mm_prefetch:
Craig Topper39c87102016-05-18 03:18:12 +00002281 i = 1; l = 0; u = 3;
2282 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002283 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002284 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2285 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2286 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2287 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002288 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002289 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002290 case X86::BI__builtin_ia32_vpermil2pd:
2291 case X86::BI__builtin_ia32_vpermil2pd256:
2292 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002293 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002294 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002295 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002296 case X86::BI__builtin_ia32_cmpb128_mask:
2297 case X86::BI__builtin_ia32_cmpw128_mask:
2298 case X86::BI__builtin_ia32_cmpd128_mask:
2299 case X86::BI__builtin_ia32_cmpq128_mask:
2300 case X86::BI__builtin_ia32_cmpb256_mask:
2301 case X86::BI__builtin_ia32_cmpw256_mask:
2302 case X86::BI__builtin_ia32_cmpd256_mask:
2303 case X86::BI__builtin_ia32_cmpq256_mask:
2304 case X86::BI__builtin_ia32_cmpb512_mask:
2305 case X86::BI__builtin_ia32_cmpw512_mask:
2306 case X86::BI__builtin_ia32_cmpd512_mask:
2307 case X86::BI__builtin_ia32_cmpq512_mask:
2308 case X86::BI__builtin_ia32_ucmpb128_mask:
2309 case X86::BI__builtin_ia32_ucmpw128_mask:
2310 case X86::BI__builtin_ia32_ucmpd128_mask:
2311 case X86::BI__builtin_ia32_ucmpq128_mask:
2312 case X86::BI__builtin_ia32_ucmpb256_mask:
2313 case X86::BI__builtin_ia32_ucmpw256_mask:
2314 case X86::BI__builtin_ia32_ucmpd256_mask:
2315 case X86::BI__builtin_ia32_ucmpq256_mask:
2316 case X86::BI__builtin_ia32_ucmpb512_mask:
2317 case X86::BI__builtin_ia32_ucmpw512_mask:
2318 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002319 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002320 case X86::BI__builtin_ia32_vpcomub:
2321 case X86::BI__builtin_ia32_vpcomuw:
2322 case X86::BI__builtin_ia32_vpcomud:
2323 case X86::BI__builtin_ia32_vpcomuq:
2324 case X86::BI__builtin_ia32_vpcomb:
2325 case X86::BI__builtin_ia32_vpcomw:
2326 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002327 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002328 i = 2; l = 0; u = 7;
2329 break;
2330 case X86::BI__builtin_ia32_roundps:
2331 case X86::BI__builtin_ia32_roundpd:
2332 case X86::BI__builtin_ia32_roundps256:
2333 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002334 i = 1; l = 0; u = 15;
2335 break;
2336 case X86::BI__builtin_ia32_roundss:
2337 case X86::BI__builtin_ia32_roundsd:
2338 case X86::BI__builtin_ia32_rangepd128_mask:
2339 case X86::BI__builtin_ia32_rangepd256_mask:
2340 case X86::BI__builtin_ia32_rangepd512_mask:
2341 case X86::BI__builtin_ia32_rangeps128_mask:
2342 case X86::BI__builtin_ia32_rangeps256_mask:
2343 case X86::BI__builtin_ia32_rangeps512_mask:
2344 case X86::BI__builtin_ia32_getmantsd_round_mask:
2345 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002346 i = 2; l = 0; u = 15;
2347 break;
2348 case X86::BI__builtin_ia32_cmpps:
2349 case X86::BI__builtin_ia32_cmpss:
2350 case X86::BI__builtin_ia32_cmppd:
2351 case X86::BI__builtin_ia32_cmpsd:
2352 case X86::BI__builtin_ia32_cmpps256:
2353 case X86::BI__builtin_ia32_cmppd256:
2354 case X86::BI__builtin_ia32_cmpps128_mask:
2355 case X86::BI__builtin_ia32_cmppd128_mask:
2356 case X86::BI__builtin_ia32_cmpps256_mask:
2357 case X86::BI__builtin_ia32_cmppd256_mask:
2358 case X86::BI__builtin_ia32_cmpps512_mask:
2359 case X86::BI__builtin_ia32_cmppd512_mask:
2360 case X86::BI__builtin_ia32_cmpsd_mask:
2361 case X86::BI__builtin_ia32_cmpss_mask:
2362 i = 2; l = 0; u = 31;
2363 break;
2364 case X86::BI__builtin_ia32_xabort:
2365 i = 0; l = -128; u = 255;
2366 break;
2367 case X86::BI__builtin_ia32_pshufw:
2368 case X86::BI__builtin_ia32_aeskeygenassist128:
2369 i = 1; l = -128; u = 255;
2370 break;
2371 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002372 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002373 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002374 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2375 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002376 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2377 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2378 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2379 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2380 case X86::BI__builtin_ia32_rndscaleps_mask:
2381 case X86::BI__builtin_ia32_rndscalepd_mask:
2382 case X86::BI__builtin_ia32_reducepd128_mask:
2383 case X86::BI__builtin_ia32_reducepd256_mask:
2384 case X86::BI__builtin_ia32_reducepd512_mask:
2385 case X86::BI__builtin_ia32_reduceps128_mask:
2386 case X86::BI__builtin_ia32_reduceps256_mask:
2387 case X86::BI__builtin_ia32_reduceps512_mask:
2388 case X86::BI__builtin_ia32_prold512_mask:
2389 case X86::BI__builtin_ia32_prolq512_mask:
2390 case X86::BI__builtin_ia32_prold128_mask:
2391 case X86::BI__builtin_ia32_prold256_mask:
2392 case X86::BI__builtin_ia32_prolq128_mask:
2393 case X86::BI__builtin_ia32_prolq256_mask:
2394 case X86::BI__builtin_ia32_prord128_mask:
2395 case X86::BI__builtin_ia32_prord256_mask:
2396 case X86::BI__builtin_ia32_prorq128_mask:
2397 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002398 case X86::BI__builtin_ia32_fpclasspd128_mask:
2399 case X86::BI__builtin_ia32_fpclasspd256_mask:
2400 case X86::BI__builtin_ia32_fpclassps128_mask:
2401 case X86::BI__builtin_ia32_fpclassps256_mask:
2402 case X86::BI__builtin_ia32_fpclassps512_mask:
2403 case X86::BI__builtin_ia32_fpclasspd512_mask:
2404 case X86::BI__builtin_ia32_fpclasssd_mask:
2405 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002406 i = 1; l = 0; u = 255;
2407 break;
2408 case X86::BI__builtin_ia32_palignr:
2409 case X86::BI__builtin_ia32_insertps128:
2410 case X86::BI__builtin_ia32_dpps:
2411 case X86::BI__builtin_ia32_dppd:
2412 case X86::BI__builtin_ia32_dpps256:
2413 case X86::BI__builtin_ia32_mpsadbw128:
2414 case X86::BI__builtin_ia32_mpsadbw256:
2415 case X86::BI__builtin_ia32_pcmpistrm128:
2416 case X86::BI__builtin_ia32_pcmpistri128:
2417 case X86::BI__builtin_ia32_pcmpistria128:
2418 case X86::BI__builtin_ia32_pcmpistric128:
2419 case X86::BI__builtin_ia32_pcmpistrio128:
2420 case X86::BI__builtin_ia32_pcmpistris128:
2421 case X86::BI__builtin_ia32_pcmpistriz128:
2422 case X86::BI__builtin_ia32_pclmulqdq128:
2423 case X86::BI__builtin_ia32_vperm2f128_pd256:
2424 case X86::BI__builtin_ia32_vperm2f128_ps256:
2425 case X86::BI__builtin_ia32_vperm2f128_si256:
2426 case X86::BI__builtin_ia32_permti256:
2427 i = 2; l = -128; u = 255;
2428 break;
2429 case X86::BI__builtin_ia32_palignr128:
2430 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002431 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002432 case X86::BI__builtin_ia32_vcomisd:
2433 case X86::BI__builtin_ia32_vcomiss:
2434 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2435 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2436 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2437 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002438 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2439 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2440 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2441 i = 2; l = 0; u = 255;
2442 break;
2443 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2444 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2445 case X86::BI__builtin_ia32_fixupimmps512_mask:
2446 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2447 case X86::BI__builtin_ia32_fixupimmsd_mask:
2448 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2449 case X86::BI__builtin_ia32_fixupimmss_mask:
2450 case X86::BI__builtin_ia32_fixupimmss_maskz:
2451 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2452 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2453 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2454 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2455 case X86::BI__builtin_ia32_fixupimmps128_mask:
2456 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2457 case X86::BI__builtin_ia32_fixupimmps256_mask:
2458 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2459 case X86::BI__builtin_ia32_pternlogd512_mask:
2460 case X86::BI__builtin_ia32_pternlogd512_maskz:
2461 case X86::BI__builtin_ia32_pternlogq512_mask:
2462 case X86::BI__builtin_ia32_pternlogq512_maskz:
2463 case X86::BI__builtin_ia32_pternlogd128_mask:
2464 case X86::BI__builtin_ia32_pternlogd128_maskz:
2465 case X86::BI__builtin_ia32_pternlogd256_mask:
2466 case X86::BI__builtin_ia32_pternlogd256_maskz:
2467 case X86::BI__builtin_ia32_pternlogq128_mask:
2468 case X86::BI__builtin_ia32_pternlogq128_maskz:
2469 case X86::BI__builtin_ia32_pternlogq256_mask:
2470 case X86::BI__builtin_ia32_pternlogq256_maskz:
2471 i = 3; l = 0; u = 255;
2472 break;
Craig Topper9625db02017-03-12 22:19:10 +00002473 case X86::BI__builtin_ia32_gatherpfdpd:
2474 case X86::BI__builtin_ia32_gatherpfdps:
2475 case X86::BI__builtin_ia32_gatherpfqpd:
2476 case X86::BI__builtin_ia32_gatherpfqps:
2477 case X86::BI__builtin_ia32_scatterpfdpd:
2478 case X86::BI__builtin_ia32_scatterpfdps:
2479 case X86::BI__builtin_ia32_scatterpfqpd:
2480 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002481 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002482 break;
Craig Topper39c87102016-05-18 03:18:12 +00002483 case X86::BI__builtin_ia32_pcmpestrm128:
2484 case X86::BI__builtin_ia32_pcmpestri128:
2485 case X86::BI__builtin_ia32_pcmpestria128:
2486 case X86::BI__builtin_ia32_pcmpestric128:
2487 case X86::BI__builtin_ia32_pcmpestrio128:
2488 case X86::BI__builtin_ia32_pcmpestris128:
2489 case X86::BI__builtin_ia32_pcmpestriz128:
2490 i = 4; l = -128; u = 255;
2491 break;
2492 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2493 case X86::BI__builtin_ia32_rndscaless_round_mask:
2494 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002495 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002496 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002497 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002498}
2499
Richard Smith55ce3522012-06-25 20:30:08 +00002500/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2501/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2502/// Returns true when the format fits the function and the FormatStringInfo has
2503/// been populated.
2504bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2505 FormatStringInfo *FSI) {
2506 FSI->HasVAListArg = Format->getFirstArg() == 0;
2507 FSI->FormatIdx = Format->getFormatIdx() - 1;
2508 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002509
Richard Smith55ce3522012-06-25 20:30:08 +00002510 // The way the format attribute works in GCC, the implicit this argument
2511 // of member functions is counted. However, it doesn't appear in our own
2512 // lists, so decrement format_idx in that case.
2513 if (IsCXXMember) {
2514 if(FSI->FormatIdx == 0)
2515 return false;
2516 --FSI->FormatIdx;
2517 if (FSI->FirstDataArg != 0)
2518 --FSI->FirstDataArg;
2519 }
2520 return true;
2521}
Mike Stump11289f42009-09-09 15:08:12 +00002522
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002523/// Checks if a the given expression evaluates to null.
2524///
2525/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002526static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002527 // If the expression has non-null type, it doesn't evaluate to null.
2528 if (auto nullability
2529 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2530 if (*nullability == NullabilityKind::NonNull)
2531 return false;
2532 }
2533
Ted Kremeneka146db32014-01-17 06:24:47 +00002534 // As a special case, transparent unions initialized with zero are
2535 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002536 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002537 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2538 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002539 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002540 if (const InitListExpr *ILE =
2541 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002542 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002543 }
2544
2545 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002546 return (!Expr->isValueDependent() &&
2547 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2548 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002549}
2550
2551static void CheckNonNullArgument(Sema &S,
2552 const Expr *ArgExpr,
2553 SourceLocation CallSiteLoc) {
2554 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002555 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2556 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002557}
2558
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002559bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2560 FormatStringInfo FSI;
2561 if ((GetFormatStringType(Format) == FST_NSString) &&
2562 getFormatStringInfo(Format, false, &FSI)) {
2563 Idx = FSI.FormatIdx;
2564 return true;
2565 }
2566 return false;
2567}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002568
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002569/// \brief Diagnose use of %s directive in an NSString which is being passed
2570/// as formatting string to formatting method.
2571static void
2572DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2573 const NamedDecl *FDecl,
2574 Expr **Args,
2575 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002576 unsigned Idx = 0;
2577 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002578 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2579 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002580 Idx = 2;
2581 Format = true;
2582 }
2583 else
2584 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2585 if (S.GetFormatNSStringIdx(I, Idx)) {
2586 Format = true;
2587 break;
2588 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002589 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002590 if (!Format || NumArgs <= Idx)
2591 return;
2592 const Expr *FormatExpr = Args[Idx];
2593 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2594 FormatExpr = CSCE->getSubExpr();
2595 const StringLiteral *FormatString;
2596 if (const ObjCStringLiteral *OSL =
2597 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2598 FormatString = OSL->getString();
2599 else
2600 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2601 if (!FormatString)
2602 return;
2603 if (S.FormatStringHasSArg(FormatString)) {
2604 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2605 << "%s" << 1 << 1;
2606 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2607 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002608 }
2609}
2610
Douglas Gregorb4866e82015-06-19 18:13:19 +00002611/// Determine whether the given type has a non-null nullability annotation.
2612static bool isNonNullType(ASTContext &ctx, QualType type) {
2613 if (auto nullability = type->getNullability(ctx))
2614 return *nullability == NullabilityKind::NonNull;
2615
2616 return false;
2617}
2618
Ted Kremenek2bc73332014-01-17 06:24:43 +00002619static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002620 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002621 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002622 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002623 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002624 assert((FDecl || Proto) && "Need a function declaration or prototype");
2625
Ted Kremenek9aedc152014-01-17 06:24:56 +00002626 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002627 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002628 if (FDecl) {
2629 // Handle the nonnull attribute on the function/method declaration itself.
2630 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2631 if (!NonNull->args_size()) {
2632 // Easy case: all pointer arguments are nonnull.
2633 for (const auto *Arg : Args)
2634 if (S.isValidPointerAttrType(Arg->getType()))
2635 CheckNonNullArgument(S, Arg, CallSiteLoc);
2636 return;
2637 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002638
Douglas Gregorb4866e82015-06-19 18:13:19 +00002639 for (unsigned Val : NonNull->args()) {
2640 if (Val >= Args.size())
2641 continue;
2642 if (NonNullArgs.empty())
2643 NonNullArgs.resize(Args.size());
2644 NonNullArgs.set(Val);
2645 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002646 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002647 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002648
Douglas Gregorb4866e82015-06-19 18:13:19 +00002649 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2650 // Handle the nonnull attribute on the parameters of the
2651 // function/method.
2652 ArrayRef<ParmVarDecl*> parms;
2653 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2654 parms = FD->parameters();
2655 else
2656 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2657
2658 unsigned ParamIndex = 0;
2659 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2660 I != E; ++I, ++ParamIndex) {
2661 const ParmVarDecl *PVD = *I;
2662 if (PVD->hasAttr<NonNullAttr>() ||
2663 isNonNullType(S.Context, PVD->getType())) {
2664 if (NonNullArgs.empty())
2665 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002666
Douglas Gregorb4866e82015-06-19 18:13:19 +00002667 NonNullArgs.set(ParamIndex);
2668 }
2669 }
2670 } else {
2671 // If we have a non-function, non-method declaration but no
2672 // function prototype, try to dig out the function prototype.
2673 if (!Proto) {
2674 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2675 QualType type = VD->getType().getNonReferenceType();
2676 if (auto pointerType = type->getAs<PointerType>())
2677 type = pointerType->getPointeeType();
2678 else if (auto blockType = type->getAs<BlockPointerType>())
2679 type = blockType->getPointeeType();
2680 // FIXME: data member pointers?
2681
2682 // Dig out the function prototype, if there is one.
2683 Proto = type->getAs<FunctionProtoType>();
2684 }
2685 }
2686
2687 // Fill in non-null argument information from the nullability
2688 // information on the parameter types (if we have them).
2689 if (Proto) {
2690 unsigned Index = 0;
2691 for (auto paramType : Proto->getParamTypes()) {
2692 if (isNonNullType(S.Context, paramType)) {
2693 if (NonNullArgs.empty())
2694 NonNullArgs.resize(Args.size());
2695
2696 NonNullArgs.set(Index);
2697 }
2698
2699 ++Index;
2700 }
2701 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002702 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002703
Douglas Gregorb4866e82015-06-19 18:13:19 +00002704 // Check for non-null arguments.
2705 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2706 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002707 if (NonNullArgs[ArgIndex])
2708 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002709 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002710}
2711
Richard Smith55ce3522012-06-25 20:30:08 +00002712/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002713/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2714/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002715void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002716 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2717 bool IsMemberFunction, SourceLocation Loc,
2718 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002719 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002720 if (CurContext->isDependentContext())
2721 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002722
Ted Kremenekb8176da2010-09-09 04:33:05 +00002723 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002724 llvm::SmallBitVector CheckedVarArgs;
2725 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002726 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002727 // Only create vector if there are format attributes.
2728 CheckedVarArgs.resize(Args.size());
2729
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002730 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002731 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002732 }
Richard Smithd7293d72013-08-05 18:49:43 +00002733 }
Richard Smith55ce3522012-06-25 20:30:08 +00002734
2735 // Refuse POD arguments that weren't caught by the format string
2736 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002737 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2738 if (CallType != VariadicDoesNotApply &&
2739 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002740 unsigned NumParams = Proto ? Proto->getNumParams()
2741 : FDecl && isa<FunctionDecl>(FDecl)
2742 ? cast<FunctionDecl>(FDecl)->getNumParams()
2743 : FDecl && isa<ObjCMethodDecl>(FDecl)
2744 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2745 : 0;
2746
Alp Toker9cacbab2014-01-20 20:26:09 +00002747 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002748 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002749 if (const Expr *Arg = Args[ArgIdx]) {
2750 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2751 checkVariadicArgument(Arg, CallType);
2752 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002753 }
Richard Smithd7293d72013-08-05 18:49:43 +00002754 }
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregorb4866e82015-06-19 18:13:19 +00002756 if (FDecl || Proto) {
2757 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002758
Richard Trieu41bc0992013-06-22 00:20:41 +00002759 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002760 if (FDecl) {
2761 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00002762 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002763 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002764 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002765
2766 if (FD)
2767 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002768}
2769
2770/// CheckConstructorCall - Check a constructor call for correctness and safety
2771/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002772void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2773 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002774 const FunctionProtoType *Proto,
2775 SourceLocation Loc) {
2776 VariadicCallType CallType =
2777 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002778 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2779 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002780}
2781
2782/// CheckFunctionCall - Check a direct function call for various correctness
2783/// and safety properties not strictly enforced by the C type system.
2784bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2785 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002786 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2787 isa<CXXMethodDecl>(FDecl);
2788 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2789 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002790 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2791 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002792 Expr** Args = TheCall->getArgs();
2793 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002794
2795 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002796 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002797 // If this is a call to a member operator, hide the first argument
2798 // from checkCall.
2799 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002800 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002801 ++Args;
2802 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002803 } else if (IsMemberFunction)
2804 ImplicitThis =
2805 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2806
2807 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002808 IsMemberFunction, TheCall->getRParenLoc(),
2809 TheCall->getCallee()->getSourceRange(), CallType);
2810
2811 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2812 // None of the checks below are needed for functions that don't have
2813 // simple names (e.g., C++ conversion functions).
2814 if (!FnInfo)
2815 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002816
Richard Trieua7f30b12016-12-06 01:42:28 +00002817 CheckAbsoluteValueFunction(TheCall, FDecl);
2818 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002819
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002820 if (getLangOpts().ObjC1)
2821 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002822
Anna Zaks22122702012-01-17 00:37:07 +00002823 unsigned CMId = FDecl->getMemoryFunctionKind();
2824 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002825 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002826
Anna Zaks201d4892012-01-13 21:52:01 +00002827 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002828 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002829 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002830 else if (CMId == Builtin::BIstrncat)
2831 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002832 else
Anna Zaks22122702012-01-17 00:37:07 +00002833 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002834
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002835 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002836}
2837
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002838bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002839 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002840 VariadicCallType CallType =
2841 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002842
George Burgess IVce6284b2017-01-28 02:19:40 +00002843 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2844 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002845 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002846
2847 return false;
2848}
2849
Richard Trieu664c4c62013-06-20 21:03:13 +00002850bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2851 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002852 QualType Ty;
2853 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002854 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002855 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002856 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002857 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002858 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002859
Douglas Gregorb4866e82015-06-19 18:13:19 +00002860 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2861 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002862 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002863
Richard Trieu664c4c62013-06-20 21:03:13 +00002864 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002865 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002866 CallType = VariadicDoesNotApply;
2867 } else if (Ty->isBlockPointerType()) {
2868 CallType = VariadicBlock;
2869 } else { // Ty->isFunctionPointerType()
2870 CallType = VariadicFunction;
2871 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002872
George Burgess IVce6284b2017-01-28 02:19:40 +00002873 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002874 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2875 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002876 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002877
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002878 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002879}
2880
Richard Trieu41bc0992013-06-22 00:20:41 +00002881/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2882/// such as function pointers returned from functions.
2883bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002884 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002885 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002886 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002887 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002888 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002889 TheCall->getCallee()->getSourceRange(), CallType);
2890
2891 return false;
2892}
2893
Tim Northovere94a34c2014-03-11 10:49:14 +00002894static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002895 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002896 return false;
2897
JF Bastiendda2cb12016-04-18 18:01:49 +00002898 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002899 switch (Op) {
2900 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002901 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002902 llvm_unreachable("There is no ordering argument for an init");
2903
2904 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002905 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002906 case AtomicExpr::AO__atomic_load_n:
2907 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002908 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2909 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002910
2911 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002912 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002913 case AtomicExpr::AO__atomic_store:
2914 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002915 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2916 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2917 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002918
2919 default:
2920 return true;
2921 }
2922}
2923
Richard Smithfeea8832012-04-12 05:08:17 +00002924ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2925 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002926 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2927 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002928
Yaxun Liu39195062017-08-04 18:16:31 +00002929 // All the non-OpenCL operations take one of the following forms.
2930 // The OpenCL operations take the __c11 forms with one extra argument for
2931 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002932 enum {
2933 // C __c11_atomic_init(A *, C)
2934 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002935
Richard Smithfeea8832012-04-12 05:08:17 +00002936 // C __c11_atomic_load(A *, int)
2937 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002938
Richard Smithfeea8832012-04-12 05:08:17 +00002939 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002940 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002941
Eric Fiselier8d662442016-03-30 23:39:56 +00002942 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002943 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002944
Richard Smithfeea8832012-04-12 05:08:17 +00002945 // C __c11_atomic_add(A *, M, int)
2946 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002947
Richard Smithfeea8832012-04-12 05:08:17 +00002948 // C __atomic_exchange_n(A *, CP, int)
2949 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002950
Richard Smithfeea8832012-04-12 05:08:17 +00002951 // void __atomic_exchange(A *, C *, CP, int)
2952 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002953
Richard Smithfeea8832012-04-12 05:08:17 +00002954 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2955 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002956
Richard Smithfeea8832012-04-12 05:08:17 +00002957 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2958 GNUCmpXchg
2959 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002960
Yaxun Liu39195062017-08-04 18:16:31 +00002961 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00002962 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2963 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00002964 // where:
2965 // C is an appropriate type,
2966 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2967 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2968 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2969 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002970
Yaxun Liu39195062017-08-04 18:16:31 +00002971 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2972 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2973 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00002974 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2975 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2976 AtomicExpr::AO__atomic_load,
2977 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00002978 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2979 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2980 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2981 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2982 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00002983 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2984 Op == AtomicExpr::AO__atomic_store_n ||
2985 Op == AtomicExpr::AO__atomic_exchange_n ||
2986 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2987 bool IsAddSub = false;
2988
2989 switch (Op) {
2990 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002991 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00002992 Form = Init;
2993 break;
2994
2995 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002996 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00002997 case AtomicExpr::AO__atomic_load_n:
2998 Form = Load;
2999 break;
3000
Richard Smithfeea8832012-04-12 05:08:17 +00003001 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003002 Form = LoadCopy;
3003 break;
3004
3005 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003006 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003007 case AtomicExpr::AO__atomic_store:
3008 case AtomicExpr::AO__atomic_store_n:
3009 Form = Copy;
3010 break;
3011
3012 case AtomicExpr::AO__c11_atomic_fetch_add:
3013 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003014 case AtomicExpr::AO__opencl_atomic_fetch_add:
3015 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3016 case AtomicExpr::AO__opencl_atomic_fetch_min:
3017 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003018 case AtomicExpr::AO__atomic_fetch_add:
3019 case AtomicExpr::AO__atomic_fetch_sub:
3020 case AtomicExpr::AO__atomic_add_fetch:
3021 case AtomicExpr::AO__atomic_sub_fetch:
3022 IsAddSub = true;
3023 // Fall through.
3024 case AtomicExpr::AO__c11_atomic_fetch_and:
3025 case AtomicExpr::AO__c11_atomic_fetch_or:
3026 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003027 case AtomicExpr::AO__opencl_atomic_fetch_and:
3028 case AtomicExpr::AO__opencl_atomic_fetch_or:
3029 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003030 case AtomicExpr::AO__atomic_fetch_and:
3031 case AtomicExpr::AO__atomic_fetch_or:
3032 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003033 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003034 case AtomicExpr::AO__atomic_and_fetch:
3035 case AtomicExpr::AO__atomic_or_fetch:
3036 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003037 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003038 Form = Arithmetic;
3039 break;
3040
3041 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003042 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003043 case AtomicExpr::AO__atomic_exchange_n:
3044 Form = Xchg;
3045 break;
3046
3047 case AtomicExpr::AO__atomic_exchange:
3048 Form = GNUXchg;
3049 break;
3050
3051 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3052 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003053 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3054 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003055 Form = C11CmpXchg;
3056 break;
3057
3058 case AtomicExpr::AO__atomic_compare_exchange:
3059 case AtomicExpr::AO__atomic_compare_exchange_n:
3060 Form = GNUCmpXchg;
3061 break;
3062 }
3063
Yaxun Liu39195062017-08-04 18:16:31 +00003064 unsigned AdjustedNumArgs = NumArgs[Form];
3065 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3066 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003067 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003068 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003069 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003070 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003071 << TheCall->getCallee()->getSourceRange();
3072 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003073 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3074 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003075 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003076 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003077 << TheCall->getCallee()->getSourceRange();
3078 return ExprError();
3079 }
3080
Richard Smithfeea8832012-04-12 05:08:17 +00003081 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003082 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003083 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3084 if (ConvertedPtr.isInvalid())
3085 return ExprError();
3086
3087 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003088 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3089 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003090 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003091 << Ptr->getType() << Ptr->getSourceRange();
3092 return ExprError();
3093 }
3094
Richard Smithfeea8832012-04-12 05:08:17 +00003095 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3096 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3097 QualType ValType = AtomTy; // 'C'
3098 if (IsC11) {
3099 if (!AtomTy->isAtomicType()) {
3100 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3101 << Ptr->getType() << Ptr->getSourceRange();
3102 return ExprError();
3103 }
Yaxun Liu39195062017-08-04 18:16:31 +00003104 if (AtomTy.isConstQualified() ||
3105 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003106 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003107 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3108 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003109 return ExprError();
3110 }
Richard Smithfeea8832012-04-12 05:08:17 +00003111 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003112 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003113 if (ValType.isConstQualified()) {
3114 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3115 << Ptr->getType() << Ptr->getSourceRange();
3116 return ExprError();
3117 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003118 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003119
Richard Smithfeea8832012-04-12 05:08:17 +00003120 // For an arithmetic operation, the implied arithmetic must be well-formed.
3121 if (Form == Arithmetic) {
3122 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3123 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3124 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3125 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126 return ExprError();
3127 }
3128 if (!IsAddSub && !ValType->isIntegerType()) {
3129 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3130 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3131 return ExprError();
3132 }
David Majnemere85cff82015-01-28 05:48:06 +00003133 if (IsC11 && ValType->isPointerType() &&
3134 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3135 diag::err_incomplete_type)) {
3136 return ExprError();
3137 }
Richard Smithfeea8832012-04-12 05:08:17 +00003138 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3139 // For __atomic_*_n operations, the value type must be a scalar integral or
3140 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003141 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003142 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3143 return ExprError();
3144 }
3145
Eli Friedmanaa769812013-09-11 03:49:34 +00003146 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3147 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003148 // For GNU atomics, require a trivially-copyable type. This is not part of
3149 // the GNU atomics specification, but we enforce it for sanity.
3150 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003151 << Ptr->getType() << Ptr->getSourceRange();
3152 return ExprError();
3153 }
3154
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003155 switch (ValType.getObjCLifetime()) {
3156 case Qualifiers::OCL_None:
3157 case Qualifiers::OCL_ExplicitNone:
3158 // okay
3159 break;
3160
3161 case Qualifiers::OCL_Weak:
3162 case Qualifiers::OCL_Strong:
3163 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003164 // FIXME: Can this happen? By this point, ValType should be known
3165 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003166 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3167 << ValType << Ptr->getSourceRange();
3168 return ExprError();
3169 }
3170
David Majnemerc6eb6502015-06-03 00:26:35 +00003171 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3172 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003173 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003174 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003175 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003176 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003177 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3178 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003179 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003180 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003181 ResultType = Context.BoolTy;
3182
Richard Smithfeea8832012-04-12 05:08:17 +00003183 // The type of a parameter passed 'by value'. In the GNU atomics, such
3184 // arguments are actually passed as pointers.
3185 QualType ByValType = ValType; // 'CP'
3186 if (!IsC11 && !IsN)
3187 ByValType = Ptr->getType();
3188
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003189 // The first argument --- the pointer --- has a fixed type; we
3190 // deduce the types of the rest of the arguments accordingly. Walk
3191 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003192 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003193 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003194 if (i < NumVals[Form] + 1) {
3195 switch (i) {
3196 case 1:
3197 // The second argument is the non-atomic operand. For arithmetic, this
3198 // is always passed by value, and for a compare_exchange it is always
3199 // passed by address. For the rest, GNU uses by-address and C11 uses
3200 // by-value.
3201 assert(Form != Load);
3202 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3203 Ty = ValType;
3204 else if (Form == Copy || Form == Xchg)
3205 Ty = ByValType;
3206 else if (Form == Arithmetic)
3207 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003208 else {
3209 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003210 // Treat this argument as _Nonnull as we want to show a warning if
3211 // NULL is passed into it.
3212 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003213 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003214 // Keep address space of non-atomic pointer type.
3215 if (const PointerType *PtrTy =
3216 ValArg->getType()->getAs<PointerType>()) {
3217 AS = PtrTy->getPointeeType().getAddressSpace();
3218 }
3219 Ty = Context.getPointerType(
3220 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3221 }
Richard Smithfeea8832012-04-12 05:08:17 +00003222 break;
3223 case 2:
3224 // The third argument to compare_exchange / GNU exchange is a
3225 // (pointer to a) desired value.
3226 Ty = ByValType;
3227 break;
3228 case 3:
3229 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3230 Ty = Context.BoolTy;
3231 break;
3232 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003233 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003234 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003235 Ty = Context.IntTy;
3236 }
Richard Smithfeea8832012-04-12 05:08:17 +00003237
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003238 InitializedEntity Entity =
3239 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003240 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003241 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3242 if (Arg.isInvalid())
3243 return true;
3244 TheCall->setArg(i, Arg.get());
3245 }
3246
Richard Smithfeea8832012-04-12 05:08:17 +00003247 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003248 SmallVector<Expr*, 5> SubExprs;
3249 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003250 switch (Form) {
3251 case Init:
3252 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003253 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003254 break;
3255 case Load:
3256 SubExprs.push_back(TheCall->getArg(1)); // Order
3257 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003258 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003259 case Copy:
3260 case Arithmetic:
3261 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003262 SubExprs.push_back(TheCall->getArg(2)); // Order
3263 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003264 break;
3265 case GNUXchg:
3266 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3267 SubExprs.push_back(TheCall->getArg(3)); // Order
3268 SubExprs.push_back(TheCall->getArg(1)); // Val1
3269 SubExprs.push_back(TheCall->getArg(2)); // Val2
3270 break;
3271 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003272 SubExprs.push_back(TheCall->getArg(3)); // Order
3273 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003274 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003275 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003276 break;
3277 case GNUCmpXchg:
3278 SubExprs.push_back(TheCall->getArg(4)); // Order
3279 SubExprs.push_back(TheCall->getArg(1)); // Val1
3280 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3281 SubExprs.push_back(TheCall->getArg(2)); // Val2
3282 SubExprs.push_back(TheCall->getArg(3)); // Weak
3283 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003284 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003285
3286 if (SubExprs.size() >= 2 && Form != Init) {
3287 llvm::APSInt Result(32);
3288 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3289 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003290 Diag(SubExprs[1]->getLocStart(),
3291 diag::warn_atomic_op_has_invalid_memory_order)
3292 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003293 }
3294
Yaxun Liu30d652a2017-08-15 16:02:49 +00003295 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3296 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3297 llvm::APSInt Result(32);
3298 if (Scope->isIntegerConstantExpr(Result, Context) &&
3299 !ScopeModel->isValid(Result.getZExtValue())) {
3300 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3301 << Scope->getSourceRange();
3302 }
3303 SubExprs.push_back(Scope);
3304 }
3305
Fariborz Jahanian615de762013-05-28 17:37:39 +00003306 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3307 SubExprs, ResultType, Op,
3308 TheCall->getRParenLoc());
3309
3310 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003311 Op == AtomicExpr::AO__c11_atomic_store ||
3312 Op == AtomicExpr::AO__opencl_atomic_load ||
3313 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003314 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003315 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3316 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3317 Op == AtomicExpr::AO__opencl_atomic_load)
3318 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003319
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003320 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003321}
3322
John McCall29ad95b2011-08-27 01:09:30 +00003323/// checkBuiltinArgument - Given a call to a builtin function, perform
3324/// normal type-checking on the given argument, updating the call in
3325/// place. This is useful when a builtin function requires custom
3326/// type-checking for some of its arguments but not necessarily all of
3327/// them.
3328///
3329/// Returns true on error.
3330static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3331 FunctionDecl *Fn = E->getDirectCallee();
3332 assert(Fn && "builtin call without direct callee!");
3333
3334 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3335 InitializedEntity Entity =
3336 InitializedEntity::InitializeParameter(S.Context, Param);
3337
3338 ExprResult Arg = E->getArg(0);
3339 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3340 if (Arg.isInvalid())
3341 return true;
3342
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003343 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003344 return false;
3345}
3346
Chris Lattnerdc046542009-05-08 06:58:22 +00003347/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3348/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3349/// type of its first argument. The main ActOnCallExpr routines have already
3350/// promoted the types of arguments because all of these calls are prototyped as
3351/// void(...).
3352///
3353/// This function goes through and does final semantic checking for these
3354/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003355ExprResult
3356Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003358 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3359 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3360
3361 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003362 if (TheCall->getNumArgs() < 1) {
3363 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3364 << 0 << 1 << TheCall->getNumArgs()
3365 << TheCall->getCallee()->getSourceRange();
3366 return ExprError();
3367 }
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattnerdc046542009-05-08 06:58:22 +00003369 // Inspect the first argument of the atomic builtin. This should always be
3370 // a pointer type, whose element is an integral scalar or pointer type.
3371 // Because it is a pointer type, we don't have to worry about any implicit
3372 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003373 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003374 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003375 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3376 if (FirstArgResult.isInvalid())
3377 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003378 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003379 TheCall->setArg(0, FirstArg);
3380
John McCall31168b02011-06-15 23:02:42 +00003381 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3382 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003383 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3384 << FirstArg->getType() << FirstArg->getSourceRange();
3385 return ExprError();
3386 }
Mike Stump11289f42009-09-09 15:08:12 +00003387
John McCall31168b02011-06-15 23:02:42 +00003388 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003390 !ValType->isBlockPointerType()) {
3391 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3392 << FirstArg->getType() << FirstArg->getSourceRange();
3393 return ExprError();
3394 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003395
John McCall31168b02011-06-15 23:02:42 +00003396 switch (ValType.getObjCLifetime()) {
3397 case Qualifiers::OCL_None:
3398 case Qualifiers::OCL_ExplicitNone:
3399 // okay
3400 break;
3401
3402 case Qualifiers::OCL_Weak:
3403 case Qualifiers::OCL_Strong:
3404 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003405 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003406 << ValType << FirstArg->getSourceRange();
3407 return ExprError();
3408 }
3409
John McCallb50451a2011-10-05 07:41:44 +00003410 // Strip any qualifiers off ValType.
3411 ValType = ValType.getUnqualifiedType();
3412
Chandler Carruth3973af72010-07-18 20:54:12 +00003413 // The majority of builtins return a value, but a few have special return
3414 // types, so allow them to override appropriately below.
3415 QualType ResultType = ValType;
3416
Chris Lattnerdc046542009-05-08 06:58:22 +00003417 // We need to figure out which concrete builtin this maps onto. For example,
3418 // __sync_fetch_and_add with a 2 byte object turns into
3419 // __sync_fetch_and_add_2.
3420#define BUILTIN_ROW(x) \
3421 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3422 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003423
Chris Lattnerdc046542009-05-08 06:58:22 +00003424 static const unsigned BuiltinIndices[][5] = {
3425 BUILTIN_ROW(__sync_fetch_and_add),
3426 BUILTIN_ROW(__sync_fetch_and_sub),
3427 BUILTIN_ROW(__sync_fetch_and_or),
3428 BUILTIN_ROW(__sync_fetch_and_and),
3429 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003430 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003431
Chris Lattnerdc046542009-05-08 06:58:22 +00003432 BUILTIN_ROW(__sync_add_and_fetch),
3433 BUILTIN_ROW(__sync_sub_and_fetch),
3434 BUILTIN_ROW(__sync_and_and_fetch),
3435 BUILTIN_ROW(__sync_or_and_fetch),
3436 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003437 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003438
Chris Lattnerdc046542009-05-08 06:58:22 +00003439 BUILTIN_ROW(__sync_val_compare_and_swap),
3440 BUILTIN_ROW(__sync_bool_compare_and_swap),
3441 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003442 BUILTIN_ROW(__sync_lock_release),
3443 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003444 };
Mike Stump11289f42009-09-09 15:08:12 +00003445#undef BUILTIN_ROW
3446
Chris Lattnerdc046542009-05-08 06:58:22 +00003447 // Determine the index of the size.
3448 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003449 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003450 case 1: SizeIndex = 0; break;
3451 case 2: SizeIndex = 1; break;
3452 case 4: SizeIndex = 2; break;
3453 case 8: SizeIndex = 3; break;
3454 case 16: SizeIndex = 4; break;
3455 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003456 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3457 << FirstArg->getType() << FirstArg->getSourceRange();
3458 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003459 }
Mike Stump11289f42009-09-09 15:08:12 +00003460
Chris Lattnerdc046542009-05-08 06:58:22 +00003461 // Each of these builtins has one pointer argument, followed by some number of
3462 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3463 // that we ignore. Find out which row of BuiltinIndices to read from as well
3464 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003465 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003466 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003467 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003468 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003469 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003470 case Builtin::BI__sync_fetch_and_add:
3471 case Builtin::BI__sync_fetch_and_add_1:
3472 case Builtin::BI__sync_fetch_and_add_2:
3473 case Builtin::BI__sync_fetch_and_add_4:
3474 case Builtin::BI__sync_fetch_and_add_8:
3475 case Builtin::BI__sync_fetch_and_add_16:
3476 BuiltinIndex = 0;
3477 break;
3478
3479 case Builtin::BI__sync_fetch_and_sub:
3480 case Builtin::BI__sync_fetch_and_sub_1:
3481 case Builtin::BI__sync_fetch_and_sub_2:
3482 case Builtin::BI__sync_fetch_and_sub_4:
3483 case Builtin::BI__sync_fetch_and_sub_8:
3484 case Builtin::BI__sync_fetch_and_sub_16:
3485 BuiltinIndex = 1;
3486 break;
3487
3488 case Builtin::BI__sync_fetch_and_or:
3489 case Builtin::BI__sync_fetch_and_or_1:
3490 case Builtin::BI__sync_fetch_and_or_2:
3491 case Builtin::BI__sync_fetch_and_or_4:
3492 case Builtin::BI__sync_fetch_and_or_8:
3493 case Builtin::BI__sync_fetch_and_or_16:
3494 BuiltinIndex = 2;
3495 break;
3496
3497 case Builtin::BI__sync_fetch_and_and:
3498 case Builtin::BI__sync_fetch_and_and_1:
3499 case Builtin::BI__sync_fetch_and_and_2:
3500 case Builtin::BI__sync_fetch_and_and_4:
3501 case Builtin::BI__sync_fetch_and_and_8:
3502 case Builtin::BI__sync_fetch_and_and_16:
3503 BuiltinIndex = 3;
3504 break;
Mike Stump11289f42009-09-09 15:08:12 +00003505
Douglas Gregor73722482011-11-28 16:30:08 +00003506 case Builtin::BI__sync_fetch_and_xor:
3507 case Builtin::BI__sync_fetch_and_xor_1:
3508 case Builtin::BI__sync_fetch_and_xor_2:
3509 case Builtin::BI__sync_fetch_and_xor_4:
3510 case Builtin::BI__sync_fetch_and_xor_8:
3511 case Builtin::BI__sync_fetch_and_xor_16:
3512 BuiltinIndex = 4;
3513 break;
3514
Hal Finkeld2208b52014-10-02 20:53:50 +00003515 case Builtin::BI__sync_fetch_and_nand:
3516 case Builtin::BI__sync_fetch_and_nand_1:
3517 case Builtin::BI__sync_fetch_and_nand_2:
3518 case Builtin::BI__sync_fetch_and_nand_4:
3519 case Builtin::BI__sync_fetch_and_nand_8:
3520 case Builtin::BI__sync_fetch_and_nand_16:
3521 BuiltinIndex = 5;
3522 WarnAboutSemanticsChange = true;
3523 break;
3524
Douglas Gregor73722482011-11-28 16:30:08 +00003525 case Builtin::BI__sync_add_and_fetch:
3526 case Builtin::BI__sync_add_and_fetch_1:
3527 case Builtin::BI__sync_add_and_fetch_2:
3528 case Builtin::BI__sync_add_and_fetch_4:
3529 case Builtin::BI__sync_add_and_fetch_8:
3530 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003531 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003532 break;
3533
3534 case Builtin::BI__sync_sub_and_fetch:
3535 case Builtin::BI__sync_sub_and_fetch_1:
3536 case Builtin::BI__sync_sub_and_fetch_2:
3537 case Builtin::BI__sync_sub_and_fetch_4:
3538 case Builtin::BI__sync_sub_and_fetch_8:
3539 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003540 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003541 break;
3542
3543 case Builtin::BI__sync_and_and_fetch:
3544 case Builtin::BI__sync_and_and_fetch_1:
3545 case Builtin::BI__sync_and_and_fetch_2:
3546 case Builtin::BI__sync_and_and_fetch_4:
3547 case Builtin::BI__sync_and_and_fetch_8:
3548 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003549 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003550 break;
3551
3552 case Builtin::BI__sync_or_and_fetch:
3553 case Builtin::BI__sync_or_and_fetch_1:
3554 case Builtin::BI__sync_or_and_fetch_2:
3555 case Builtin::BI__sync_or_and_fetch_4:
3556 case Builtin::BI__sync_or_and_fetch_8:
3557 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003558 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003559 break;
3560
3561 case Builtin::BI__sync_xor_and_fetch:
3562 case Builtin::BI__sync_xor_and_fetch_1:
3563 case Builtin::BI__sync_xor_and_fetch_2:
3564 case Builtin::BI__sync_xor_and_fetch_4:
3565 case Builtin::BI__sync_xor_and_fetch_8:
3566 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003567 BuiltinIndex = 10;
3568 break;
3569
3570 case Builtin::BI__sync_nand_and_fetch:
3571 case Builtin::BI__sync_nand_and_fetch_1:
3572 case Builtin::BI__sync_nand_and_fetch_2:
3573 case Builtin::BI__sync_nand_and_fetch_4:
3574 case Builtin::BI__sync_nand_and_fetch_8:
3575 case Builtin::BI__sync_nand_and_fetch_16:
3576 BuiltinIndex = 11;
3577 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003578 break;
Mike Stump11289f42009-09-09 15:08:12 +00003579
Chris Lattnerdc046542009-05-08 06:58:22 +00003580 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003581 case Builtin::BI__sync_val_compare_and_swap_1:
3582 case Builtin::BI__sync_val_compare_and_swap_2:
3583 case Builtin::BI__sync_val_compare_and_swap_4:
3584 case Builtin::BI__sync_val_compare_and_swap_8:
3585 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003586 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003587 NumFixed = 2;
3588 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003589
Chris Lattnerdc046542009-05-08 06:58:22 +00003590 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003591 case Builtin::BI__sync_bool_compare_and_swap_1:
3592 case Builtin::BI__sync_bool_compare_and_swap_2:
3593 case Builtin::BI__sync_bool_compare_and_swap_4:
3594 case Builtin::BI__sync_bool_compare_and_swap_8:
3595 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003596 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003597 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003598 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003599 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003600
3601 case Builtin::BI__sync_lock_test_and_set:
3602 case Builtin::BI__sync_lock_test_and_set_1:
3603 case Builtin::BI__sync_lock_test_and_set_2:
3604 case Builtin::BI__sync_lock_test_and_set_4:
3605 case Builtin::BI__sync_lock_test_and_set_8:
3606 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003607 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003608 break;
3609
Chris Lattnerdc046542009-05-08 06:58:22 +00003610 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003611 case Builtin::BI__sync_lock_release_1:
3612 case Builtin::BI__sync_lock_release_2:
3613 case Builtin::BI__sync_lock_release_4:
3614 case Builtin::BI__sync_lock_release_8:
3615 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003616 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003617 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003618 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003619 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003620
3621 case Builtin::BI__sync_swap:
3622 case Builtin::BI__sync_swap_1:
3623 case Builtin::BI__sync_swap_2:
3624 case Builtin::BI__sync_swap_4:
3625 case Builtin::BI__sync_swap_8:
3626 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003627 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003628 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003629 }
Mike Stump11289f42009-09-09 15:08:12 +00003630
Chris Lattnerdc046542009-05-08 06:58:22 +00003631 // Now that we know how many fixed arguments we expect, first check that we
3632 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003633 if (TheCall->getNumArgs() < 1+NumFixed) {
3634 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3635 << 0 << 1+NumFixed << TheCall->getNumArgs()
3636 << TheCall->getCallee()->getSourceRange();
3637 return ExprError();
3638 }
Mike Stump11289f42009-09-09 15:08:12 +00003639
Hal Finkeld2208b52014-10-02 20:53:50 +00003640 if (WarnAboutSemanticsChange) {
3641 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3642 << TheCall->getCallee()->getSourceRange();
3643 }
3644
Chris Lattner5b9241b2009-05-08 15:36:58 +00003645 // Get the decl for the concrete builtin from this, we can tell what the
3646 // concrete integer type we should convert to is.
3647 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003648 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003649 FunctionDecl *NewBuiltinDecl;
3650 if (NewBuiltinID == BuiltinID)
3651 NewBuiltinDecl = FDecl;
3652 else {
3653 // Perform builtin lookup to avoid redeclaring it.
3654 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3655 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3656 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3657 assert(Res.getFoundDecl());
3658 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003659 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003660 return ExprError();
3661 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003662
John McCallcf142162010-08-07 06:22:56 +00003663 // The first argument --- the pointer --- has a fixed type; we
3664 // deduce the types of the rest of the arguments accordingly. Walk
3665 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003666 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003667 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003668
Chris Lattnerdc046542009-05-08 06:58:22 +00003669 // GCC does an implicit conversion to the pointer or integer ValType. This
3670 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003671 // Initialize the argument.
3672 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3673 ValType, /*consume*/ false);
3674 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003675 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003676 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003677
Chris Lattnerdc046542009-05-08 06:58:22 +00003678 // Okay, we have something that *can* be converted to the right type. Check
3679 // to see if there is a potentially weird extension going on here. This can
3680 // happen when you do an atomic operation on something like an char* and
3681 // pass in 42. The 42 gets converted to char. This is even more strange
3682 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003683 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003684 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003685 }
Mike Stump11289f42009-09-09 15:08:12 +00003686
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003687 ASTContext& Context = this->getASTContext();
3688
3689 // Create a new DeclRefExpr to refer to the new decl.
3690 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3691 Context,
3692 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003693 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003694 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003695 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003696 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003697 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003698 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003699
Chris Lattnerdc046542009-05-08 06:58:22 +00003700 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003701 // FIXME: This loses syntactic information.
3702 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3703 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3704 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003705 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003706
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003707 // Change the result type of the call to match the original value type. This
3708 // is arbitrary, but the codegen for these builtins ins design to handle it
3709 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003710 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003711
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003712 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003713}
3714
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003715/// SemaBuiltinNontemporalOverloaded - We have a call to
3716/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3717/// overloaded function based on the pointer type of its last argument.
3718///
3719/// This function goes through and does final semantic checking for these
3720/// builtins.
3721ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3722 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3723 DeclRefExpr *DRE =
3724 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3725 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3726 unsigned BuiltinID = FDecl->getBuiltinID();
3727 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3728 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3729 "Unexpected nontemporal load/store builtin!");
3730 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3731 unsigned numArgs = isStore ? 2 : 1;
3732
3733 // Ensure that we have the proper number of arguments.
3734 if (checkArgCount(*this, TheCall, numArgs))
3735 return ExprError();
3736
3737 // Inspect the last argument of the nontemporal builtin. This should always
3738 // be a pointer type, from which we imply the type of the memory access.
3739 // Because it is a pointer type, we don't have to worry about any implicit
3740 // casts here.
3741 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3742 ExprResult PointerArgResult =
3743 DefaultFunctionArrayLvalueConversion(PointerArg);
3744
3745 if (PointerArgResult.isInvalid())
3746 return ExprError();
3747 PointerArg = PointerArgResult.get();
3748 TheCall->setArg(numArgs - 1, PointerArg);
3749
3750 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3751 if (!pointerType) {
3752 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3753 << PointerArg->getType() << PointerArg->getSourceRange();
3754 return ExprError();
3755 }
3756
3757 QualType ValType = pointerType->getPointeeType();
3758
3759 // Strip any qualifiers off ValType.
3760 ValType = ValType.getUnqualifiedType();
3761 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3762 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3763 !ValType->isVectorType()) {
3764 Diag(DRE->getLocStart(),
3765 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3766 << PointerArg->getType() << PointerArg->getSourceRange();
3767 return ExprError();
3768 }
3769
3770 if (!isStore) {
3771 TheCall->setType(ValType);
3772 return TheCallResult;
3773 }
3774
3775 ExprResult ValArg = TheCall->getArg(0);
3776 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3777 Context, ValType, /*consume*/ false);
3778 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3779 if (ValArg.isInvalid())
3780 return ExprError();
3781
3782 TheCall->setArg(0, ValArg.get());
3783 TheCall->setType(Context.VoidTy);
3784 return TheCallResult;
3785}
3786
Chris Lattner6436fb62009-02-18 06:01:06 +00003787/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003788/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003789/// Note: It might also make sense to do the UTF-16 conversion here (would
3790/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003791bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003792 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003793 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3794
Douglas Gregorfb65e592011-07-27 05:40:30 +00003795 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003796 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3797 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003798 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003799 }
Mike Stump11289f42009-09-09 15:08:12 +00003800
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003801 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003802 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003803 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003804 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3805 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3806 llvm::UTF16 *ToPtr = &ToBuf[0];
3807
3808 llvm::ConversionResult Result =
3809 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3810 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003811 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003812 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003813 Diag(Arg->getLocStart(),
3814 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3815 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003816 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003817}
3818
Mehdi Amini06d367c2016-10-24 20:39:34 +00003819/// CheckObjCString - Checks that the format string argument to the os_log()
3820/// and os_trace() functions is correct, and converts it to const char *.
3821ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3822 Arg = Arg->IgnoreParenCasts();
3823 auto *Literal = dyn_cast<StringLiteral>(Arg);
3824 if (!Literal) {
3825 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3826 Literal = ObjcLiteral->getString();
3827 }
3828 }
3829
3830 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3831 return ExprError(
3832 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3833 << Arg->getSourceRange());
3834 }
3835
3836 ExprResult Result(Literal);
3837 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3838 InitializedEntity Entity =
3839 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3840 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3841 return Result;
3842}
3843
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003844/// Check that the user is calling the appropriate va_start builtin for the
3845/// target and calling convention.
3846static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3847 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3848 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003849 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003850 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003851 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3852 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003853 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003854 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3855 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3856 if (IsMSVAStart) {
3857 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003858 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003859 return S.Diag(Fn->getLocStart(),
3860 diag::err_ms_va_start_used_in_sysv_function);
3861 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003862 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003863 // On x64 Windows, don't allow this in System V ABI functions.
3864 // (Yes, that means there's no corresponding way to support variadic
3865 // System V ABI functions on Windows.)
3866 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003867 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003868 return S.Diag(Fn->getLocStart(),
3869 diag::err_va_start_used_in_wrong_abi_function)
3870 << !IsWindows;
3871 }
3872 return false;
3873 }
3874
3875 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003876 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003877 return false;
3878}
3879
3880static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3881 ParmVarDecl **LastParam = nullptr) {
3882 // Determine whether the current function, block, or obj-c method is variadic
3883 // and get its parameter list.
3884 bool IsVariadic = false;
3885 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003886 DeclContext *Caller = S.CurContext;
3887 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3888 IsVariadic = Block->isVariadic();
3889 Params = Block->parameters();
3890 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003891 IsVariadic = FD->isVariadic();
3892 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003893 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003894 IsVariadic = MD->isVariadic();
3895 // FIXME: This isn't correct for methods (results in bogus warning).
3896 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003897 } else if (isa<CapturedDecl>(Caller)) {
3898 // We don't support va_start in a CapturedDecl.
3899 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3900 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003901 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003902 // This must be some other declcontext that parses exprs.
3903 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3904 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003905 }
3906
3907 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003908 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003909 return true;
3910 }
3911
3912 if (LastParam)
3913 *LastParam = Params.empty() ? nullptr : Params.back();
3914
3915 return false;
3916}
3917
Charles Davisc7d5c942015-09-17 20:55:33 +00003918/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3919/// for validity. Emit an error and return true on failure; return false
3920/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003921bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003922 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003923
3924 if (checkVAStartABI(*this, BuiltinID, Fn))
3925 return true;
3926
Chris Lattner08464942007-12-28 05:29:59 +00003927 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003928 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003929 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003930 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3931 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003932 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003933 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003934 return true;
3935 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003936
3937 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003938 return Diag(TheCall->getLocEnd(),
3939 diag::err_typecheck_call_too_few_args_at_least)
3940 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003941 }
3942
John McCall29ad95b2011-08-27 01:09:30 +00003943 // Type-check the first argument normally.
3944 if (checkBuiltinArgument(*this, TheCall, 0))
3945 return true;
3946
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003947 // Check that the current function is variadic, and get its last parameter.
3948 ParmVarDecl *LastParam;
3949 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00003950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003951
Chris Lattner43be2e62007-12-19 23:59:04 +00003952 // Verify that the second argument to the builtin is the last argument of the
3953 // current function or method.
3954 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00003955 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003956
Nico Weber9eea7642013-05-24 23:31:57 +00003957 // These are valid if SecondArgIsLastNamedArgument is false after the next
3958 // block.
3959 QualType Type;
3960 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00003961 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00003962
Anders Carlsson6a8350b2008-02-11 04:20:54 +00003963 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3964 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003965 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00003966
3967 Type = PV->getType();
3968 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00003969 IsCRegister =
3970 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00003971 }
3972 }
Mike Stump11289f42009-09-09 15:08:12 +00003973
Chris Lattner43be2e62007-12-19 23:59:04 +00003974 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00003975 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00003976 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00003977 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00003978 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3979 // Promotable integers are UB, but enumerations need a bit of
3980 // extra checking to see what their promotable type actually is.
3981 if (!Type->isPromotableIntegerType())
3982 return false;
3983 if (!Type->isEnumeralType())
3984 return true;
3985 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3986 return !(ED &&
3987 Context.typesAreCompatible(ED->getPromotionType(), Type));
3988 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00003989 unsigned Reason = 0;
3990 if (Type->isReferenceType()) Reason = 1;
3991 else if (IsCRegister) Reason = 2;
3992 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00003993 Diag(ParamLoc, diag::note_parameter_type) << Type;
3994 }
3995
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00003996 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00003997 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00003998}
Chris Lattner43be2e62007-12-19 23:59:04 +00003999
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004000bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004001 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4002 // const char *named_addr);
4003
4004 Expr *Func = Call->getCallee();
4005
4006 if (Call->getNumArgs() < 3)
4007 return Diag(Call->getLocEnd(),
4008 diag::err_typecheck_call_too_few_args_at_least)
4009 << 0 /*function call*/ << 3 << Call->getNumArgs();
4010
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004011 // Type-check the first argument normally.
4012 if (checkBuiltinArgument(*this, Call, 0))
4013 return true;
4014
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004015 // Check that the current function is variadic.
4016 if (checkVAStartIsInVariadicFunction(*this, Func))
4017 return true;
4018
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004019 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004020
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004021 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4022 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4023
4024 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4025 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4026
4027 const QualType &ConstCharPtrTy =
4028 Context.getPointerType(Context.CharTy.withConst());
4029 if (!Arg1Ty->isPointerType() ||
4030 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4031 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4032 << Arg1->getType() << ConstCharPtrTy
4033 << 1 /* different class */
4034 << 0 /* qualifier difference */
4035 << 3 /* parameter mismatch */
4036 << 2 << Arg1->getType() << ConstCharPtrTy;
4037
4038 const QualType SizeTy = Context.getSizeType();
4039 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4040 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4041 << Arg2->getType() << SizeTy
4042 << 1 /* different class */
4043 << 0 /* qualifier difference */
4044 << 3 /* parameter mismatch */
4045 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004046
4047 return false;
4048}
4049
Chris Lattner2da14fb2007-12-20 00:26:33 +00004050/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4051/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004052bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4053 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004054 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004055 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004056 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004057 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004058 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004059 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004060 << SourceRange(TheCall->getArg(2)->getLocStart(),
4061 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004062
John Wiegley01296292011-04-08 18:41:53 +00004063 ExprResult OrigArg0 = TheCall->getArg(0);
4064 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004065
Chris Lattner2da14fb2007-12-20 00:26:33 +00004066 // Do standard promotions between the two arguments, returning their common
4067 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004068 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004069 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4070 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004071
4072 // Make sure any conversions are pushed back into the call; this is
4073 // type safe since unordered compare builtins are declared as "_Bool
4074 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004075 TheCall->setArg(0, OrigArg0.get());
4076 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004077
John Wiegley01296292011-04-08 18:41:53 +00004078 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004079 return false;
4080
Chris Lattner2da14fb2007-12-20 00:26:33 +00004081 // If the common type isn't a real floating type, then the arguments were
4082 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004083 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004084 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004085 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004086 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4087 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004088
Chris Lattner2da14fb2007-12-20 00:26:33 +00004089 return false;
4090}
4091
Benjamin Kramer634fc102010-02-15 22:42:31 +00004092/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4093/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004094/// to check everything. We expect the last argument to be a floating point
4095/// value.
4096bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4097 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004098 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004099 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004100 if (TheCall->getNumArgs() > NumArgs)
4101 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004102 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004103 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004104 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004105 (*(TheCall->arg_end()-1))->getLocEnd());
4106
Benjamin Kramer64aae502010-02-16 10:07:31 +00004107 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004108
Eli Friedman7e4faac2009-08-31 20:06:00 +00004109 if (OrigArg->isTypeDependent())
4110 return false;
4111
Chris Lattner68784ef2010-05-06 05:50:07 +00004112 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004113 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004114 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004115 diag::err_typecheck_call_invalid_unary_fp)
4116 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004117
Neil Hickey88c0fac2016-12-13 16:22:50 +00004118 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004119 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004120 // Only remove standard FloatCasts, leaving other casts inplace
4121 if (Cast->getCastKind() == CK_FloatingCast) {
4122 Expr *CastArg = Cast->getSubExpr();
4123 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4124 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4125 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4126 "promotion from float to either float or double is the only expected cast here");
4127 Cast->setSubExpr(nullptr);
4128 TheCall->setArg(NumArgs-1, CastArg);
4129 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004130 }
4131 }
4132
Eli Friedman7e4faac2009-08-31 20:06:00 +00004133 return false;
4134}
4135
Tony Jiangbbc48e92017-05-24 15:13:32 +00004136// Customized Sema Checking for VSX builtins that have the following signature:
4137// vector [...] builtinName(vector [...], vector [...], const int);
4138// Which takes the same type of vectors (any legal vector type) for the first
4139// two arguments and takes compile time constant for the third argument.
4140// Example builtins are :
4141// vector double vec_xxpermdi(vector double, vector double, int);
4142// vector short vec_xxsldwi(vector short, vector short, int);
4143bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4144 unsigned ExpectedNumArgs = 3;
4145 if (TheCall->getNumArgs() < ExpectedNumArgs)
4146 return Diag(TheCall->getLocEnd(),
4147 diag::err_typecheck_call_too_few_args_at_least)
4148 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4149 << TheCall->getSourceRange();
4150
4151 if (TheCall->getNumArgs() > ExpectedNumArgs)
4152 return Diag(TheCall->getLocEnd(),
4153 diag::err_typecheck_call_too_many_args_at_most)
4154 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4155 << TheCall->getSourceRange();
4156
4157 // Check the third argument is a compile time constant
4158 llvm::APSInt Value;
4159 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4160 return Diag(TheCall->getLocStart(),
4161 diag::err_vsx_builtin_nonconstant_argument)
4162 << 3 /* argument index */ << TheCall->getDirectCallee()
4163 << SourceRange(TheCall->getArg(2)->getLocStart(),
4164 TheCall->getArg(2)->getLocEnd());
4165
4166 QualType Arg1Ty = TheCall->getArg(0)->getType();
4167 QualType Arg2Ty = TheCall->getArg(1)->getType();
4168
4169 // Check the type of argument 1 and argument 2 are vectors.
4170 SourceLocation BuiltinLoc = TheCall->getLocStart();
4171 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4172 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4173 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4174 << TheCall->getDirectCallee()
4175 << SourceRange(TheCall->getArg(0)->getLocStart(),
4176 TheCall->getArg(1)->getLocEnd());
4177 }
4178
4179 // Check the first two arguments are the same type.
4180 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4181 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4182 << TheCall->getDirectCallee()
4183 << SourceRange(TheCall->getArg(0)->getLocStart(),
4184 TheCall->getArg(1)->getLocEnd());
4185 }
4186
4187 // When default clang type checking is turned off and the customized type
4188 // checking is used, the returning type of the function must be explicitly
4189 // set. Otherwise it is _Bool by default.
4190 TheCall->setType(Arg1Ty);
4191
4192 return false;
4193}
4194
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004195/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4196// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004197ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004198 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004199 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004200 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004201 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4202 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004203
Nate Begemana0110022010-06-08 00:16:34 +00004204 // Determine which of the following types of shufflevector we're checking:
4205 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004206 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004207 QualType resType = TheCall->getArg(0)->getType();
4208 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004209
Douglas Gregorc25f7662009-05-19 22:10:17 +00004210 if (!TheCall->getArg(0)->isTypeDependent() &&
4211 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004212 QualType LHSType = TheCall->getArg(0)->getType();
4213 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004214
Craig Topperbaca3892013-07-29 06:47:04 +00004215 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4216 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004217 diag::err_vec_builtin_non_vector)
4218 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004219 << SourceRange(TheCall->getArg(0)->getLocStart(),
4220 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004221
Nate Begemana0110022010-06-08 00:16:34 +00004222 numElements = LHSType->getAs<VectorType>()->getNumElements();
4223 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004224
Nate Begemana0110022010-06-08 00:16:34 +00004225 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4226 // with mask. If so, verify that RHS is an integer vector type with the
4227 // same number of elts as lhs.
4228 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004229 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004230 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004231 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004232 diag::err_vec_builtin_incompatible_vector)
4233 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004234 << SourceRange(TheCall->getArg(1)->getLocStart(),
4235 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004236 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004237 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004238 diag::err_vec_builtin_incompatible_vector)
4239 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004240 << SourceRange(TheCall->getArg(0)->getLocStart(),
4241 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004242 } else if (numElements != numResElements) {
4243 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004244 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004245 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004246 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004247 }
4248
4249 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004250 if (TheCall->getArg(i)->isTypeDependent() ||
4251 TheCall->getArg(i)->isValueDependent())
4252 continue;
4253
Nate Begemana0110022010-06-08 00:16:34 +00004254 llvm::APSInt Result(32);
4255 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4256 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004257 diag::err_shufflevector_nonconstant_argument)
4258 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004259
Craig Topper50ad5b72013-08-03 17:40:38 +00004260 // Allow -1 which will be translated to undef in the IR.
4261 if (Result.isSigned() && Result.isAllOnesValue())
4262 continue;
4263
Chris Lattner7ab824e2008-08-10 02:05:13 +00004264 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004265 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004266 diag::err_shufflevector_argument_too_large)
4267 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004268 }
4269
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004270 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004271
Chris Lattner7ab824e2008-08-10 02:05:13 +00004272 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004273 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004274 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004275 }
4276
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004277 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4278 TheCall->getCallee()->getLocStart(),
4279 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004280}
Chris Lattner43be2e62007-12-19 23:59:04 +00004281
Hal Finkelc4d7c822013-09-18 03:29:45 +00004282/// SemaConvertVectorExpr - Handle __builtin_convertvector
4283ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4284 SourceLocation BuiltinLoc,
4285 SourceLocation RParenLoc) {
4286 ExprValueKind VK = VK_RValue;
4287 ExprObjectKind OK = OK_Ordinary;
4288 QualType DstTy = TInfo->getType();
4289 QualType SrcTy = E->getType();
4290
4291 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4292 return ExprError(Diag(BuiltinLoc,
4293 diag::err_convertvector_non_vector)
4294 << E->getSourceRange());
4295 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4296 return ExprError(Diag(BuiltinLoc,
4297 diag::err_convertvector_non_vector_type));
4298
4299 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4300 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4301 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4302 if (SrcElts != DstElts)
4303 return ExprError(Diag(BuiltinLoc,
4304 diag::err_convertvector_incompatible_vector)
4305 << E->getSourceRange());
4306 }
4307
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004308 return new (Context)
4309 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004310}
4311
Daniel Dunbarb7257262008-07-21 22:59:13 +00004312/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4313// This is declared to take (const void*, ...) and can take two
4314// optional constant int args.
4315bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004316 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004317
Chris Lattner3b054132008-11-19 05:08:23 +00004318 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004319 return Diag(TheCall->getLocEnd(),
4320 diag::err_typecheck_call_too_many_args_at_most)
4321 << 0 /*function call*/ << 3 << NumArgs
4322 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004323
4324 // Argument 0 is checked for us and the remaining arguments must be
4325 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004326 for (unsigned i = 1; i != NumArgs; ++i)
4327 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004328 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004329
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004330 return false;
4331}
4332
Hal Finkelf0417332014-07-17 14:25:55 +00004333/// SemaBuiltinAssume - Handle __assume (MS Extension).
4334// __assume does not evaluate its arguments, and should warn if its argument
4335// has side effects.
4336bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4337 Expr *Arg = TheCall->getArg(0);
4338 if (Arg->isInstantiationDependent()) return false;
4339
4340 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004341 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004342 << Arg->getSourceRange()
4343 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4344
4345 return false;
4346}
4347
David Majnemer86b1bfa2016-10-31 18:07:57 +00004348/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004349/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4350/// than 8.
4351bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4352 // The alignment must be a constant integer.
4353 Expr *Arg = TheCall->getArg(1);
4354
4355 // We can't check the value of a dependent argument.
4356 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004357 if (const auto *UE =
4358 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4359 if (UE->getKind() == UETT_AlignOf)
4360 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4361 << Arg->getSourceRange();
4362
David Majnemer51169932016-10-31 05:37:48 +00004363 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4364
4365 if (!Result.isPowerOf2())
4366 return Diag(TheCall->getLocStart(),
4367 diag::err_alignment_not_power_of_two)
4368 << Arg->getSourceRange();
4369
4370 if (Result < Context.getCharWidth())
4371 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4372 << (unsigned)Context.getCharWidth()
4373 << Arg->getSourceRange();
4374
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004375 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004376 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004377 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004378 << Arg->getSourceRange();
4379 }
4380
4381 return false;
4382}
4383
4384/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004385/// as (const void*, size_t, ...) and can take one optional constant int arg.
4386bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4387 unsigned NumArgs = TheCall->getNumArgs();
4388
4389 if (NumArgs > 3)
4390 return Diag(TheCall->getLocEnd(),
4391 diag::err_typecheck_call_too_many_args_at_most)
4392 << 0 /*function call*/ << 3 << NumArgs
4393 << TheCall->getSourceRange();
4394
4395 // The alignment must be a constant integer.
4396 Expr *Arg = TheCall->getArg(1);
4397
4398 // We can't check the value of a dependent argument.
4399 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4400 llvm::APSInt Result;
4401 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4402 return true;
4403
4404 if (!Result.isPowerOf2())
4405 return Diag(TheCall->getLocStart(),
4406 diag::err_alignment_not_power_of_two)
4407 << Arg->getSourceRange();
4408 }
4409
4410 if (NumArgs > 2) {
4411 ExprResult Arg(TheCall->getArg(2));
4412 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4413 Context.getSizeType(), false);
4414 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4415 if (Arg.isInvalid()) return true;
4416 TheCall->setArg(2, Arg.get());
4417 }
Hal Finkelf0417332014-07-17 14:25:55 +00004418
4419 return false;
4420}
4421
Mehdi Amini06d367c2016-10-24 20:39:34 +00004422bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4423 unsigned BuiltinID =
4424 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4425 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4426
4427 unsigned NumArgs = TheCall->getNumArgs();
4428 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4429 if (NumArgs < NumRequiredArgs) {
4430 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4431 << 0 /* function call */ << NumRequiredArgs << NumArgs
4432 << TheCall->getSourceRange();
4433 }
4434 if (NumArgs >= NumRequiredArgs + 0x100) {
4435 return Diag(TheCall->getLocEnd(),
4436 diag::err_typecheck_call_too_many_args_at_most)
4437 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4438 << TheCall->getSourceRange();
4439 }
4440 unsigned i = 0;
4441
4442 // For formatting call, check buffer arg.
4443 if (!IsSizeCall) {
4444 ExprResult Arg(TheCall->getArg(i));
4445 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4446 Context, Context.VoidPtrTy, false);
4447 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4448 if (Arg.isInvalid())
4449 return true;
4450 TheCall->setArg(i, Arg.get());
4451 i++;
4452 }
4453
4454 // Check string literal arg.
4455 unsigned FormatIdx = i;
4456 {
4457 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4458 if (Arg.isInvalid())
4459 return true;
4460 TheCall->setArg(i, Arg.get());
4461 i++;
4462 }
4463
4464 // Make sure variadic args are scalar.
4465 unsigned FirstDataArg = i;
4466 while (i < NumArgs) {
4467 ExprResult Arg = DefaultVariadicArgumentPromotion(
4468 TheCall->getArg(i), VariadicFunction, nullptr);
4469 if (Arg.isInvalid())
4470 return true;
4471 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4472 if (ArgSize.getQuantity() >= 0x100) {
4473 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4474 << i << (int)ArgSize.getQuantity() << 0xff
4475 << TheCall->getSourceRange();
4476 }
4477 TheCall->setArg(i, Arg.get());
4478 i++;
4479 }
4480
4481 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4482 // call to avoid duplicate diagnostics.
4483 if (!IsSizeCall) {
4484 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4485 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4486 bool Success = CheckFormatArguments(
4487 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4488 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4489 CheckedVarArgs);
4490 if (!Success)
4491 return true;
4492 }
4493
4494 if (IsSizeCall) {
4495 TheCall->setType(Context.getSizeType());
4496 } else {
4497 TheCall->setType(Context.VoidPtrTy);
4498 }
4499 return false;
4500}
4501
Eric Christopher8d0c6212010-04-17 02:26:23 +00004502/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4503/// TheCall is a constant expression.
4504bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4505 llvm::APSInt &Result) {
4506 Expr *Arg = TheCall->getArg(ArgNum);
4507 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4508 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4509
4510 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4511
4512 if (!Arg->isIntegerConstantExpr(Result, Context))
4513 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004514 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004515
Chris Lattnerd545ad12009-09-23 06:06:36 +00004516 return false;
4517}
4518
Richard Sandiford28940af2014-04-16 08:47:51 +00004519/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4520/// TheCall is a constant expression in the range [Low, High].
4521bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4522 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004523 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004524
4525 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004526 Expr *Arg = TheCall->getArg(ArgNum);
4527 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004528 return false;
4529
Eric Christopher8d0c6212010-04-17 02:26:23 +00004530 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004531 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004532 return true;
4533
Richard Sandiford28940af2014-04-16 08:47:51 +00004534 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004535 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004536 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004537
4538 return false;
4539}
4540
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004541/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4542/// TheCall is a constant expression is a multiple of Num..
4543bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4544 unsigned Num) {
4545 llvm::APSInt Result;
4546
4547 // We can't check the value of a dependent argument.
4548 Expr *Arg = TheCall->getArg(ArgNum);
4549 if (Arg->isTypeDependent() || Arg->isValueDependent())
4550 return false;
4551
4552 // Check constant-ness first.
4553 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4554 return true;
4555
4556 if (Result.getSExtValue() % Num != 0)
4557 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4558 << Num << Arg->getSourceRange();
4559
4560 return false;
4561}
4562
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004563/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4564/// TheCall is an ARM/AArch64 special register string literal.
4565bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4566 int ArgNum, unsigned ExpectedFieldNum,
4567 bool AllowName) {
4568 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4569 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4570 BuiltinID == ARM::BI__builtin_arm_rsr ||
4571 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4572 BuiltinID == ARM::BI__builtin_arm_wsr ||
4573 BuiltinID == ARM::BI__builtin_arm_wsrp;
4574 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4575 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4576 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4577 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4578 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4579 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4580 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4581
4582 // We can't check the value of a dependent argument.
4583 Expr *Arg = TheCall->getArg(ArgNum);
4584 if (Arg->isTypeDependent() || Arg->isValueDependent())
4585 return false;
4586
4587 // Check if the argument is a string literal.
4588 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4589 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4590 << Arg->getSourceRange();
4591
4592 // Check the type of special register given.
4593 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4594 SmallVector<StringRef, 6> Fields;
4595 Reg.split(Fields, ":");
4596
4597 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4598 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4599 << Arg->getSourceRange();
4600
4601 // If the string is the name of a register then we cannot check that it is
4602 // valid here but if the string is of one the forms described in ACLE then we
4603 // can check that the supplied fields are integers and within the valid
4604 // ranges.
4605 if (Fields.size() > 1) {
4606 bool FiveFields = Fields.size() == 5;
4607
4608 bool ValidString = true;
4609 if (IsARMBuiltin) {
4610 ValidString &= Fields[0].startswith_lower("cp") ||
4611 Fields[0].startswith_lower("p");
4612 if (ValidString)
4613 Fields[0] =
4614 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4615
4616 ValidString &= Fields[2].startswith_lower("c");
4617 if (ValidString)
4618 Fields[2] = Fields[2].drop_front(1);
4619
4620 if (FiveFields) {
4621 ValidString &= Fields[3].startswith_lower("c");
4622 if (ValidString)
4623 Fields[3] = Fields[3].drop_front(1);
4624 }
4625 }
4626
4627 SmallVector<int, 5> Ranges;
4628 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004629 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004630 else
4631 Ranges.append({15, 7, 15});
4632
4633 for (unsigned i=0; i<Fields.size(); ++i) {
4634 int IntField;
4635 ValidString &= !Fields[i].getAsInteger(10, IntField);
4636 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4637 }
4638
4639 if (!ValidString)
4640 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4641 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004642 } else if (IsAArch64Builtin && Fields.size() == 1) {
4643 // If the register name is one of those that appear in the condition below
4644 // and the special register builtin being used is one of the write builtins,
4645 // then we require that the argument provided for writing to the register
4646 // is an integer constant expression. This is because it will be lowered to
4647 // an MSR (immediate) instruction, so we need to know the immediate at
4648 // compile time.
4649 if (TheCall->getNumArgs() != 2)
4650 return false;
4651
4652 std::string RegLower = Reg.lower();
4653 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4654 RegLower != "pan" && RegLower != "uao")
4655 return false;
4656
4657 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4658 }
4659
4660 return false;
4661}
4662
Eli Friedmanc97d0142009-05-03 06:04:26 +00004663/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004664/// This checks that the target supports __builtin_longjmp and
4665/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004666bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004667 if (!Context.getTargetInfo().hasSjLjLowering())
4668 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4669 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4670
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004671 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004672 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004673
Eric Christopher8d0c6212010-04-17 02:26:23 +00004674 // TODO: This is less than ideal. Overload this to take a value.
4675 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4676 return true;
4677
4678 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004679 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4680 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4681
4682 return false;
4683}
4684
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004685/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4686/// This checks that the target supports __builtin_setjmp.
4687bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4688 if (!Context.getTargetInfo().hasSjLjLowering())
4689 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4690 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4691 return false;
4692}
4693
Richard Smithd7293d72013-08-05 18:49:43 +00004694namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004695
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004696class UncoveredArgHandler {
4697 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004698
4699 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004700 SmallVector<const Expr *, 4> DiagnosticExprs;
4701
4702public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004703 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004704
4705 bool hasUncoveredArg() const {
4706 return (FirstUncoveredArg >= 0);
4707 }
4708
4709 unsigned getUncoveredArg() const {
4710 assert(hasUncoveredArg() && "no uncovered argument");
4711 return FirstUncoveredArg;
4712 }
4713
4714 void setAllCovered() {
4715 // A string has been found with all arguments covered, so clear out
4716 // the diagnostics.
4717 DiagnosticExprs.clear();
4718 FirstUncoveredArg = AllCovered;
4719 }
4720
4721 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4722 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4723
4724 // Don't update if a previous string covers all arguments.
4725 if (FirstUncoveredArg == AllCovered)
4726 return;
4727
4728 // UncoveredArgHandler tracks the highest uncovered argument index
4729 // and with it all the strings that match this index.
4730 if (NewFirstUncoveredArg == FirstUncoveredArg)
4731 DiagnosticExprs.push_back(StrExpr);
4732 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4733 DiagnosticExprs.clear();
4734 DiagnosticExprs.push_back(StrExpr);
4735 FirstUncoveredArg = NewFirstUncoveredArg;
4736 }
4737 }
4738
4739 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4740};
4741
Richard Smithd7293d72013-08-05 18:49:43 +00004742enum StringLiteralCheckType {
4743 SLCT_NotALiteral,
4744 SLCT_UncheckedLiteral,
4745 SLCT_CheckedLiteral
4746};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004747
4748} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004749
Stephen Hines648c3692016-09-16 01:07:04 +00004750static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4751 BinaryOperatorKind BinOpKind,
4752 bool AddendIsRight) {
4753 unsigned BitWidth = Offset.getBitWidth();
4754 unsigned AddendBitWidth = Addend.getBitWidth();
4755 // There might be negative interim results.
4756 if (Addend.isUnsigned()) {
4757 Addend = Addend.zext(++AddendBitWidth);
4758 Addend.setIsSigned(true);
4759 }
4760 // Adjust the bit width of the APSInts.
4761 if (AddendBitWidth > BitWidth) {
4762 Offset = Offset.sext(AddendBitWidth);
4763 BitWidth = AddendBitWidth;
4764 } else if (BitWidth > AddendBitWidth) {
4765 Addend = Addend.sext(BitWidth);
4766 }
4767
4768 bool Ov = false;
4769 llvm::APSInt ResOffset = Offset;
4770 if (BinOpKind == BO_Add)
4771 ResOffset = Offset.sadd_ov(Addend, Ov);
4772 else {
4773 assert(AddendIsRight && BinOpKind == BO_Sub &&
4774 "operator must be add or sub with addend on the right");
4775 ResOffset = Offset.ssub_ov(Addend, Ov);
4776 }
4777
4778 // We add an offset to a pointer here so we should support an offset as big as
4779 // possible.
4780 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004781 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4782 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004783 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004784 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4785 return;
4786 }
4787
4788 Offset = ResOffset;
4789}
4790
4791namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004792
Stephen Hines648c3692016-09-16 01:07:04 +00004793// This is a wrapper class around StringLiteral to support offsetted string
4794// literals as format strings. It takes the offset into account when returning
4795// the string and its length or the source locations to display notes correctly.
4796class FormatStringLiteral {
4797 const StringLiteral *FExpr;
4798 int64_t Offset;
4799
4800 public:
4801 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4802 : FExpr(fexpr), Offset(Offset) {}
4803
4804 StringRef getString() const {
4805 return FExpr->getString().drop_front(Offset);
4806 }
4807
4808 unsigned getByteLength() const {
4809 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4810 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004811
Stephen Hines648c3692016-09-16 01:07:04 +00004812 unsigned getLength() const { return FExpr->getLength() - Offset; }
4813 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4814
4815 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4816
4817 QualType getType() const { return FExpr->getType(); }
4818
4819 bool isAscii() const { return FExpr->isAscii(); }
4820 bool isWide() const { return FExpr->isWide(); }
4821 bool isUTF8() const { return FExpr->isUTF8(); }
4822 bool isUTF16() const { return FExpr->isUTF16(); }
4823 bool isUTF32() const { return FExpr->isUTF32(); }
4824 bool isPascal() const { return FExpr->isPascal(); }
4825
4826 SourceLocation getLocationOfByte(
4827 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4828 const TargetInfo &Target, unsigned *StartToken = nullptr,
4829 unsigned *StartTokenByteOffset = nullptr) const {
4830 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4831 StartToken, StartTokenByteOffset);
4832 }
4833
4834 SourceLocation getLocStart() const LLVM_READONLY {
4835 return FExpr->getLocStart().getLocWithOffset(Offset);
4836 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004837
Stephen Hines648c3692016-09-16 01:07:04 +00004838 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4839};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004840
4841} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004842
4843static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004844 const Expr *OrigFormatExpr,
4845 ArrayRef<const Expr *> Args,
4846 bool HasVAListArg, unsigned format_idx,
4847 unsigned firstDataArg,
4848 Sema::FormatStringType Type,
4849 bool inFunctionCall,
4850 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004851 llvm::SmallBitVector &CheckedVarArgs,
4852 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004853
Richard Smith55ce3522012-06-25 20:30:08 +00004854// Determine if an expression is a string literal or constant string.
4855// If this function returns false on the arguments to a function expecting a
4856// format string, we will usually need to emit a warning.
4857// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004858static StringLiteralCheckType
4859checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4860 bool HasVAListArg, unsigned format_idx,
4861 unsigned firstDataArg, Sema::FormatStringType Type,
4862 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004863 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004864 UncoveredArgHandler &UncoveredArg,
4865 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004866 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004867 assert(Offset.isSigned() && "invalid offset");
4868
Douglas Gregorc25f7662009-05-19 22:10:17 +00004869 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004870 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004871
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004872 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004873
Richard Smithd7293d72013-08-05 18:49:43 +00004874 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004875 // Technically -Wformat-nonliteral does not warn about this case.
4876 // The behavior of printf and friends in this case is implementation
4877 // dependent. Ideally if the format string cannot be null then
4878 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004879 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004880
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004881 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004882 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004883 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004884 // The expression is a literal if both sub-expressions were, and it was
4885 // completely checked only if both sub-expressions were checked.
4886 const AbstractConditionalOperator *C =
4887 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004888
4889 // Determine whether it is necessary to check both sub-expressions, for
4890 // example, because the condition expression is a constant that can be
4891 // evaluated at compile time.
4892 bool CheckLeft = true, CheckRight = true;
4893
4894 bool Cond;
4895 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4896 if (Cond)
4897 CheckRight = false;
4898 else
4899 CheckLeft = false;
4900 }
4901
Stephen Hines648c3692016-09-16 01:07:04 +00004902 // We need to maintain the offsets for the right and the left hand side
4903 // separately to check if every possible indexed expression is a valid
4904 // string literal. They might have different offsets for different string
4905 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004906 StringLiteralCheckType Left;
4907 if (!CheckLeft)
4908 Left = SLCT_UncheckedLiteral;
4909 else {
4910 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4911 HasVAListArg, format_idx, firstDataArg,
4912 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004913 CheckedVarArgs, UncoveredArg, Offset);
4914 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004915 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004916 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004917 }
4918
Richard Smith55ce3522012-06-25 20:30:08 +00004919 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004920 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004921 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004922 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004923 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004924
4925 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004926 }
4927
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004928 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004929 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4930 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004931
John McCallc07a0c72011-02-17 10:25:35 +00004932 case Stmt::OpaqueValueExprClass:
4933 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4934 E = src;
4935 goto tryAgain;
4936 }
Richard Smith55ce3522012-06-25 20:30:08 +00004937 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004938
Ted Kremeneka8890832011-02-24 23:03:04 +00004939 case Stmt::PredefinedExprClass:
4940 // While __func__, etc., are technically not string literals, they
4941 // cannot contain format specifiers and thus are not a security
4942 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004943 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004944
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004945 case Stmt::DeclRefExprClass: {
4946 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004947
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004948 // As an exception, do not flag errors for variables binding to
4949 // const string literals.
4950 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4951 bool isConstant = false;
4952 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004953
Richard Smithd7293d72013-08-05 18:49:43 +00004954 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4955 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00004956 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00004957 isConstant = T.isConstant(S.Context) &&
4958 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00004959 } else if (T->isObjCObjectPointerType()) {
4960 // In ObjC, there is usually no "const ObjectPointer" type,
4961 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00004962 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004963 }
Mike Stump11289f42009-09-09 15:08:12 +00004964
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004965 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004966 if (const Expr *Init = VD->getAnyInitializer()) {
4967 // Look through initializers like const char c[] = { "foo" }
4968 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4969 if (InitList->isStringLiteralInit())
4970 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4971 }
Richard Smithd7293d72013-08-05 18:49:43 +00004972 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004973 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004974 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00004975 /*InFunctionCall*/ false, CheckedVarArgs,
4976 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00004977 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004978 }
Mike Stump11289f42009-09-09 15:08:12 +00004979
Anders Carlssonb012ca92009-06-28 19:55:58 +00004980 // For vprintf* functions (i.e., HasVAListArg==true), we add a
4981 // special check to see if the format string is a function parameter
4982 // of the function calling the printf function. If the function
4983 // has an attribute indicating it is a printf-like function, then we
4984 // should suppress warnings concerning non-literals being used in a call
4985 // to a vprintf function. For example:
4986 //
4987 // void
4988 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4989 // va_list ap;
4990 // va_start(ap, fmt);
4991 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
4992 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00004993 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004994 if (HasVAListArg) {
4995 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4996 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4997 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004998 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00004999 // adjust for implicit parameter
5000 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5001 if (MD->isInstance())
5002 ++PVIndex;
5003 // We also check if the formats are compatible.
5004 // We can't pass a 'scanf' string to a 'printf' function.
5005 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005006 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005007 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005008 }
5009 }
5010 }
5011 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005012 }
Mike Stump11289f42009-09-09 15:08:12 +00005013
Richard Smith55ce3522012-06-25 20:30:08 +00005014 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005015 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005016
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005017 case Stmt::CallExprClass:
5018 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005019 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005020 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5021 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5022 unsigned ArgIndex = FA->getFormatIdx();
5023 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5024 if (MD->isInstance())
5025 --ArgIndex;
5026 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00005027
Richard Smithd7293d72013-08-05 18:49:43 +00005028 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005029 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005030 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005031 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005032 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5033 unsigned BuiltinID = FD->getBuiltinID();
5034 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5035 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5036 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005037 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005038 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005039 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005040 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005041 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005042 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005043 }
5044 }
Mike Stump11289f42009-09-09 15:08:12 +00005045
Richard Smith55ce3522012-06-25 20:30:08 +00005046 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005047 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005048 case Stmt::ObjCMessageExprClass: {
5049 const auto *ME = cast<ObjCMessageExpr>(E);
5050 if (const auto *ND = ME->getMethodDecl()) {
5051 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5052 unsigned ArgIndex = FA->getFormatIdx();
5053 const Expr *Arg = ME->getArg(ArgIndex - 1);
5054 return checkFormatStringExpr(
5055 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5056 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5057 }
5058 }
5059
5060 return SLCT_NotALiteral;
5061 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005062 case Stmt::ObjCStringLiteralClass:
5063 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005064 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005065
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005066 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005067 StrE = ObjCFExpr->getString();
5068 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005069 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005070
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005071 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005072 if (Offset.isNegative() || Offset > StrE->getLength()) {
5073 // TODO: It would be better to have an explicit warning for out of
5074 // bounds literals.
5075 return SLCT_NotALiteral;
5076 }
5077 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5078 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005079 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005080 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005081 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005082 }
Mike Stump11289f42009-09-09 15:08:12 +00005083
Richard Smith55ce3522012-06-25 20:30:08 +00005084 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005085 }
Stephen Hines648c3692016-09-16 01:07:04 +00005086 case Stmt::BinaryOperatorClass: {
5087 llvm::APSInt LResult;
5088 llvm::APSInt RResult;
5089
5090 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5091
5092 // A string literal + an int offset is still a string literal.
5093 if (BinOp->isAdditiveOp()) {
5094 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5095 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5096
5097 if (LIsInt != RIsInt) {
5098 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5099
5100 if (LIsInt) {
5101 if (BinOpKind == BO_Add) {
5102 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5103 E = BinOp->getRHS();
5104 goto tryAgain;
5105 }
5106 } else {
5107 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5108 E = BinOp->getLHS();
5109 goto tryAgain;
5110 }
5111 }
Stephen Hines648c3692016-09-16 01:07:04 +00005112 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005113
5114 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005115 }
5116 case Stmt::UnaryOperatorClass: {
5117 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5118 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005119 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005120 llvm::APSInt IndexResult;
5121 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5122 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5123 E = ASE->getBase();
5124 goto tryAgain;
5125 }
5126 }
5127
5128 return SLCT_NotALiteral;
5129 }
Mike Stump11289f42009-09-09 15:08:12 +00005130
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005131 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005132 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005133 }
5134}
5135
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005136Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005137 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005138 .Case("scanf", FST_Scanf)
5139 .Cases("printf", "printf0", FST_Printf)
5140 .Cases("NSString", "CFString", FST_NSString)
5141 .Case("strftime", FST_Strftime)
5142 .Case("strfmon", FST_Strfmon)
5143 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5144 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5145 .Case("os_trace", FST_OSLog)
5146 .Case("os_log", FST_OSLog)
5147 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005148}
5149
Jordan Rose3e0ec582012-07-19 18:10:23 +00005150/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005151/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005152/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005153bool Sema::CheckFormatArguments(const FormatAttr *Format,
5154 ArrayRef<const Expr *> Args,
5155 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005156 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005157 SourceLocation Loc, SourceRange Range,
5158 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005159 FormatStringInfo FSI;
5160 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005161 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005162 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005163 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005164 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005165}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005166
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005167bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005168 bool HasVAListArg, unsigned format_idx,
5169 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005170 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005171 SourceLocation Loc, SourceRange Range,
5172 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005173 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005174 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005175 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005176 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005177 }
Mike Stump11289f42009-09-09 15:08:12 +00005178
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005179 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005180
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005181 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005182 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005183 // Dynamically generated format strings are difficult to
5184 // automatically vet at compile time. Requiring that format strings
5185 // are string literals: (1) permits the checking of format strings by
5186 // the compiler and thereby (2) can practically remove the source of
5187 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005188
Mike Stump11289f42009-09-09 15:08:12 +00005189 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005190 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005191 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005192 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005193 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005194 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005195 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5196 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005197 /*IsFunctionCall*/ true, CheckedVarArgs,
5198 UncoveredArg,
5199 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005200
5201 // Generate a diagnostic where an uncovered argument is detected.
5202 if (UncoveredArg.hasUncoveredArg()) {
5203 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5204 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5205 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5206 }
5207
Richard Smith55ce3522012-06-25 20:30:08 +00005208 if (CT != SLCT_NotALiteral)
5209 // Literal format string found, check done!
5210 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005211
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005212 // Strftime is particular as it always uses a single 'time' argument,
5213 // so it is safe to pass a non-literal string.
5214 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005215 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005216
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005217 // Do not emit diag when the string param is a macro expansion and the
5218 // format is either NSString or CFString. This is a hack to prevent
5219 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5220 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005221 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5222 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005223 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005224
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005225 // If there are no arguments specified, warn with -Wformat-security, otherwise
5226 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005227 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005228 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5229 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005230 switch (Type) {
5231 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005232 break;
5233 case FST_Kprintf:
5234 case FST_FreeBSDKPrintf:
5235 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005236 Diag(FormatLoc, diag::note_format_security_fixit)
5237 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005238 break;
5239 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005240 Diag(FormatLoc, diag::note_format_security_fixit)
5241 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005242 break;
5243 }
5244 } else {
5245 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005246 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005247 }
Richard Smith55ce3522012-06-25 20:30:08 +00005248 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005249}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005250
Ted Kremenekab278de2010-01-28 23:39:18 +00005251namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005252
Ted Kremenek02087932010-07-16 02:11:22 +00005253class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5254protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005255 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005256 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005257 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005258 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005259 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005260 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005261 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005262 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005263 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005264 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005265 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005266 bool usesPositionalArgs = false;
5267 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005268 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005269 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005270 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005271 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005272
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005273public:
Stephen Hines648c3692016-09-16 01:07:04 +00005274 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005275 const Expr *origFormatExpr,
5276 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005277 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005278 ArrayRef<const Expr *> Args, unsigned formatIdx,
5279 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005280 llvm::SmallBitVector &CheckedVarArgs,
5281 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005282 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5283 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5284 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005285 inFunctionCall(inFunctionCall), CallType(callType),
5286 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005287 CoveredArgs.resize(numDataArgs);
5288 CoveredArgs.reset();
5289 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005290
Ted Kremenek019d2242010-01-29 01:50:07 +00005291 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005292
Ted Kremenek02087932010-07-16 02:11:22 +00005293 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005294 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005295
Jordan Rose92303592012-09-08 04:00:03 +00005296 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005297 const analyze_format_string::FormatSpecifier &FS,
5298 const analyze_format_string::ConversionSpecifier &CS,
5299 const char *startSpecifier, unsigned specifierLen,
5300 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005301
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005302 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005303 const analyze_format_string::FormatSpecifier &FS,
5304 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005305
5306 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005307 const analyze_format_string::ConversionSpecifier &CS,
5308 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005309
Craig Toppere14c0f82014-03-12 04:55:44 +00005310 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005311
Craig Toppere14c0f82014-03-12 04:55:44 +00005312 void HandleInvalidPosition(const char *startSpecifier,
5313 unsigned specifierLen,
5314 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005315
Craig Toppere14c0f82014-03-12 04:55:44 +00005316 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005317
Craig Toppere14c0f82014-03-12 04:55:44 +00005318 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005319
Richard Trieu03cf7b72011-10-28 00:41:25 +00005320 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005321 static void
5322 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5323 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5324 bool IsStringLocation, Range StringRange,
5325 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005326
Ted Kremenek02087932010-07-16 02:11:22 +00005327protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005328 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5329 const char *startSpec,
5330 unsigned specifierLen,
5331 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005332
5333 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5334 const char *startSpec,
5335 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005336
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005337 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005338 CharSourceRange getSpecifierRange(const char *startSpecifier,
5339 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005340 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005341
Ted Kremenek5739de72010-01-29 01:06:55 +00005342 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005343
5344 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5345 const analyze_format_string::ConversionSpecifier &CS,
5346 const char *startSpecifier, unsigned specifierLen,
5347 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005348
5349 template <typename Range>
5350 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5351 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005352 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005353};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005354
5355} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005356
Ted Kremenek02087932010-07-16 02:11:22 +00005357SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005358 return OrigFormatExpr->getSourceRange();
5359}
5360
Ted Kremenek02087932010-07-16 02:11:22 +00005361CharSourceRange CheckFormatHandler::
5362getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005363 SourceLocation Start = getLocationOfByte(startSpecifier);
5364 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5365
5366 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005367 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005368
5369 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005370}
5371
Ted Kremenek02087932010-07-16 02:11:22 +00005372SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005373 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5374 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005375}
5376
Ted Kremenek02087932010-07-16 02:11:22 +00005377void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5378 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005379 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5380 getLocationOfByte(startSpecifier),
5381 /*IsStringLocation*/true,
5382 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005383}
5384
Jordan Rose92303592012-09-08 04:00:03 +00005385void CheckFormatHandler::HandleInvalidLengthModifier(
5386 const analyze_format_string::FormatSpecifier &FS,
5387 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005388 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005389 using namespace analyze_format_string;
5390
5391 const LengthModifier &LM = FS.getLengthModifier();
5392 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5393
5394 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005395 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005396 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005397 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005398 getLocationOfByte(LM.getStart()),
5399 /*IsStringLocation*/true,
5400 getSpecifierRange(startSpecifier, specifierLen));
5401
5402 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5403 << FixedLM->toString()
5404 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5405
5406 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005407 FixItHint Hint;
5408 if (DiagID == diag::warn_format_nonsensical_length)
5409 Hint = FixItHint::CreateRemoval(LMRange);
5410
5411 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005412 getLocationOfByte(LM.getStart()),
5413 /*IsStringLocation*/true,
5414 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005415 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005416 }
5417}
5418
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005419void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005420 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005421 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005422 using namespace analyze_format_string;
5423
5424 const LengthModifier &LM = FS.getLengthModifier();
5425 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5426
5427 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005428 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005429 if (FixedLM) {
5430 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5431 << LM.toString() << 0,
5432 getLocationOfByte(LM.getStart()),
5433 /*IsStringLocation*/true,
5434 getSpecifierRange(startSpecifier, specifierLen));
5435
5436 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5437 << FixedLM->toString()
5438 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5439
5440 } else {
5441 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5442 << LM.toString() << 0,
5443 getLocationOfByte(LM.getStart()),
5444 /*IsStringLocation*/true,
5445 getSpecifierRange(startSpecifier, specifierLen));
5446 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005447}
5448
5449void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5450 const analyze_format_string::ConversionSpecifier &CS,
5451 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005452 using namespace analyze_format_string;
5453
5454 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005455 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005456 if (FixedCS) {
5457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5458 << CS.toString() << /*conversion specifier*/1,
5459 getLocationOfByte(CS.getStart()),
5460 /*IsStringLocation*/true,
5461 getSpecifierRange(startSpecifier, specifierLen));
5462
5463 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5464 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5465 << FixedCS->toString()
5466 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5467 } else {
5468 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5469 << CS.toString() << /*conversion specifier*/1,
5470 getLocationOfByte(CS.getStart()),
5471 /*IsStringLocation*/true,
5472 getSpecifierRange(startSpecifier, specifierLen));
5473 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005474}
5475
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005476void CheckFormatHandler::HandlePosition(const char *startPos,
5477 unsigned posLen) {
5478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5479 getLocationOfByte(startPos),
5480 /*IsStringLocation*/true,
5481 getSpecifierRange(startPos, posLen));
5482}
5483
Ted Kremenekd1668192010-02-27 01:41:03 +00005484void
Ted Kremenek02087932010-07-16 02:11:22 +00005485CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5486 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005487 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5488 << (unsigned) p,
5489 getLocationOfByte(startPos), /*IsStringLocation*/true,
5490 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005491}
5492
Ted Kremenek02087932010-07-16 02:11:22 +00005493void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005494 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005495 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5496 getLocationOfByte(startPos),
5497 /*IsStringLocation*/true,
5498 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005499}
5500
Ted Kremenek02087932010-07-16 02:11:22 +00005501void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005502 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005503 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005504 EmitFormatDiagnostic(
5505 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5506 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5507 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005508 }
Ted Kremenek02087932010-07-16 02:11:22 +00005509}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005510
Jordan Rose58bbe422012-07-19 18:10:08 +00005511// Note that this may return NULL if there was an error parsing or building
5512// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005513const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005514 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005515}
5516
5517void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005518 // Does the number of data arguments exceed the number of
5519 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005520 if (!HasVAListArg) {
5521 // Find any arguments that weren't covered.
5522 CoveredArgs.flip();
5523 signed notCoveredArg = CoveredArgs.find_first();
5524 if (notCoveredArg >= 0) {
5525 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005526 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5527 } else {
5528 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005529 }
5530 }
5531}
5532
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005533void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5534 const Expr *ArgExpr) {
5535 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5536 "Invalid state");
5537
5538 if (!ArgExpr)
5539 return;
5540
5541 SourceLocation Loc = ArgExpr->getLocStart();
5542
5543 if (S.getSourceManager().isInSystemMacro(Loc))
5544 return;
5545
5546 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5547 for (auto E : DiagnosticExprs)
5548 PDiag << E->getSourceRange();
5549
5550 CheckFormatHandler::EmitFormatDiagnostic(
5551 S, IsFunctionCall, DiagnosticExprs[0],
5552 PDiag, Loc, /*IsStringLocation*/false,
5553 DiagnosticExprs[0]->getSourceRange());
5554}
5555
Ted Kremenekce815422010-07-19 21:25:57 +00005556bool
5557CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5558 SourceLocation Loc,
5559 const char *startSpec,
5560 unsigned specifierLen,
5561 const char *csStart,
5562 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005563 bool keepGoing = true;
5564 if (argIndex < NumDataArgs) {
5565 // Consider the argument coverered, even though the specifier doesn't
5566 // make sense.
5567 CoveredArgs.set(argIndex);
5568 }
5569 else {
5570 // If argIndex exceeds the number of data arguments we
5571 // don't issue a warning because that is just a cascade of warnings (and
5572 // they may have intended '%%' anyway). We don't want to continue processing
5573 // the format string after this point, however, as we will like just get
5574 // gibberish when trying to match arguments.
5575 keepGoing = false;
5576 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005577
5578 StringRef Specifier(csStart, csLen);
5579
5580 // If the specifier in non-printable, it could be the first byte of a UTF-8
5581 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5582 // hex value.
5583 std::string CodePointStr;
5584 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005585 llvm::UTF32 CodePoint;
5586 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5587 const llvm::UTF8 *E =
5588 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5589 llvm::ConversionResult Result =
5590 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005591
Justin Lebar90910552016-09-30 00:38:45 +00005592 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005593 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005594 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005595 }
5596
5597 llvm::raw_string_ostream OS(CodePointStr);
5598 if (CodePoint < 256)
5599 OS << "\\x" << llvm::format("%02x", CodePoint);
5600 else if (CodePoint <= 0xFFFF)
5601 OS << "\\u" << llvm::format("%04x", CodePoint);
5602 else
5603 OS << "\\U" << llvm::format("%08x", CodePoint);
5604 OS.flush();
5605 Specifier = CodePointStr;
5606 }
5607
5608 EmitFormatDiagnostic(
5609 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5610 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5611
Ted Kremenekce815422010-07-19 21:25:57 +00005612 return keepGoing;
5613}
5614
Richard Trieu03cf7b72011-10-28 00:41:25 +00005615void
5616CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5617 const char *startSpec,
5618 unsigned specifierLen) {
5619 EmitFormatDiagnostic(
5620 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5621 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5622}
5623
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005624bool
5625CheckFormatHandler::CheckNumArgs(
5626 const analyze_format_string::FormatSpecifier &FS,
5627 const analyze_format_string::ConversionSpecifier &CS,
5628 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5629
5630 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005631 PartialDiagnostic PDiag = FS.usesPositionalArg()
5632 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5633 << (argIndex+1) << NumDataArgs)
5634 : S.PDiag(diag::warn_printf_insufficient_data_args);
5635 EmitFormatDiagnostic(
5636 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5637 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005638
5639 // Since more arguments than conversion tokens are given, by extension
5640 // all arguments are covered, so mark this as so.
5641 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005642 return false;
5643 }
5644 return true;
5645}
5646
Richard Trieu03cf7b72011-10-28 00:41:25 +00005647template<typename Range>
5648void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5649 SourceLocation Loc,
5650 bool IsStringLocation,
5651 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005652 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005653 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005654 Loc, IsStringLocation, StringRange, FixIt);
5655}
5656
5657/// \brief If the format string is not within the funcion call, emit a note
5658/// so that the function call and string are in diagnostic messages.
5659///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005660/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005661/// call and only one diagnostic message will be produced. Otherwise, an
5662/// extra note will be emitted pointing to location of the format string.
5663///
5664/// \param ArgumentExpr the expression that is passed as the format string
5665/// argument in the function call. Used for getting locations when two
5666/// diagnostics are emitted.
5667///
5668/// \param PDiag the callee should already have provided any strings for the
5669/// diagnostic message. This function only adds locations and fixits
5670/// to diagnostics.
5671///
5672/// \param Loc primary location for diagnostic. If two diagnostics are
5673/// required, one will be at Loc and a new SourceLocation will be created for
5674/// the other one.
5675///
5676/// \param IsStringLocation if true, Loc points to the format string should be
5677/// used for the note. Otherwise, Loc points to the argument list and will
5678/// be used with PDiag.
5679///
5680/// \param StringRange some or all of the string to highlight. This is
5681/// templated so it can accept either a CharSourceRange or a SourceRange.
5682///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005683/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005684template <typename Range>
5685void CheckFormatHandler::EmitFormatDiagnostic(
5686 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5687 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5688 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005689 if (InFunctionCall) {
5690 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5691 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005692 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005693 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005694 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5695 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005696
5697 const Sema::SemaDiagnosticBuilder &Note =
5698 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5699 diag::note_format_string_defined);
5700
5701 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005702 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005703 }
5704}
5705
Ted Kremenek02087932010-07-16 02:11:22 +00005706//===--- CHECK: Printf format string checking ------------------------------===//
5707
5708namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005709
Ted Kremenek02087932010-07-16 02:11:22 +00005710class CheckPrintfHandler : public CheckFormatHandler {
5711public:
Stephen Hines648c3692016-09-16 01:07:04 +00005712 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005713 const Expr *origFormatExpr,
5714 const Sema::FormatStringType type, unsigned firstDataArg,
5715 unsigned numDataArgs, bool isObjC, const char *beg,
5716 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005717 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005718 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005719 llvm::SmallBitVector &CheckedVarArgs,
5720 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005721 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5722 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5723 inFunctionCall, CallType, CheckedVarArgs,
5724 UncoveredArg) {}
5725
5726 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5727
5728 /// Returns true if '%@' specifiers are allowed in the format string.
5729 bool allowsObjCArg() const {
5730 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5731 FSType == Sema::FST_OSTrace;
5732 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005733
Ted Kremenek02087932010-07-16 02:11:22 +00005734 bool HandleInvalidPrintfConversionSpecifier(
5735 const analyze_printf::PrintfSpecifier &FS,
5736 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005737 unsigned specifierLen) override;
5738
Ted Kremenek02087932010-07-16 02:11:22 +00005739 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5740 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005741 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005742 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5743 const char *StartSpecifier,
5744 unsigned SpecifierLen,
5745 const Expr *E);
5746
Ted Kremenek02087932010-07-16 02:11:22 +00005747 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5748 const char *startSpecifier, unsigned specifierLen);
5749 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5750 const analyze_printf::OptionalAmount &Amt,
5751 unsigned type,
5752 const char *startSpecifier, unsigned specifierLen);
5753 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5754 const analyze_printf::OptionalFlag &flag,
5755 const char *startSpecifier, unsigned specifierLen);
5756 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5757 const analyze_printf::OptionalFlag &ignoredFlag,
5758 const analyze_printf::OptionalFlag &flag,
5759 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005760 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005761 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005762
5763 void HandleEmptyObjCModifierFlag(const char *startFlag,
5764 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005765
Ted Kremenek2b417712015-07-02 05:39:16 +00005766 void HandleInvalidObjCModifierFlag(const char *startFlag,
5767 unsigned flagLen) override;
5768
5769 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5770 const char *flagsEnd,
5771 const char *conversionPosition)
5772 override;
5773};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005774
5775} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005776
5777bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5778 const analyze_printf::PrintfSpecifier &FS,
5779 const char *startSpecifier,
5780 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005781 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005782 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005783
Ted Kremenekce815422010-07-19 21:25:57 +00005784 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5785 getLocationOfByte(CS.getStart()),
5786 startSpecifier, specifierLen,
5787 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005788}
5789
Ted Kremenek02087932010-07-16 02:11:22 +00005790bool CheckPrintfHandler::HandleAmount(
5791 const analyze_format_string::OptionalAmount &Amt,
5792 unsigned k, const char *startSpecifier,
5793 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005794 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005795 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005796 unsigned argIndex = Amt.getArgIndex();
5797 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005798 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5799 << k,
5800 getLocationOfByte(Amt.getStart()),
5801 /*IsStringLocation*/true,
5802 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005803 // Don't do any more checking. We will just emit
5804 // spurious errors.
5805 return false;
5806 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005807
Ted Kremenek5739de72010-01-29 01:06:55 +00005808 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005809 // Although not in conformance with C99, we also allow the argument to be
5810 // an 'unsigned int' as that is a reasonably safe case. GCC also
5811 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005812 CoveredArgs.set(argIndex);
5813 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005814 if (!Arg)
5815 return false;
5816
Ted Kremenek5739de72010-01-29 01:06:55 +00005817 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005818
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005819 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5820 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005821
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005822 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005823 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005824 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005825 << T << Arg->getSourceRange(),
5826 getLocationOfByte(Amt.getStart()),
5827 /*IsStringLocation*/true,
5828 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005829 // Don't do any more checking. We will just emit
5830 // spurious errors.
5831 return false;
5832 }
5833 }
5834 }
5835 return true;
5836}
Ted Kremenek5739de72010-01-29 01:06:55 +00005837
Tom Careb49ec692010-06-17 19:00:27 +00005838void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005839 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005840 const analyze_printf::OptionalAmount &Amt,
5841 unsigned type,
5842 const char *startSpecifier,
5843 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005844 const analyze_printf::PrintfConversionSpecifier &CS =
5845 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005846
Richard Trieu03cf7b72011-10-28 00:41:25 +00005847 FixItHint fixit =
5848 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5849 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5850 Amt.getConstantLength()))
5851 : FixItHint();
5852
5853 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5854 << type << CS.toString(),
5855 getLocationOfByte(Amt.getStart()),
5856 /*IsStringLocation*/true,
5857 getSpecifierRange(startSpecifier, specifierLen),
5858 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005859}
5860
Ted Kremenek02087932010-07-16 02:11:22 +00005861void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005862 const analyze_printf::OptionalFlag &flag,
5863 const char *startSpecifier,
5864 unsigned specifierLen) {
5865 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005866 const analyze_printf::PrintfConversionSpecifier &CS =
5867 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005868 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5869 << flag.toString() << CS.toString(),
5870 getLocationOfByte(flag.getPosition()),
5871 /*IsStringLocation*/true,
5872 getSpecifierRange(startSpecifier, specifierLen),
5873 FixItHint::CreateRemoval(
5874 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005875}
5876
5877void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005878 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005879 const analyze_printf::OptionalFlag &ignoredFlag,
5880 const analyze_printf::OptionalFlag &flag,
5881 const char *startSpecifier,
5882 unsigned specifierLen) {
5883 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005884 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5885 << ignoredFlag.toString() << flag.toString(),
5886 getLocationOfByte(ignoredFlag.getPosition()),
5887 /*IsStringLocation*/true,
5888 getSpecifierRange(startSpecifier, specifierLen),
5889 FixItHint::CreateRemoval(
5890 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005891}
5892
Ted Kremenek2b417712015-07-02 05:39:16 +00005893void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5894 unsigned flagLen) {
5895 // Warn about an empty flag.
5896 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5897 getLocationOfByte(startFlag),
5898 /*IsStringLocation*/true,
5899 getSpecifierRange(startFlag, flagLen));
5900}
5901
5902void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5903 unsigned flagLen) {
5904 // Warn about an invalid flag.
5905 auto Range = getSpecifierRange(startFlag, flagLen);
5906 StringRef flag(startFlag, flagLen);
5907 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5908 getLocationOfByte(startFlag),
5909 /*IsStringLocation*/true,
5910 Range, FixItHint::CreateRemoval(Range));
5911}
5912
5913void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5914 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5915 // Warn about using '[...]' without a '@' conversion.
5916 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5917 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5918 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5919 getLocationOfByte(conversionPosition),
5920 /*IsStringLocation*/true,
5921 Range, FixItHint::CreateRemoval(Range));
5922}
5923
Richard Smith55ce3522012-06-25 20:30:08 +00005924// Determines if the specified is a C++ class or struct containing
5925// a member with the specified name and kind (e.g. a CXXMethodDecl named
5926// "c_str()").
5927template<typename MemberKind>
5928static llvm::SmallPtrSet<MemberKind*, 1>
5929CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5930 const RecordType *RT = Ty->getAs<RecordType>();
5931 llvm::SmallPtrSet<MemberKind*, 1> Results;
5932
5933 if (!RT)
5934 return Results;
5935 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005936 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005937 return Results;
5938
Alp Tokerb6cc5922014-05-03 03:45:55 +00005939 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005940 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005941 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005942
5943 // We just need to include all members of the right kind turned up by the
5944 // filter, at this point.
5945 if (S.LookupQualifiedName(R, RT->getDecl()))
5946 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5947 NamedDecl *decl = (*I)->getUnderlyingDecl();
5948 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5949 Results.insert(FK);
5950 }
5951 return Results;
5952}
5953
Richard Smith2868a732014-02-28 01:36:39 +00005954/// Check if we could call '.c_str()' on an object.
5955///
5956/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5957/// allow the call, or if it would be ambiguous).
5958bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005959 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5960
Richard Smith2868a732014-02-28 01:36:39 +00005961 MethodSet Results =
5962 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5964 MI != ME; ++MI)
5965 if ((*MI)->getMinRequiredArguments() == 0)
5966 return true;
5967 return false;
5968}
5969
Richard Smith55ce3522012-06-25 20:30:08 +00005970// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005971// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00005972// Returns true when a c_str() conversion method is found.
5973bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00005974 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005975 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00005976
5977 MethodSet Results =
5978 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5979
5980 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5981 MI != ME; ++MI) {
5982 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00005983 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00005984 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00005985 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00005986 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00005987 S.Diag(E->getLocStart(), diag::note_printf_c_str)
5988 << "c_str()"
5989 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5990 return true;
5991 }
5992 }
5993
5994 return false;
5995}
5996
Ted Kremenekab278de2010-01-28 23:39:18 +00005997bool
Ted Kremenek02087932010-07-16 02:11:22 +00005998CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00005999 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006000 const char *startSpecifier,
6001 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006002 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006003 using namespace analyze_printf;
6004
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006005 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006006
Ted Kremenek6cd69422010-07-19 22:01:06 +00006007 if (FS.consumesDataArgument()) {
6008 if (atFirstArg) {
6009 atFirstArg = false;
6010 usesPositionalArgs = FS.usesPositionalArg();
6011 }
6012 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006013 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6014 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006015 return false;
6016 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006017 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006018
Ted Kremenekd1668192010-02-27 01:41:03 +00006019 // First check if the field width, precision, and conversion specifier
6020 // have matching data arguments.
6021 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6022 startSpecifier, specifierLen)) {
6023 return false;
6024 }
6025
6026 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6027 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006028 return false;
6029 }
6030
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006031 if (!CS.consumesDataArgument()) {
6032 // FIXME: Technically specifying a precision or field width here
6033 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006034 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006035 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006036
Ted Kremenek4a49d982010-02-26 19:18:41 +00006037 // Consume the argument.
6038 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006039 if (argIndex < NumDataArgs) {
6040 // The check to see if the argIndex is valid will come later.
6041 // We set the bit here because we may exit early from this
6042 // function if we encounter some other error.
6043 CoveredArgs.set(argIndex);
6044 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006045
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006046 // FreeBSD kernel extensions.
6047 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6048 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6049 // We need at least two arguments.
6050 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6051 return false;
6052
6053 // Claim the second argument.
6054 CoveredArgs.set(argIndex + 1);
6055
6056 // Type check the first argument (int for %b, pointer for %D)
6057 const Expr *Ex = getDataArg(argIndex);
6058 const analyze_printf::ArgType &AT =
6059 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6060 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6061 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6062 EmitFormatDiagnostic(
6063 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6064 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6065 << false << Ex->getSourceRange(),
6066 Ex->getLocStart(), /*IsStringLocation*/false,
6067 getSpecifierRange(startSpecifier, specifierLen));
6068
6069 // Type check the second argument (char * for both %b and %D)
6070 Ex = getDataArg(argIndex + 1);
6071 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6072 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6073 EmitFormatDiagnostic(
6074 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6075 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6076 << false << Ex->getSourceRange(),
6077 Ex->getLocStart(), /*IsStringLocation*/false,
6078 getSpecifierRange(startSpecifier, specifierLen));
6079
6080 return true;
6081 }
6082
Ted Kremenek4a49d982010-02-26 19:18:41 +00006083 // Check for using an Objective-C specific conversion specifier
6084 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006085 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006086 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6087 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006088 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006089
Mehdi Amini06d367c2016-10-24 20:39:34 +00006090 // %P can only be used with os_log.
6091 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6092 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6093 specifierLen);
6094 }
6095
6096 // %n is not allowed with os_log.
6097 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6098 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6099 getLocationOfByte(CS.getStart()),
6100 /*IsStringLocation*/ false,
6101 getSpecifierRange(startSpecifier, specifierLen));
6102
6103 return true;
6104 }
6105
6106 // Only scalars are allowed for os_trace.
6107 if (FSType == Sema::FST_OSTrace &&
6108 (CS.getKind() == ConversionSpecifier::PArg ||
6109 CS.getKind() == ConversionSpecifier::sArg ||
6110 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6111 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6112 specifierLen);
6113 }
6114
6115 // Check for use of public/private annotation outside of os_log().
6116 if (FSType != Sema::FST_OSLog) {
6117 if (FS.isPublic().isSet()) {
6118 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6119 << "public",
6120 getLocationOfByte(FS.isPublic().getPosition()),
6121 /*IsStringLocation*/ false,
6122 getSpecifierRange(startSpecifier, specifierLen));
6123 }
6124 if (FS.isPrivate().isSet()) {
6125 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6126 << "private",
6127 getLocationOfByte(FS.isPrivate().getPosition()),
6128 /*IsStringLocation*/ false,
6129 getSpecifierRange(startSpecifier, specifierLen));
6130 }
6131 }
6132
Tom Careb49ec692010-06-17 19:00:27 +00006133 // Check for invalid use of field width
6134 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006135 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006136 startSpecifier, specifierLen);
6137 }
6138
6139 // Check for invalid use of precision
6140 if (!FS.hasValidPrecision()) {
6141 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6142 startSpecifier, specifierLen);
6143 }
6144
Mehdi Amini06d367c2016-10-24 20:39:34 +00006145 // Precision is mandatory for %P specifier.
6146 if (CS.getKind() == ConversionSpecifier::PArg &&
6147 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6148 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6149 getLocationOfByte(startSpecifier),
6150 /*IsStringLocation*/ false,
6151 getSpecifierRange(startSpecifier, specifierLen));
6152 }
6153
Tom Careb49ec692010-06-17 19:00:27 +00006154 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006155 if (!FS.hasValidThousandsGroupingPrefix())
6156 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006157 if (!FS.hasValidLeadingZeros())
6158 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6159 if (!FS.hasValidPlusPrefix())
6160 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006161 if (!FS.hasValidSpacePrefix())
6162 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006163 if (!FS.hasValidAlternativeForm())
6164 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6165 if (!FS.hasValidLeftJustified())
6166 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6167
6168 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006169 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6170 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6171 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006172 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6173 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6174 startSpecifier, specifierLen);
6175
6176 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006177 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006178 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006180 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006181 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006182 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006183 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6184 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006185
Jordan Rose92303592012-09-08 04:00:03 +00006186 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6187 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6188
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006189 // The remaining checks depend on the data arguments.
6190 if (HasVAListArg)
6191 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006192
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006193 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006194 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006195
Jordan Rose58bbe422012-07-19 18:10:08 +00006196 const Expr *Arg = getDataArg(argIndex);
6197 if (!Arg)
6198 return true;
6199
6200 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006201}
6202
Jordan Roseaee34382012-09-05 22:56:26 +00006203static bool requiresParensToAddCast(const Expr *E) {
6204 // FIXME: We should have a general way to reason about operator
6205 // precedence and whether parens are actually needed here.
6206 // Take care of a few common cases where they aren't.
6207 const Expr *Inside = E->IgnoreImpCasts();
6208 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6209 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6210
6211 switch (Inside->getStmtClass()) {
6212 case Stmt::ArraySubscriptExprClass:
6213 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006214 case Stmt::CharacterLiteralClass:
6215 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006216 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006217 case Stmt::FloatingLiteralClass:
6218 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006219 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006220 case Stmt::ObjCArrayLiteralClass:
6221 case Stmt::ObjCBoolLiteralExprClass:
6222 case Stmt::ObjCBoxedExprClass:
6223 case Stmt::ObjCDictionaryLiteralClass:
6224 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006225 case Stmt::ObjCIvarRefExprClass:
6226 case Stmt::ObjCMessageExprClass:
6227 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006228 case Stmt::ObjCStringLiteralClass:
6229 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006230 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006231 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006232 case Stmt::UnaryOperatorClass:
6233 return false;
6234 default:
6235 return true;
6236 }
6237}
6238
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006239static std::pair<QualType, StringRef>
6240shouldNotPrintDirectly(const ASTContext &Context,
6241 QualType IntendedTy,
6242 const Expr *E) {
6243 // Use a 'while' to peel off layers of typedefs.
6244 QualType TyTy = IntendedTy;
6245 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6246 StringRef Name = UserTy->getDecl()->getName();
6247 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006248 .Case("CFIndex", Context.getNSIntegerType())
6249 .Case("NSInteger", Context.getNSIntegerType())
6250 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006251 .Case("SInt32", Context.IntTy)
6252 .Case("UInt32", Context.UnsignedIntTy)
6253 .Default(QualType());
6254
6255 if (!CastTy.isNull())
6256 return std::make_pair(CastTy, Name);
6257
6258 TyTy = UserTy->desugar();
6259 }
6260
6261 // Strip parens if necessary.
6262 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6263 return shouldNotPrintDirectly(Context,
6264 PE->getSubExpr()->getType(),
6265 PE->getSubExpr());
6266
6267 // If this is a conditional expression, then its result type is constructed
6268 // via usual arithmetic conversions and thus there might be no necessary
6269 // typedef sugar there. Recurse to operands to check for NSInteger &
6270 // Co. usage condition.
6271 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6272 QualType TrueTy, FalseTy;
6273 StringRef TrueName, FalseName;
6274
6275 std::tie(TrueTy, TrueName) =
6276 shouldNotPrintDirectly(Context,
6277 CO->getTrueExpr()->getType(),
6278 CO->getTrueExpr());
6279 std::tie(FalseTy, FalseName) =
6280 shouldNotPrintDirectly(Context,
6281 CO->getFalseExpr()->getType(),
6282 CO->getFalseExpr());
6283
6284 if (TrueTy == FalseTy)
6285 return std::make_pair(TrueTy, TrueName);
6286 else if (TrueTy.isNull())
6287 return std::make_pair(FalseTy, FalseName);
6288 else if (FalseTy.isNull())
6289 return std::make_pair(TrueTy, TrueName);
6290 }
6291
6292 return std::make_pair(QualType(), StringRef());
6293}
6294
Richard Smith55ce3522012-06-25 20:30:08 +00006295bool
6296CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6297 const char *StartSpecifier,
6298 unsigned SpecifierLen,
6299 const Expr *E) {
6300 using namespace analyze_format_string;
6301 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006302
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006303 // Now type check the data expression that matches the
6304 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006305 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006306 if (!AT.isValid())
6307 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006308
Jordan Rose598ec092012-12-05 18:44:40 +00006309 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006310 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6311 ExprTy = TET->getUnderlyingExpr()->getType();
6312 }
6313
Seth Cantrellb4802962015-03-04 03:12:10 +00006314 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6315
6316 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006317 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006318 }
Jordan Rose98709982012-06-04 22:48:57 +00006319
Jordan Rose22b74712012-09-05 22:56:19 +00006320 // Look through argument promotions for our error message's reported type.
6321 // This includes the integral and floating promotions, but excludes array
6322 // and function pointer decay; seeing that an argument intended to be a
6323 // string has type 'char [6]' is probably more confusing than 'char *'.
6324 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6325 if (ICE->getCastKind() == CK_IntegralCast ||
6326 ICE->getCastKind() == CK_FloatingCast) {
6327 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006328 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006329
6330 // Check if we didn't match because of an implicit cast from a 'char'
6331 // or 'short' to an 'int'. This is done because printf is a varargs
6332 // function.
6333 if (ICE->getType() == S.Context.IntTy ||
6334 ICE->getType() == S.Context.UnsignedIntTy) {
6335 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006336 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006337 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006338 }
Jordan Rose98709982012-06-04 22:48:57 +00006339 }
Jordan Rose598ec092012-12-05 18:44:40 +00006340 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6341 // Special case for 'a', which has type 'int' in C.
6342 // Note, however, that we do /not/ want to treat multibyte constants like
6343 // 'MooV' as characters! This form is deprecated but still exists.
6344 if (ExprTy == S.Context.IntTy)
6345 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6346 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006347 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006348
Jordan Rosebc53ed12014-05-31 04:12:14 +00006349 // Look through enums to their underlying type.
6350 bool IsEnum = false;
6351 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6352 ExprTy = EnumTy->getDecl()->getIntegerType();
6353 IsEnum = true;
6354 }
6355
Jordan Rose0e5badd2012-12-05 18:44:49 +00006356 // %C in an Objective-C context prints a unichar, not a wchar_t.
6357 // If the argument is an integer of some kind, believe the %C and suggest
6358 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006359 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006360 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006361 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6362 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6363 !ExprTy->isCharType()) {
6364 // 'unichar' is defined as a typedef of unsigned short, but we should
6365 // prefer using the typedef if it is visible.
6366 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006367
6368 // While we are here, check if the value is an IntegerLiteral that happens
6369 // to be within the valid range.
6370 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6371 const llvm::APInt &V = IL->getValue();
6372 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6373 return true;
6374 }
6375
Jordan Rose0e5badd2012-12-05 18:44:49 +00006376 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6377 Sema::LookupOrdinaryName);
6378 if (S.LookupName(Result, S.getCurScope())) {
6379 NamedDecl *ND = Result.getFoundDecl();
6380 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6381 if (TD->getUnderlyingType() == IntendedTy)
6382 IntendedTy = S.Context.getTypedefType(TD);
6383 }
6384 }
6385 }
6386
6387 // Special-case some of Darwin's platform-independence types by suggesting
6388 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006389 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006390 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006391 QualType CastTy;
6392 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6393 if (!CastTy.isNull()) {
6394 IntendedTy = CastTy;
6395 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006396 }
6397 }
6398
Jordan Rose22b74712012-09-05 22:56:19 +00006399 // We may be able to offer a FixItHint if it is a supported type.
6400 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006401 bool success =
6402 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006403
Jordan Rose22b74712012-09-05 22:56:19 +00006404 if (success) {
6405 // Get the fix string from the fixed format specifier
6406 SmallString<16> buf;
6407 llvm::raw_svector_ostream os(buf);
6408 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006409
Jordan Roseaee34382012-09-05 22:56:26 +00006410 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6411
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006412 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006413 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6414 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6415 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6416 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006417 // In this case, the specifier is wrong and should be changed to match
6418 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006419 EmitFormatDiagnostic(S.PDiag(diag)
6420 << AT.getRepresentativeTypeName(S.Context)
6421 << IntendedTy << IsEnum << E->getSourceRange(),
6422 E->getLocStart(),
6423 /*IsStringLocation*/ false, SpecRange,
6424 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006425 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006426 // The canonical type for formatting this value is different from the
6427 // actual type of the expression. (This occurs, for example, with Darwin's
6428 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6429 // should be printed as 'long' for 64-bit compatibility.)
6430 // Rather than emitting a normal format/argument mismatch, we want to
6431 // add a cast to the recommended type (and correct the format string
6432 // if necessary).
6433 SmallString<16> CastBuf;
6434 llvm::raw_svector_ostream CastFix(CastBuf);
6435 CastFix << "(";
6436 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6437 CastFix << ")";
6438
6439 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006440 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006441 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6442
6443 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6444 // If there's already a cast present, just replace it.
6445 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6446 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6447
6448 } else if (!requiresParensToAddCast(E)) {
6449 // If the expression has high enough precedence,
6450 // just write the C-style cast.
6451 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6452 CastFix.str()));
6453 } else {
6454 // Otherwise, add parens around the expression as well as the cast.
6455 CastFix << "(";
6456 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6457 CastFix.str()));
6458
Alp Tokerb6cc5922014-05-03 03:45:55 +00006459 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006460 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6461 }
6462
Jordan Rose0e5badd2012-12-05 18:44:49 +00006463 if (ShouldNotPrintDirectly) {
6464 // The expression has a type that should not be printed directly.
6465 // We extract the name from the typedef because we don't want to show
6466 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006467 StringRef Name;
6468 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6469 Name = TypedefTy->getDecl()->getName();
6470 else
6471 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006472 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006473 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006474 << E->getSourceRange(),
6475 E->getLocStart(), /*IsStringLocation=*/false,
6476 SpecRange, Hints);
6477 } else {
6478 // In this case, the expression could be printed using a different
6479 // specifier, but we've decided that the specifier is probably correct
6480 // and we should cast instead. Just use the normal warning message.
6481 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006482 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6483 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006484 << E->getSourceRange(),
6485 E->getLocStart(), /*IsStringLocation*/false,
6486 SpecRange, Hints);
6487 }
Jordan Roseaee34382012-09-05 22:56:26 +00006488 }
Jordan Rose22b74712012-09-05 22:56:19 +00006489 } else {
6490 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6491 SpecifierLen);
6492 // Since the warning for passing non-POD types to variadic functions
6493 // was deferred until now, we emit a warning for non-POD
6494 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006495 switch (S.isValidVarArgType(ExprTy)) {
6496 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006497 case Sema::VAK_ValidInCXX11: {
6498 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6499 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6500 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6501 }
Richard Smithd7293d72013-08-05 18:49:43 +00006502
Seth Cantrellb4802962015-03-04 03:12:10 +00006503 EmitFormatDiagnostic(
6504 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6505 << IsEnum << CSR << E->getSourceRange(),
6506 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6507 break;
6508 }
Richard Smithd7293d72013-08-05 18:49:43 +00006509 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006510 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006511 EmitFormatDiagnostic(
6512 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006513 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006514 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006515 << CallType
6516 << AT.getRepresentativeTypeName(S.Context)
6517 << CSR
6518 << E->getSourceRange(),
6519 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006520 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006521 break;
6522
6523 case Sema::VAK_Invalid:
6524 if (ExprTy->isObjCObjectType())
6525 EmitFormatDiagnostic(
6526 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6527 << S.getLangOpts().CPlusPlus11
6528 << ExprTy
6529 << CallType
6530 << AT.getRepresentativeTypeName(S.Context)
6531 << CSR
6532 << E->getSourceRange(),
6533 E->getLocStart(), /*IsStringLocation*/false, CSR);
6534 else
6535 // FIXME: If this is an initializer list, suggest removing the braces
6536 // or inserting a cast to the target type.
6537 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6538 << isa<InitListExpr>(E) << ExprTy << CallType
6539 << AT.getRepresentativeTypeName(S.Context)
6540 << E->getSourceRange();
6541 break;
6542 }
6543
6544 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6545 "format string specifier index out of range");
6546 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006547 }
6548
Ted Kremenekab278de2010-01-28 23:39:18 +00006549 return true;
6550}
6551
Ted Kremenek02087932010-07-16 02:11:22 +00006552//===--- CHECK: Scanf format string checking ------------------------------===//
6553
6554namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006555
Ted Kremenek02087932010-07-16 02:11:22 +00006556class CheckScanfHandler : public CheckFormatHandler {
6557public:
Stephen Hines648c3692016-09-16 01:07:04 +00006558 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006559 const Expr *origFormatExpr, Sema::FormatStringType type,
6560 unsigned firstDataArg, unsigned numDataArgs,
6561 const char *beg, bool hasVAListArg,
6562 ArrayRef<const Expr *> Args, unsigned formatIdx,
6563 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006564 llvm::SmallBitVector &CheckedVarArgs,
6565 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006566 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6567 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6568 inFunctionCall, CallType, CheckedVarArgs,
6569 UncoveredArg) {}
6570
Ted Kremenek02087932010-07-16 02:11:22 +00006571 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6572 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006573 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006574
6575 bool HandleInvalidScanfConversionSpecifier(
6576 const analyze_scanf::ScanfSpecifier &FS,
6577 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006578 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006579
Craig Toppere14c0f82014-03-12 04:55:44 +00006580 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006581};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006582
6583} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006584
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006585void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6586 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006587 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6588 getLocationOfByte(end), /*IsStringLocation*/true,
6589 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006590}
6591
Ted Kremenekce815422010-07-19 21:25:57 +00006592bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6593 const analyze_scanf::ScanfSpecifier &FS,
6594 const char *startSpecifier,
6595 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006596 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006597 FS.getConversionSpecifier();
6598
6599 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6600 getLocationOfByte(CS.getStart()),
6601 startSpecifier, specifierLen,
6602 CS.getStart(), CS.getLength());
6603}
6604
Ted Kremenek02087932010-07-16 02:11:22 +00006605bool CheckScanfHandler::HandleScanfSpecifier(
6606 const analyze_scanf::ScanfSpecifier &FS,
6607 const char *startSpecifier,
6608 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006609 using namespace analyze_scanf;
6610 using namespace analyze_format_string;
6611
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006612 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006613
Ted Kremenek6cd69422010-07-19 22:01:06 +00006614 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6615 // be used to decide if we are using positional arguments consistently.
6616 if (FS.consumesDataArgument()) {
6617 if (atFirstArg) {
6618 atFirstArg = false;
6619 usesPositionalArgs = FS.usesPositionalArg();
6620 }
6621 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006622 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6623 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006624 return false;
6625 }
Ted Kremenek02087932010-07-16 02:11:22 +00006626 }
6627
6628 // Check if the field with is non-zero.
6629 const OptionalAmount &Amt = FS.getFieldWidth();
6630 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6631 if (Amt.getConstantAmount() == 0) {
6632 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6633 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006634 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6635 getLocationOfByte(Amt.getStart()),
6636 /*IsStringLocation*/true, R,
6637 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006638 }
6639 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006640
Ted Kremenek02087932010-07-16 02:11:22 +00006641 if (!FS.consumesDataArgument()) {
6642 // FIXME: Technically specifying a precision or field width here
6643 // makes no sense. Worth issuing a warning at some point.
6644 return true;
6645 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006646
Ted Kremenek02087932010-07-16 02:11:22 +00006647 // Consume the argument.
6648 unsigned argIndex = FS.getArgIndex();
6649 if (argIndex < NumDataArgs) {
6650 // The check to see if the argIndex is valid will come later.
6651 // We set the bit here because we may exit early from this
6652 // function if we encounter some other error.
6653 CoveredArgs.set(argIndex);
6654 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006655
Ted Kremenek4407ea42010-07-20 20:04:47 +00006656 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006657 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006658 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006660 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006661 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006662 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006663 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6664 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006665
Jordan Rose92303592012-09-08 04:00:03 +00006666 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6667 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6668
Ted Kremenek02087932010-07-16 02:11:22 +00006669 // The remaining checks depend on the data arguments.
6670 if (HasVAListArg)
6671 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006672
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006673 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006674 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006675
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006676 // Check that the argument type matches the format specifier.
6677 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006678 if (!Ex)
6679 return true;
6680
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006681 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006682
6683 if (!AT.isValid()) {
6684 return true;
6685 }
6686
Seth Cantrellb4802962015-03-04 03:12:10 +00006687 analyze_format_string::ArgType::MatchKind match =
6688 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006689 if (match == analyze_format_string::ArgType::Match) {
6690 return true;
6691 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006692
Seth Cantrell79340072015-03-04 05:58:08 +00006693 ScanfSpecifier fixedFS = FS;
6694 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6695 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006696
Seth Cantrell79340072015-03-04 05:58:08 +00006697 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6698 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6699 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6700 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006701
Seth Cantrell79340072015-03-04 05:58:08 +00006702 if (success) {
6703 // Get the fix string from the fixed format specifier.
6704 SmallString<128> buf;
6705 llvm::raw_svector_ostream os(buf);
6706 fixedFS.toString(os);
6707
6708 EmitFormatDiagnostic(
6709 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6710 << Ex->getType() << false << Ex->getSourceRange(),
6711 Ex->getLocStart(),
6712 /*IsStringLocation*/ false,
6713 getSpecifierRange(startSpecifier, specifierLen),
6714 FixItHint::CreateReplacement(
6715 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6716 } else {
6717 EmitFormatDiagnostic(S.PDiag(diag)
6718 << AT.getRepresentativeTypeName(S.Context)
6719 << Ex->getType() << false << Ex->getSourceRange(),
6720 Ex->getLocStart(),
6721 /*IsStringLocation*/ false,
6722 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006723 }
6724
Ted Kremenek02087932010-07-16 02:11:22 +00006725 return true;
6726}
6727
Stephen Hines648c3692016-09-16 01:07:04 +00006728static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006729 const Expr *OrigFormatExpr,
6730 ArrayRef<const Expr *> Args,
6731 bool HasVAListArg, unsigned format_idx,
6732 unsigned firstDataArg,
6733 Sema::FormatStringType Type,
6734 bool inFunctionCall,
6735 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006736 llvm::SmallBitVector &CheckedVarArgs,
6737 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006738 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006739 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006740 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006741 S, inFunctionCall, Args[format_idx],
6742 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006743 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006744 return;
6745 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006746
Ted Kremenekab278de2010-01-28 23:39:18 +00006747 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006748 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006749 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006750 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006751 const ConstantArrayType *T =
6752 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006753 assert(T && "String literal not of constant array type!");
6754 size_t TypeSize = T->getSize().getZExtValue();
6755 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006756 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006757
6758 // Emit a warning if the string literal is truncated and does not contain an
6759 // embedded null character.
6760 if (TypeSize <= StrRef.size() &&
6761 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6762 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006763 S, inFunctionCall, Args[format_idx],
6764 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006765 FExpr->getLocStart(),
6766 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6767 return;
6768 }
6769
Ted Kremenekab278de2010-01-28 23:39:18 +00006770 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006771 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006772 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006773 S, inFunctionCall, Args[format_idx],
6774 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006775 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006776 return;
6777 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006778
6779 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006780 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6781 Type == Sema::FST_OSTrace) {
6782 CheckPrintfHandler H(
6783 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6784 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6785 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6786 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006787
Hans Wennborg23926bd2011-12-15 10:25:47 +00006788 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006789 S.getLangOpts(),
6790 S.Context.getTargetInfo(),
6791 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006792 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006793 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006794 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6795 numDataArgs, Str, HasVAListArg, Args, format_idx,
6796 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006797
Hans Wennborg23926bd2011-12-15 10:25:47 +00006798 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006799 S.getLangOpts(),
6800 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006801 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006802 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006803}
6804
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006805bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6806 // Str - The format string. NOTE: this is NOT null-terminated!
6807 StringRef StrRef = FExpr->getString();
6808 const char *Str = StrRef.data();
6809 // Account for cases where the string literal is truncated in a declaration.
6810 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6811 assert(T && "String literal not of constant array type!");
6812 size_t TypeSize = T->getSize().getZExtValue();
6813 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6814 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6815 getLangOpts(),
6816 Context.getTargetInfo());
6817}
6818
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006819//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6820
6821// Returns the related absolute value function that is larger, of 0 if one
6822// does not exist.
6823static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6824 switch (AbsFunction) {
6825 default:
6826 return 0;
6827
6828 case Builtin::BI__builtin_abs:
6829 return Builtin::BI__builtin_labs;
6830 case Builtin::BI__builtin_labs:
6831 return Builtin::BI__builtin_llabs;
6832 case Builtin::BI__builtin_llabs:
6833 return 0;
6834
6835 case Builtin::BI__builtin_fabsf:
6836 return Builtin::BI__builtin_fabs;
6837 case Builtin::BI__builtin_fabs:
6838 return Builtin::BI__builtin_fabsl;
6839 case Builtin::BI__builtin_fabsl:
6840 return 0;
6841
6842 case Builtin::BI__builtin_cabsf:
6843 return Builtin::BI__builtin_cabs;
6844 case Builtin::BI__builtin_cabs:
6845 return Builtin::BI__builtin_cabsl;
6846 case Builtin::BI__builtin_cabsl:
6847 return 0;
6848
6849 case Builtin::BIabs:
6850 return Builtin::BIlabs;
6851 case Builtin::BIlabs:
6852 return Builtin::BIllabs;
6853 case Builtin::BIllabs:
6854 return 0;
6855
6856 case Builtin::BIfabsf:
6857 return Builtin::BIfabs;
6858 case Builtin::BIfabs:
6859 return Builtin::BIfabsl;
6860 case Builtin::BIfabsl:
6861 return 0;
6862
6863 case Builtin::BIcabsf:
6864 return Builtin::BIcabs;
6865 case Builtin::BIcabs:
6866 return Builtin::BIcabsl;
6867 case Builtin::BIcabsl:
6868 return 0;
6869 }
6870}
6871
6872// Returns the argument type of the absolute value function.
6873static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6874 unsigned AbsType) {
6875 if (AbsType == 0)
6876 return QualType();
6877
6878 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6879 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6880 if (Error != ASTContext::GE_None)
6881 return QualType();
6882
6883 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6884 if (!FT)
6885 return QualType();
6886
6887 if (FT->getNumParams() != 1)
6888 return QualType();
6889
6890 return FT->getParamType(0);
6891}
6892
6893// Returns the best absolute value function, or zero, based on type and
6894// current absolute value function.
6895static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6896 unsigned AbsFunctionKind) {
6897 unsigned BestKind = 0;
6898 uint64_t ArgSize = Context.getTypeSize(ArgType);
6899 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6900 Kind = getLargerAbsoluteValueFunction(Kind)) {
6901 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6902 if (Context.getTypeSize(ParamType) >= ArgSize) {
6903 if (BestKind == 0)
6904 BestKind = Kind;
6905 else if (Context.hasSameType(ParamType, ArgType)) {
6906 BestKind = Kind;
6907 break;
6908 }
6909 }
6910 }
6911 return BestKind;
6912}
6913
6914enum AbsoluteValueKind {
6915 AVK_Integer,
6916 AVK_Floating,
6917 AVK_Complex
6918};
6919
6920static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6921 if (T->isIntegralOrEnumerationType())
6922 return AVK_Integer;
6923 if (T->isRealFloatingType())
6924 return AVK_Floating;
6925 if (T->isAnyComplexType())
6926 return AVK_Complex;
6927
6928 llvm_unreachable("Type not integer, floating, or complex");
6929}
6930
6931// Changes the absolute value function to a different type. Preserves whether
6932// the function is a builtin.
6933static unsigned changeAbsFunction(unsigned AbsKind,
6934 AbsoluteValueKind ValueKind) {
6935 switch (ValueKind) {
6936 case AVK_Integer:
6937 switch (AbsKind) {
6938 default:
6939 return 0;
6940 case Builtin::BI__builtin_fabsf:
6941 case Builtin::BI__builtin_fabs:
6942 case Builtin::BI__builtin_fabsl:
6943 case Builtin::BI__builtin_cabsf:
6944 case Builtin::BI__builtin_cabs:
6945 case Builtin::BI__builtin_cabsl:
6946 return Builtin::BI__builtin_abs;
6947 case Builtin::BIfabsf:
6948 case Builtin::BIfabs:
6949 case Builtin::BIfabsl:
6950 case Builtin::BIcabsf:
6951 case Builtin::BIcabs:
6952 case Builtin::BIcabsl:
6953 return Builtin::BIabs;
6954 }
6955 case AVK_Floating:
6956 switch (AbsKind) {
6957 default:
6958 return 0;
6959 case Builtin::BI__builtin_abs:
6960 case Builtin::BI__builtin_labs:
6961 case Builtin::BI__builtin_llabs:
6962 case Builtin::BI__builtin_cabsf:
6963 case Builtin::BI__builtin_cabs:
6964 case Builtin::BI__builtin_cabsl:
6965 return Builtin::BI__builtin_fabsf;
6966 case Builtin::BIabs:
6967 case Builtin::BIlabs:
6968 case Builtin::BIllabs:
6969 case Builtin::BIcabsf:
6970 case Builtin::BIcabs:
6971 case Builtin::BIcabsl:
6972 return Builtin::BIfabsf;
6973 }
6974 case AVK_Complex:
6975 switch (AbsKind) {
6976 default:
6977 return 0;
6978 case Builtin::BI__builtin_abs:
6979 case Builtin::BI__builtin_labs:
6980 case Builtin::BI__builtin_llabs:
6981 case Builtin::BI__builtin_fabsf:
6982 case Builtin::BI__builtin_fabs:
6983 case Builtin::BI__builtin_fabsl:
6984 return Builtin::BI__builtin_cabsf;
6985 case Builtin::BIabs:
6986 case Builtin::BIlabs:
6987 case Builtin::BIllabs:
6988 case Builtin::BIfabsf:
6989 case Builtin::BIfabs:
6990 case Builtin::BIfabsl:
6991 return Builtin::BIcabsf;
6992 }
6993 }
6994 llvm_unreachable("Unable to convert function");
6995}
6996
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00006997static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006998 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6999 if (!FnInfo)
7000 return 0;
7001
7002 switch (FDecl->getBuiltinID()) {
7003 default:
7004 return 0;
7005 case Builtin::BI__builtin_abs:
7006 case Builtin::BI__builtin_fabs:
7007 case Builtin::BI__builtin_fabsf:
7008 case Builtin::BI__builtin_fabsl:
7009 case Builtin::BI__builtin_labs:
7010 case Builtin::BI__builtin_llabs:
7011 case Builtin::BI__builtin_cabs:
7012 case Builtin::BI__builtin_cabsf:
7013 case Builtin::BI__builtin_cabsl:
7014 case Builtin::BIabs:
7015 case Builtin::BIlabs:
7016 case Builtin::BIllabs:
7017 case Builtin::BIfabs:
7018 case Builtin::BIfabsf:
7019 case Builtin::BIfabsl:
7020 case Builtin::BIcabs:
7021 case Builtin::BIcabsf:
7022 case Builtin::BIcabsl:
7023 return FDecl->getBuiltinID();
7024 }
7025 llvm_unreachable("Unknown Builtin type");
7026}
7027
7028// If the replacement is valid, emit a note with replacement function.
7029// Additionally, suggest including the proper header if not already included.
7030static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007031 unsigned AbsKind, QualType ArgType) {
7032 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007033 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007034 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007035 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7036 FunctionName = "std::abs";
7037 if (ArgType->isIntegralOrEnumerationType()) {
7038 HeaderName = "cstdlib";
7039 } else if (ArgType->isRealFloatingType()) {
7040 HeaderName = "cmath";
7041 } else {
7042 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007043 }
Richard Trieubeffb832014-04-15 23:47:53 +00007044
7045 // Lookup all std::abs
7046 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007047 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007048 R.suppressDiagnostics();
7049 S.LookupQualifiedName(R, Std);
7050
7051 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007052 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007053 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7054 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7055 } else {
7056 FDecl = dyn_cast<FunctionDecl>(I);
7057 }
7058 if (!FDecl)
7059 continue;
7060
7061 // Found std::abs(), check that they are the right ones.
7062 if (FDecl->getNumParams() != 1)
7063 continue;
7064
7065 // Check that the parameter type can handle the argument.
7066 QualType ParamType = FDecl->getParamDecl(0)->getType();
7067 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7068 S.Context.getTypeSize(ArgType) <=
7069 S.Context.getTypeSize(ParamType)) {
7070 // Found a function, don't need the header hint.
7071 EmitHeaderHint = false;
7072 break;
7073 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007074 }
Richard Trieubeffb832014-04-15 23:47:53 +00007075 }
7076 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007077 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007078 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7079
7080 if (HeaderName) {
7081 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7082 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7083 R.suppressDiagnostics();
7084 S.LookupName(R, S.getCurScope());
7085
7086 if (R.isSingleResult()) {
7087 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7088 if (FD && FD->getBuiltinID() == AbsKind) {
7089 EmitHeaderHint = false;
7090 } else {
7091 return;
7092 }
7093 } else if (!R.empty()) {
7094 return;
7095 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007096 }
7097 }
7098
7099 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007100 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007101
Richard Trieubeffb832014-04-15 23:47:53 +00007102 if (!HeaderName)
7103 return;
7104
7105 if (!EmitHeaderHint)
7106 return;
7107
Alp Toker5d96e0a2014-07-11 20:53:51 +00007108 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7109 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007110}
7111
Richard Trieua7f30b12016-12-06 01:42:28 +00007112template <std::size_t StrLen>
7113static bool IsStdFunction(const FunctionDecl *FDecl,
7114 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007115 if (!FDecl)
7116 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007117 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007118 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007119 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007120 return false;
7121
7122 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007123}
7124
7125// Warn when using the wrong abs() function.
7126void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007127 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007128 if (Call->getNumArgs() != 1)
7129 return;
7130
7131 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007132 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007133 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007134 return;
7135
7136 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7137 QualType ParamType = Call->getArg(0)->getType();
7138
Alp Toker5d96e0a2014-07-11 20:53:51 +00007139 // Unsigned types cannot be negative. Suggest removing the absolute value
7140 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007141 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007142 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007143 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007144 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7145 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007146 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007147 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7148 return;
7149 }
7150
David Majnemer7f77eb92015-11-15 03:04:34 +00007151 // Taking the absolute value of a pointer is very suspicious, they probably
7152 // wanted to index into an array, dereference a pointer, call a function, etc.
7153 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7154 unsigned DiagType = 0;
7155 if (ArgType->isFunctionType())
7156 DiagType = 1;
7157 else if (ArgType->isArrayType())
7158 DiagType = 2;
7159
7160 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7161 return;
7162 }
7163
Richard Trieubeffb832014-04-15 23:47:53 +00007164 // std::abs has overloads which prevent most of the absolute value problems
7165 // from occurring.
7166 if (IsStdAbs)
7167 return;
7168
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007169 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7170 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7171
7172 // The argument and parameter are the same kind. Check if they are the right
7173 // size.
7174 if (ArgValueKind == ParamValueKind) {
7175 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7176 return;
7177
7178 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7179 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7180 << FDecl << ArgType << ParamType;
7181
7182 if (NewAbsKind == 0)
7183 return;
7184
7185 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007186 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007187 return;
7188 }
7189
7190 // ArgValueKind != ParamValueKind
7191 // The wrong type of absolute value function was used. Attempt to find the
7192 // proper one.
7193 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7194 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7195 if (NewAbsKind == 0)
7196 return;
7197
7198 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7199 << FDecl << ParamValueKind << ArgValueKind;
7200
7201 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007202 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007203}
7204
Richard Trieu67c00712016-12-05 23:41:46 +00007205//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007206void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7207 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007208 if (!Call || !FDecl) return;
7209
7210 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007211 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007212 if (Call->getExprLoc().isMacroID()) return;
7213
7214 // Only care about the one template argument, two function parameter std::max
7215 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007216 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007217 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7218 if (!ArgList) return;
7219 if (ArgList->size() != 1) return;
7220
7221 // Check that template type argument is unsigned integer.
7222 const auto& TA = ArgList->get(0);
7223 if (TA.getKind() != TemplateArgument::Type) return;
7224 QualType ArgType = TA.getAsType();
7225 if (!ArgType->isUnsignedIntegerType()) return;
7226
7227 // See if either argument is a literal zero.
7228 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7229 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7230 if (!MTE) return false;
7231 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7232 if (!Num) return false;
7233 if (Num->getValue() != 0) return false;
7234 return true;
7235 };
7236
7237 const Expr *FirstArg = Call->getArg(0);
7238 const Expr *SecondArg = Call->getArg(1);
7239 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7240 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7241
7242 // Only warn when exactly one argument is zero.
7243 if (IsFirstArgZero == IsSecondArgZero) return;
7244
7245 SourceRange FirstRange = FirstArg->getSourceRange();
7246 SourceRange SecondRange = SecondArg->getSourceRange();
7247
7248 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7249
7250 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7251 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7252
7253 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7254 SourceRange RemovalRange;
7255 if (IsFirstArgZero) {
7256 RemovalRange = SourceRange(FirstRange.getBegin(),
7257 SecondRange.getBegin().getLocWithOffset(-1));
7258 } else {
7259 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7260 SecondRange.getEnd());
7261 }
7262
7263 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7264 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7265 << FixItHint::CreateRemoval(RemovalRange);
7266}
7267
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007268//===--- CHECK: Standard memory functions ---------------------------------===//
7269
Nico Weber0e6daef2013-12-26 23:38:39 +00007270/// \brief Takes the expression passed to the size_t parameter of functions
7271/// such as memcmp, strncat, etc and warns if it's a comparison.
7272///
7273/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7274static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7275 IdentifierInfo *FnName,
7276 SourceLocation FnLoc,
7277 SourceLocation RParenLoc) {
7278 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7279 if (!Size)
7280 return false;
7281
7282 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7283 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7284 return false;
7285
Nico Weber0e6daef2013-12-26 23:38:39 +00007286 SourceRange SizeRange = Size->getSourceRange();
7287 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7288 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007289 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007290 << FnName << FixItHint::CreateInsertion(
7291 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007292 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007293 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007294 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007295 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7296 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007297
7298 return true;
7299}
7300
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007301/// \brief Determine whether the given type is or contains a dynamic class type
7302/// (e.g., whether it has a vtable).
7303static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7304 bool &IsContained) {
7305 // Look through array types while ignoring qualifiers.
7306 const Type *Ty = T->getBaseElementTypeUnsafe();
7307 IsContained = false;
7308
7309 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7310 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007311 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007312 return nullptr;
7313
7314 if (RD->isDynamicClass())
7315 return RD;
7316
7317 // Check all the fields. If any bases were dynamic, the class is dynamic.
7318 // It's impossible for a class to transitively contain itself by value, so
7319 // infinite recursion is impossible.
7320 for (auto *FD : RD->fields()) {
7321 bool SubContained;
7322 if (const CXXRecordDecl *ContainedRD =
7323 getContainedDynamicClass(FD->getType(), SubContained)) {
7324 IsContained = true;
7325 return ContainedRD;
7326 }
7327 }
7328
7329 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007330}
7331
Chandler Carruth889ed862011-06-21 23:04:20 +00007332/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007333/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007334static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007335 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007336 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007337 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007338 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007339
Craig Topperc3ec1492014-05-26 06:22:03 +00007340 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007341}
7342
Chandler Carruth889ed862011-06-21 23:04:20 +00007343/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007344static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007345 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7346 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007347 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007348 return SizeOf->getTypeOfArgument();
7349
7350 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007351}
7352
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007353/// \brief Check for dangerous or invalid arguments to memset().
7354///
Chandler Carruthac687262011-06-03 06:23:57 +00007355/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007356/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7357/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007358///
7359/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007360void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007361 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007362 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007363 assert(BId != 0);
7364
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007365 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007366 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007367 unsigned ExpectedNumArgs =
7368 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007369 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007370 return;
7371
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007372 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007373 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007374 unsigned LenArg =
7375 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007376 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007377
Nico Weber0e6daef2013-12-26 23:38:39 +00007378 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7379 Call->getLocStart(), Call->getRParenLoc()))
7380 return;
7381
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007382 // We have special checking when the length is a sizeof expression.
7383 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7384 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7385 llvm::FoldingSetNodeID SizeOfArgID;
7386
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007387 // Although widely used, 'bzero' is not a standard function. Be more strict
7388 // with the argument types before allowing diagnostics and only allow the
7389 // form bzero(ptr, sizeof(...)).
7390 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7391 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7392 return;
7393
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007394 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7395 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007396 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007397
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007398 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007399 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007400 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007401 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007402
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007403 // Never warn about void type pointers. This can be used to suppress
7404 // false positives.
7405 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007406 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007407
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007408 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7409 // actually comparing the expressions for equality. Because computing the
7410 // expression IDs can be expensive, we only do this if the diagnostic is
7411 // enabled.
7412 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007413 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7414 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007415 // We only compute IDs for expressions if the warning is enabled, and
7416 // cache the sizeof arg's ID.
7417 if (SizeOfArgID == llvm::FoldingSetNodeID())
7418 SizeOfArg->Profile(SizeOfArgID, Context, true);
7419 llvm::FoldingSetNodeID DestID;
7420 Dest->Profile(DestID, Context, true);
7421 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007422 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7423 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007424 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007425 StringRef ReadableName = FnName->getName();
7426
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007427 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007428 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007429 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007430 if (!PointeeTy->isIncompleteType() &&
7431 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007432 ActionIdx = 2; // If the pointee's size is sizeof(char),
7433 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007434
7435 // If the function is defined as a builtin macro, do not show macro
7436 // expansion.
7437 SourceLocation SL = SizeOfArg->getExprLoc();
7438 SourceRange DSR = Dest->getSourceRange();
7439 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007440 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007441
7442 if (SM.isMacroArgExpansion(SL)) {
7443 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7444 SL = SM.getSpellingLoc(SL);
7445 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7446 SM.getSpellingLoc(DSR.getEnd()));
7447 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7448 SM.getSpellingLoc(SSR.getEnd()));
7449 }
7450
Anna Zaksd08d9152012-05-30 23:14:52 +00007451 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007452 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007453 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007454 << PointeeTy
7455 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007456 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007457 << SSR);
7458 DiagRuntimeBehavior(SL, SizeOfArg,
7459 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7460 << ActionIdx
7461 << SSR);
7462
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007463 break;
7464 }
7465 }
7466
7467 // Also check for cases where the sizeof argument is the exact same
7468 // type as the memory argument, and where it points to a user-defined
7469 // record type.
7470 if (SizeOfArgTy != QualType()) {
7471 if (PointeeTy->isRecordType() &&
7472 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7473 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7474 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7475 << FnName << SizeOfArgTy << ArgIdx
7476 << PointeeTy << Dest->getSourceRange()
7477 << LenExpr->getSourceRange());
7478 break;
7479 }
Nico Weberc5e73862011-06-14 16:14:58 +00007480 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007481 } else if (DestTy->isArrayType()) {
7482 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007483 }
Nico Weberc5e73862011-06-14 16:14:58 +00007484
Nico Weberc44b35e2015-03-21 17:37:46 +00007485 if (PointeeTy == QualType())
7486 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007487
Nico Weberc44b35e2015-03-21 17:37:46 +00007488 // Always complain about dynamic classes.
7489 bool IsContained;
7490 if (const CXXRecordDecl *ContainedRD =
7491 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007492
Nico Weberc44b35e2015-03-21 17:37:46 +00007493 unsigned OperationType = 0;
7494 // "overwritten" if we're warning about the destination for any call
7495 // but memcmp; otherwise a verb appropriate to the call.
7496 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7497 if (BId == Builtin::BImemcpy)
7498 OperationType = 1;
7499 else if(BId == Builtin::BImemmove)
7500 OperationType = 2;
7501 else if (BId == Builtin::BImemcmp)
7502 OperationType = 3;
7503 }
7504
John McCall31168b02011-06-15 23:02:42 +00007505 DiagRuntimeBehavior(
7506 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007507 PDiag(diag::warn_dyn_class_memaccess)
7508 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7509 << FnName << IsContained << ContainedRD << OperationType
7510 << Call->getCallee()->getSourceRange());
7511 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7512 BId != Builtin::BImemset)
7513 DiagRuntimeBehavior(
7514 Dest->getExprLoc(), Dest,
7515 PDiag(diag::warn_arc_object_memaccess)
7516 << ArgIdx << FnName << PointeeTy
7517 << Call->getCallee()->getSourceRange());
7518 else
7519 continue;
7520
7521 DiagRuntimeBehavior(
7522 Dest->getExprLoc(), Dest,
7523 PDiag(diag::note_bad_memaccess_silence)
7524 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7525 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007526 }
7527}
7528
Ted Kremenek6865f772011-08-18 20:55:45 +00007529// A little helper routine: ignore addition and subtraction of integer literals.
7530// This intentionally does not ignore all integer constant expressions because
7531// we don't want to remove sizeof().
7532static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7533 Ex = Ex->IgnoreParenCasts();
7534
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007535 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007536 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7537 if (!BO || !BO->isAdditiveOp())
7538 break;
7539
7540 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7541 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7542
7543 if (isa<IntegerLiteral>(RHS))
7544 Ex = LHS;
7545 else if (isa<IntegerLiteral>(LHS))
7546 Ex = RHS;
7547 else
7548 break;
7549 }
7550
7551 return Ex;
7552}
7553
Anna Zaks13b08572012-08-08 21:42:23 +00007554static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7555 ASTContext &Context) {
7556 // Only handle constant-sized or VLAs, but not flexible members.
7557 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7558 // Only issue the FIXIT for arrays of size > 1.
7559 if (CAT->getSize().getSExtValue() <= 1)
7560 return false;
7561 } else if (!Ty->isVariableArrayType()) {
7562 return false;
7563 }
7564 return true;
7565}
7566
Ted Kremenek6865f772011-08-18 20:55:45 +00007567// Warn if the user has made the 'size' argument to strlcpy or strlcat
7568// be the size of the source, instead of the destination.
7569void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7570 IdentifierInfo *FnName) {
7571
7572 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007573 unsigned NumArgs = Call->getNumArgs();
7574 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007575 return;
7576
7577 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7578 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007579 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007580
7581 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7582 Call->getLocStart(), Call->getRParenLoc()))
7583 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007584
7585 // Look for 'strlcpy(dst, x, sizeof(x))'
7586 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7587 CompareWithSrc = Ex;
7588 else {
7589 // Look for 'strlcpy(dst, x, strlen(x))'
7590 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007591 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7592 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007593 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7594 }
7595 }
7596
7597 if (!CompareWithSrc)
7598 return;
7599
7600 // Determine if the argument to sizeof/strlen is equal to the source
7601 // argument. In principle there's all kinds of things you could do
7602 // here, for instance creating an == expression and evaluating it with
7603 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7604 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7605 if (!SrcArgDRE)
7606 return;
7607
7608 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7609 if (!CompareWithSrcDRE ||
7610 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7611 return;
7612
7613 const Expr *OriginalSizeArg = Call->getArg(2);
7614 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7615 << OriginalSizeArg->getSourceRange() << FnName;
7616
7617 // Output a FIXIT hint if the destination is an array (rather than a
7618 // pointer to an array). This could be enhanced to handle some
7619 // pointers if we know the actual size, like if DstArg is 'array+2'
7620 // we could say 'sizeof(array)-2'.
7621 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007622 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007623 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007624
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007625 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007626 llvm::raw_svector_ostream OS(sizeString);
7627 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007628 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007629 OS << ")";
7630
7631 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7632 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7633 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007634}
7635
Anna Zaks314cd092012-02-01 19:08:57 +00007636/// Check if two expressions refer to the same declaration.
7637static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7638 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7639 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7640 return D1->getDecl() == D2->getDecl();
7641 return false;
7642}
7643
7644static const Expr *getStrlenExprArg(const Expr *E) {
7645 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7646 const FunctionDecl *FD = CE->getDirectCallee();
7647 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007648 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007649 return CE->getArg(0)->IgnoreParenCasts();
7650 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007651 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007652}
7653
7654// Warn on anti-patterns as the 'size' argument to strncat.
7655// The correct size argument should look like following:
7656// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7657void Sema::CheckStrncatArguments(const CallExpr *CE,
7658 IdentifierInfo *FnName) {
7659 // Don't crash if the user has the wrong number of arguments.
7660 if (CE->getNumArgs() < 3)
7661 return;
7662 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7663 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7664 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7665
Nico Weber0e6daef2013-12-26 23:38:39 +00007666 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7667 CE->getRParenLoc()))
7668 return;
7669
Anna Zaks314cd092012-02-01 19:08:57 +00007670 // Identify common expressions, which are wrongly used as the size argument
7671 // to strncat and may lead to buffer overflows.
7672 unsigned PatternType = 0;
7673 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7674 // - sizeof(dst)
7675 if (referToTheSameDecl(SizeOfArg, DstArg))
7676 PatternType = 1;
7677 // - sizeof(src)
7678 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7679 PatternType = 2;
7680 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7681 if (BE->getOpcode() == BO_Sub) {
7682 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7683 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7684 // - sizeof(dst) - strlen(dst)
7685 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7686 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7687 PatternType = 1;
7688 // - sizeof(src) - (anything)
7689 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7690 PatternType = 2;
7691 }
7692 }
7693
7694 if (PatternType == 0)
7695 return;
7696
Anna Zaks5069aa32012-02-03 01:27:37 +00007697 // Generate the diagnostic.
7698 SourceLocation SL = LenArg->getLocStart();
7699 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007700 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007701
7702 // If the function is defined as a builtin macro, do not show macro expansion.
7703 if (SM.isMacroArgExpansion(SL)) {
7704 SL = SM.getSpellingLoc(SL);
7705 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7706 SM.getSpellingLoc(SR.getEnd()));
7707 }
7708
Anna Zaks13b08572012-08-08 21:42:23 +00007709 // Check if the destination is an array (rather than a pointer to an array).
7710 QualType DstTy = DstArg->getType();
7711 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7712 Context);
7713 if (!isKnownSizeArray) {
7714 if (PatternType == 1)
7715 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7716 else
7717 Diag(SL, diag::warn_strncat_src_size) << SR;
7718 return;
7719 }
7720
Anna Zaks314cd092012-02-01 19:08:57 +00007721 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007722 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007723 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007724 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007725
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007726 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007727 llvm::raw_svector_ostream OS(sizeString);
7728 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007729 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007730 OS << ") - ";
7731 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007732 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007733 OS << ") - 1";
7734
Anna Zaks5069aa32012-02-03 01:27:37 +00007735 Diag(SL, diag::note_strncat_wrong_size)
7736 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007737}
7738
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007739//===--- CHECK: Return Address of Stack Variable --------------------------===//
7740
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007741static const Expr *EvalVal(const Expr *E,
7742 SmallVectorImpl<const DeclRefExpr *> &refVars,
7743 const Decl *ParentDecl);
7744static const Expr *EvalAddr(const Expr *E,
7745 SmallVectorImpl<const DeclRefExpr *> &refVars,
7746 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007747
7748/// CheckReturnStackAddr - Check if a return statement returns the address
7749/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007750static void
7751CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7752 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007753 const Expr *stackE = nullptr;
7754 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007755
7756 // Perform checking for returned stack addresses, local blocks,
7757 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007758 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007759 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007760 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007761 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007762 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007763 }
7764
Craig Topperc3ec1492014-05-26 06:22:03 +00007765 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007766 return; // Nothing suspicious was found.
7767
Simon Pilgrim750bde62017-03-31 11:00:53 +00007768 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007769 // of a parameter reference doesn't need a warning.
7770 for (auto *DRE : refVars)
7771 if (isa<ParmVarDecl>(DRE->getDecl()))
7772 return;
7773
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007774 SourceLocation diagLoc;
7775 SourceRange diagRange;
7776 if (refVars.empty()) {
7777 diagLoc = stackE->getLocStart();
7778 diagRange = stackE->getSourceRange();
7779 } else {
7780 // We followed through a reference variable. 'stackE' contains the
7781 // problematic expression but we will warn at the return statement pointing
7782 // at the reference variable. We will later display the "trail" of
7783 // reference variables using notes.
7784 diagLoc = refVars[0]->getLocStart();
7785 diagRange = refVars[0]->getSourceRange();
7786 }
7787
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007788 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7789 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007790 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007791 << DR->getDecl()->getDeclName() << diagRange;
7792 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007793 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007794 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007795 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007796 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007797 // If there is an LValue->RValue conversion, then the value of the
7798 // reference type is used, not the reference.
7799 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7800 if (ICE->getCastKind() == CK_LValueToRValue) {
7801 return;
7802 }
7803 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007804 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7805 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007806 }
7807
7808 // Display the "trail" of reference variables that we followed until we
7809 // found the problematic expression using notes.
7810 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007811 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007812 // If this var binds to another reference var, show the range of the next
7813 // var, otherwise the var binds to the problematic expression, in which case
7814 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007815 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7816 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007817 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7818 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007819 }
7820}
7821
7822/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7823/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007824/// to a location on the stack, a local block, an address of a label, or a
7825/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007826/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007827/// encounter a subexpression that (1) clearly does not lead to one of the
7828/// above problematic expressions (2) is something we cannot determine leads to
7829/// a problematic expression based on such local checking.
7830///
7831/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7832/// the expression that they point to. Such variables are added to the
7833/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007834///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007835/// EvalAddr processes expressions that are pointers that are used as
7836/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007837/// At the base case of the recursion is a check for the above problematic
7838/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007839///
7840/// This implementation handles:
7841///
7842/// * pointer-to-pointer casts
7843/// * implicit conversions from array references to pointers
7844/// * taking the address of fields
7845/// * arbitrary interplay between "&" and "*" operators
7846/// * pointer arithmetic from an address of a stack variable
7847/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007848static const Expr *EvalAddr(const Expr *E,
7849 SmallVectorImpl<const DeclRefExpr *> &refVars,
7850 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007851 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00007852 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007853
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007854 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00007855 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00007856 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007857 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00007858 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00007859
Peter Collingbourne91147592011-04-15 00:35:48 +00007860 E = E->IgnoreParens();
7861
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007862 // Our "symbolic interpreter" is just a dispatch off the currently
7863 // viewed AST node. We then recursively traverse the AST by calling
7864 // EvalAddr and EvalVal appropriately.
7865 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007866 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007867 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007868
Richard Smith40f08eb2014-01-30 22:05:38 +00007869 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00007870 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00007871 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00007872
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007873 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007874 // If this is a reference variable, follow through to the expression that
7875 // it points to.
7876 if (V->hasLocalStorage() &&
7877 V->getType()->isReferenceType() && V->hasInit()) {
7878 // Add the reference variable to the "trail".
7879 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007880 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007881 }
7882
Craig Topperc3ec1492014-05-26 06:22:03 +00007883 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007884 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007885
Chris Lattner934edb22007-12-28 05:31:15 +00007886 case Stmt::UnaryOperatorClass: {
7887 // The only unary operator that make sense to handle here
7888 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007889 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007890
John McCalle3027922010-08-25 11:45:40 +00007891 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007892 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007893 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007894 }
Mike Stump11289f42009-09-09 15:08:12 +00007895
Chris Lattner934edb22007-12-28 05:31:15 +00007896 case Stmt::BinaryOperatorClass: {
7897 // Handle pointer arithmetic. All other binary operators are not valid
7898 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007899 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00007900 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00007901
John McCalle3027922010-08-25 11:45:40 +00007902 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00007903 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00007904
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007905 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00007906
7907 // Determine which argument is the real pointer base. It could be
7908 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007909 if (!Base->getType()->isPointerType())
7910 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00007911
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007912 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007913 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007914 }
Steve Naroff2752a172008-09-10 19:17:48 +00007915
Chris Lattner934edb22007-12-28 05:31:15 +00007916 // For conditional operators we need to see if either the LHS or RHS are
7917 // valid DeclRefExpr*s. If one of them is valid, we return it.
7918 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007919 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00007920
Chris Lattner934edb22007-12-28 05:31:15 +00007921 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007922 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007923 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007924 // In C++, we can have a throw-expression, which has 'void' type.
7925 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007926 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007927 return LHS;
7928 }
Chris Lattner934edb22007-12-28 05:31:15 +00007929
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007930 // In C++, we can have a throw-expression, which has 'void' type.
7931 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00007932 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00007933
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007934 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00007935 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00007936
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007937 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00007938 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007939 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00007940 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007941
7942 case Stmt::AddrLabelExprClass:
7943 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00007944
John McCall28fc7092011-11-10 05:35:25 +00007945 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007946 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7947 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00007948
Ted Kremenekc3b4c522008-08-07 00:49:01 +00007949 // For casts, we need to handle conversions from arrays to
7950 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00007951 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00007952 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00007953 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00007954 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00007955 case Stmt::CXXStaticCastExprClass:
7956 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00007957 case Stmt::CXXConstCastExprClass:
7958 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007959 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00007960 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00007961 case CK_LValueToRValue:
7962 case CK_NoOp:
7963 case CK_BaseToDerived:
7964 case CK_DerivedToBase:
7965 case CK_UncheckedDerivedToBase:
7966 case CK_Dynamic:
7967 case CK_CPointerToObjCPointerCast:
7968 case CK_BlockPointerToObjCPointerCast:
7969 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007970 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007971
7972 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00007973 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00007974
Richard Trieudadefde2014-07-02 04:39:38 +00007975 case CK_BitCast:
7976 if (SubExpr->getType()->isAnyPointerType() ||
7977 SubExpr->getType()->isBlockPointerType() ||
7978 SubExpr->getType()->isObjCQualifiedIdType())
7979 return EvalAddr(SubExpr, refVars, ParentDecl);
7980 else
7981 return nullptr;
7982
Eli Friedman8195ad72012-02-23 23:04:32 +00007983 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007984 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00007985 }
Chris Lattner934edb22007-12-28 05:31:15 +00007986 }
Mike Stump11289f42009-09-09 15:08:12 +00007987
Douglas Gregorfe314812011-06-21 17:03:29 +00007988 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007989 if (const Expr *Result =
7990 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7991 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00007992 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00007993 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007994
Chris Lattner934edb22007-12-28 05:31:15 +00007995 // Everything else: we simply don't reason about them.
7996 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00007997 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00007998 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007999}
Mike Stump11289f42009-09-09 15:08:12 +00008000
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008001/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8002/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008003static const Expr *EvalVal(const Expr *E,
8004 SmallVectorImpl<const DeclRefExpr *> &refVars,
8005 const Decl *ParentDecl) {
8006 do {
8007 // We should only be called for evaluating non-pointer expressions, or
8008 // expressions with a pointer type that are not used as references but
8009 // instead
8010 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008011
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008012 // Our "symbolic interpreter" is just a dispatch off the currently
8013 // viewed AST node. We then recursively traverse the AST by calling
8014 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008015
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008016 E = E->IgnoreParens();
8017 switch (E->getStmtClass()) {
8018 case Stmt::ImplicitCastExprClass: {
8019 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8020 if (IE->getValueKind() == VK_LValue) {
8021 E = IE->getSubExpr();
8022 continue;
8023 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008024 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008025 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008026
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008027 case Stmt::ExprWithCleanupsClass:
8028 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8029 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008030
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008031 case Stmt::DeclRefExprClass: {
8032 // When we hit a DeclRefExpr we are looking at code that refers to a
8033 // variable's name. If it's not a reference variable we check if it has
8034 // local storage within the function, and if so, return the expression.
8035 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8036
8037 // If we leave the immediate function, the lifetime isn't about to end.
8038 if (DR->refersToEnclosingVariableOrCapture())
8039 return nullptr;
8040
8041 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8042 // Check if it refers to itself, e.g. "int& i = i;".
8043 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008044 return DR;
8045
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008046 if (V->hasLocalStorage()) {
8047 if (!V->getType()->isReferenceType())
8048 return DR;
8049
8050 // Reference variable, follow through to the expression that
8051 // it points to.
8052 if (V->hasInit()) {
8053 // Add the reference variable to the "trail".
8054 refVars.push_back(DR);
8055 return EvalVal(V->getInit(), refVars, V);
8056 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008057 }
8058 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008059
8060 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008061 }
Mike Stump11289f42009-09-09 15:08:12 +00008062
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008063 case Stmt::UnaryOperatorClass: {
8064 // The only unary operator that make sense to handle here
8065 // is Deref. All others don't resolve to a "name." This includes
8066 // handling all sorts of rvalues passed to a unary operator.
8067 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008068
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008069 if (U->getOpcode() == UO_Deref)
8070 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008071
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008072 return nullptr;
8073 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008074
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008075 case Stmt::ArraySubscriptExprClass: {
8076 // Array subscripts are potential references to data on the stack. We
8077 // retrieve the DeclRefExpr* for the array variable if it indeed
8078 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008079 const auto *ASE = cast<ArraySubscriptExpr>(E);
8080 if (ASE->isTypeDependent())
8081 return nullptr;
8082 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008083 }
Mike Stump11289f42009-09-09 15:08:12 +00008084
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008085 case Stmt::OMPArraySectionExprClass: {
8086 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8087 ParentDecl);
8088 }
Mike Stump11289f42009-09-09 15:08:12 +00008089
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008090 case Stmt::ConditionalOperatorClass: {
8091 // For conditional operators we need to see if either the LHS or RHS are
8092 // non-NULL Expr's. If one is non-NULL, we return it.
8093 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008094
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008095 // Handle the GNU extension for missing LHS.
8096 if (const Expr *LHSExpr = C->getLHS()) {
8097 // In C++, we can have a throw-expression, which has 'void' type.
8098 if (!LHSExpr->getType()->isVoidType())
8099 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8100 return LHS;
8101 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008102
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008103 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008104 if (C->getRHS()->getType()->isVoidType())
8105 return nullptr;
8106
8107 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008108 }
8109
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008110 // Accesses to members are potential references to data on the stack.
8111 case Stmt::MemberExprClass: {
8112 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008113
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008114 // Check for indirect access. We only want direct field accesses.
8115 if (M->isArrow())
8116 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008117
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008118 // Check whether the member type is itself a reference, in which case
8119 // we're not going to refer to the member, but to what the member refers
8120 // to.
8121 if (M->getMemberDecl()->getType()->isReferenceType())
8122 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008123
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008124 return EvalVal(M->getBase(), refVars, ParentDecl);
8125 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008126
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008127 case Stmt::MaterializeTemporaryExprClass:
8128 if (const Expr *Result =
8129 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8130 refVars, ParentDecl))
8131 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008132 return E;
8133
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008134 default:
8135 // Check that we don't return or take the address of a reference to a
8136 // temporary. This is only useful in C++.
8137 if (!E->isTypeDependent() && E->isRValue())
8138 return E;
8139
8140 // Everything else: we simply don't reason about them.
8141 return nullptr;
8142 }
8143 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008144}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008145
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008146void
8147Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8148 SourceLocation ReturnLoc,
8149 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008150 const AttrVec *Attrs,
8151 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008152 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8153
8154 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008155 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8156 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008157 CheckNonNullExpr(*this, RetValExp))
8158 Diag(ReturnLoc, diag::warn_null_ret)
8159 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008160
8161 // C++11 [basic.stc.dynamic.allocation]p4:
8162 // If an allocation function declared with a non-throwing
8163 // exception-specification fails to allocate storage, it shall return
8164 // a null pointer. Any other allocation function that fails to allocate
8165 // storage shall indicate failure only by throwing an exception [...]
8166 if (FD) {
8167 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8168 if (Op == OO_New || Op == OO_Array_New) {
8169 const FunctionProtoType *Proto
8170 = FD->getType()->castAs<FunctionProtoType>();
8171 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8172 CheckNonNullExpr(*this, RetValExp))
8173 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8174 << FD << getLangOpts().CPlusPlus11;
8175 }
8176 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008177}
8178
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008179//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8180
8181/// Check for comparisons of floating point operands using != and ==.
8182/// Issue a warning if these are no self-comparisons, as they are not likely
8183/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008184void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008185 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8186 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008187
8188 // Special case: check for x == x (which is OK).
8189 // Do not emit warnings for such cases.
8190 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8191 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8192 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008193 return;
Mike Stump11289f42009-09-09 15:08:12 +00008194
Ted Kremenekeda40e22007-11-29 00:59:04 +00008195 // Special case: check for comparisons against literals that can be exactly
8196 // represented by APFloat. In such cases, do not emit a warning. This
8197 // is a heuristic: often comparison against such literals are used to
8198 // detect if a value in a variable has not changed. This clearly can
8199 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008200 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8201 if (FLL->isExact())
8202 return;
8203 } else
8204 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8205 if (FLR->isExact())
8206 return;
Mike Stump11289f42009-09-09 15:08:12 +00008207
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008208 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008209 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008210 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008211 return;
Mike Stump11289f42009-09-09 15:08:12 +00008212
David Blaikie1f4ff152012-07-16 20:47:22 +00008213 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008214 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008215 return;
Mike Stump11289f42009-09-09 15:08:12 +00008216
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008217 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008218 Diag(Loc, diag::warn_floatingpoint_eq)
8219 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008220}
John McCallca01b222010-01-04 23:21:16 +00008221
John McCall70aa5392010-01-06 05:24:50 +00008222//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8223//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008224
John McCall70aa5392010-01-06 05:24:50 +00008225namespace {
John McCallca01b222010-01-04 23:21:16 +00008226
John McCall70aa5392010-01-06 05:24:50 +00008227/// Structure recording the 'active' range of an integer-valued
8228/// expression.
8229struct IntRange {
8230 /// The number of bits active in the int.
8231 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008232
John McCall70aa5392010-01-06 05:24:50 +00008233 /// True if the int is known not to have negative values.
8234 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008235
John McCall70aa5392010-01-06 05:24:50 +00008236 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008237 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008238
John McCall817d4af2010-11-10 23:38:19 +00008239 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008240 static IntRange forBoolType() {
8241 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008242 }
8243
John McCall817d4af2010-11-10 23:38:19 +00008244 /// Returns the range of an opaque value of the given integral type.
8245 static IntRange forValueOfType(ASTContext &C, QualType T) {
8246 return forValueOfCanonicalType(C,
8247 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008248 }
8249
John McCall817d4af2010-11-10 23:38:19 +00008250 /// Returns the range of an opaque value of a canonical integral type.
8251 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008252 assert(T->isCanonicalUnqualified());
8253
8254 if (const VectorType *VT = dyn_cast<VectorType>(T))
8255 T = VT->getElementType().getTypePtr();
8256 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8257 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008258 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8259 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008260
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008261 if (!C.getLangOpts().CPlusPlus) {
8262 // For enum types in C code, use the underlying datatype.
8263 if (const EnumType *ET = dyn_cast<EnumType>(T))
8264 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8265 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8266 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008267 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008268 // In C++11, enums can have a fixed underlying type. Use this type to
8269 // compute the range.
8270 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008271 return IntRange(C.getIntWidth(QualType(T, 0)),
8272 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008273 }
John McCall18a2c2c2010-11-09 22:22:12 +00008274
David Majnemer6a426652013-06-07 22:07:20 +00008275 unsigned NumPositive = Enum->getNumPositiveBits();
8276 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008277
David Majnemer6a426652013-06-07 22:07:20 +00008278 if (NumNegative == 0)
8279 return IntRange(NumPositive, true/*NonNegative*/);
8280 else
8281 return IntRange(std::max(NumPositive + 1, NumNegative),
8282 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008283 }
John McCall70aa5392010-01-06 05:24:50 +00008284
8285 const BuiltinType *BT = cast<BuiltinType>(T);
8286 assert(BT->isInteger());
8287
8288 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8289 }
8290
John McCall817d4af2010-11-10 23:38:19 +00008291 /// Returns the "target" range of a canonical integral type, i.e.
8292 /// the range of values expressible in the type.
8293 ///
8294 /// This matches forValueOfCanonicalType except that enums have the
8295 /// full range of their type, not the range of their enumerators.
8296 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8297 assert(T->isCanonicalUnqualified());
8298
8299 if (const VectorType *VT = dyn_cast<VectorType>(T))
8300 T = VT->getElementType().getTypePtr();
8301 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8302 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008303 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8304 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008305 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008306 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008307
8308 const BuiltinType *BT = cast<BuiltinType>(T);
8309 assert(BT->isInteger());
8310
8311 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8312 }
8313
8314 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008315 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008316 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008317 L.NonNegative && R.NonNegative);
8318 }
8319
John McCall817d4af2010-11-10 23:38:19 +00008320 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008321 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008322 return IntRange(std::min(L.Width, R.Width),
8323 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008324 }
8325};
8326
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008327} // namespace
8328
8329static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8330 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008331 if (value.isSigned() && value.isNegative())
8332 return IntRange(value.getMinSignedBits(), false);
8333
8334 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008335 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008336
8337 // isNonNegative() just checks the sign bit without considering
8338 // signedness.
8339 return IntRange(value.getActiveBits(), true);
8340}
8341
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008342static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8343 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008344 if (result.isInt())
8345 return GetValueRange(C, result.getInt(), MaxWidth);
8346
8347 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008348 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8349 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8350 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8351 R = IntRange::join(R, El);
8352 }
John McCall70aa5392010-01-06 05:24:50 +00008353 return R;
8354 }
8355
8356 if (result.isComplexInt()) {
8357 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8358 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8359 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008360 }
8361
8362 // This can happen with lossless casts to intptr_t of "based" lvalues.
8363 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008364 // FIXME: The only reason we need to pass the type in here is to get
8365 // the sign right on this one case. It would be nice if APValue
8366 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008367 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008368 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008369}
John McCall70aa5392010-01-06 05:24:50 +00008370
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008371static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008372 QualType Ty = E->getType();
8373 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8374 Ty = AtomicRHS->getValueType();
8375 return Ty;
8376}
8377
John McCall70aa5392010-01-06 05:24:50 +00008378/// Pseudo-evaluate the given integer expression, estimating the
8379/// range of values it might take.
8380///
8381/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008382static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008383 E = E->IgnoreParens();
8384
8385 // Try a full evaluation first.
8386 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008387 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008388 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008389
8390 // I think we only want to look through implicit casts here; if the
8391 // user has an explicit widening cast, we should treat the value as
8392 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008393 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008394 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008395 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8396
Eli Friedmane6d33952013-07-08 20:20:06 +00008397 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008398
George Burgess IVdf1ed002016-01-13 01:52:39 +00008399 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8400 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008401
John McCall70aa5392010-01-06 05:24:50 +00008402 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008403 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008404 return OutputTypeRange;
8405
8406 IntRange SubRange
8407 = GetExprRange(C, CE->getSubExpr(),
8408 std::min(MaxWidth, OutputTypeRange.Width));
8409
8410 // Bail out if the subexpr's range is as wide as the cast type.
8411 if (SubRange.Width >= OutputTypeRange.Width)
8412 return OutputTypeRange;
8413
8414 // Otherwise, we take the smaller width, and we're non-negative if
8415 // either the output type or the subexpr is.
8416 return IntRange(SubRange.Width,
8417 SubRange.NonNegative || OutputTypeRange.NonNegative);
8418 }
8419
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008420 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008421 // If we can fold the condition, just take that operand.
8422 bool CondResult;
8423 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8424 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8425 : CO->getFalseExpr(),
8426 MaxWidth);
8427
8428 // Otherwise, conservatively merge.
8429 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8430 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8431 return IntRange::join(L, R);
8432 }
8433
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008434 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008435 switch (BO->getOpcode()) {
8436
8437 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008438 case BO_LAnd:
8439 case BO_LOr:
8440 case BO_LT:
8441 case BO_GT:
8442 case BO_LE:
8443 case BO_GE:
8444 case BO_EQ:
8445 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008446 return IntRange::forBoolType();
8447
John McCallc3688382011-07-13 06:35:24 +00008448 // The type of the assignments is the type of the LHS, so the RHS
8449 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008450 case BO_MulAssign:
8451 case BO_DivAssign:
8452 case BO_RemAssign:
8453 case BO_AddAssign:
8454 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008455 case BO_XorAssign:
8456 case BO_OrAssign:
8457 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008458 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008459
John McCallc3688382011-07-13 06:35:24 +00008460 // Simple assignments just pass through the RHS, which will have
8461 // been coerced to the LHS type.
8462 case BO_Assign:
8463 // TODO: bitfields?
8464 return GetExprRange(C, BO->getRHS(), MaxWidth);
8465
John McCall70aa5392010-01-06 05:24:50 +00008466 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008467 case BO_PtrMemD:
8468 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008469 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008470
John McCall2ce81ad2010-01-06 22:07:33 +00008471 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008472 case BO_And:
8473 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008474 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8475 GetExprRange(C, BO->getRHS(), MaxWidth));
8476
John McCall70aa5392010-01-06 05:24:50 +00008477 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008478 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008479 // ...except that we want to treat '1 << (blah)' as logically
8480 // positive. It's an important idiom.
8481 if (IntegerLiteral *I
8482 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8483 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008484 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008485 return IntRange(R.Width, /*NonNegative*/ true);
8486 }
8487 }
8488 // fallthrough
8489
John McCalle3027922010-08-25 11:45:40 +00008490 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008491 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008492
John McCall2ce81ad2010-01-06 22:07:33 +00008493 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008494 case BO_Shr:
8495 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008496 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8497
8498 // If the shift amount is a positive constant, drop the width by
8499 // that much.
8500 llvm::APSInt shift;
8501 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8502 shift.isNonNegative()) {
8503 unsigned zext = shift.getZExtValue();
8504 if (zext >= L.Width)
8505 L.Width = (L.NonNegative ? 0 : 1);
8506 else
8507 L.Width -= zext;
8508 }
8509
8510 return L;
8511 }
8512
8513 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008514 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008515 return GetExprRange(C, BO->getRHS(), MaxWidth);
8516
John McCall2ce81ad2010-01-06 22:07:33 +00008517 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008518 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008519 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008520 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008521 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008522
John McCall51431812011-07-14 22:39:48 +00008523 // The width of a division result is mostly determined by the size
8524 // of the LHS.
8525 case BO_Div: {
8526 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008527 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008528 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8529
8530 // If the divisor is constant, use that.
8531 llvm::APSInt divisor;
8532 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8533 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8534 if (log2 >= L.Width)
8535 L.Width = (L.NonNegative ? 0 : 1);
8536 else
8537 L.Width = std::min(L.Width - log2, MaxWidth);
8538 return L;
8539 }
8540
8541 // Otherwise, just use the LHS's width.
8542 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8543 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8544 }
8545
8546 // The result of a remainder can't be larger than the result of
8547 // either side.
8548 case BO_Rem: {
8549 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008550 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008551 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8552 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8553
8554 IntRange meet = IntRange::meet(L, R);
8555 meet.Width = std::min(meet.Width, MaxWidth);
8556 return meet;
8557 }
8558
8559 // The default behavior is okay for these.
8560 case BO_Mul:
8561 case BO_Add:
8562 case BO_Xor:
8563 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008564 break;
8565 }
8566
John McCall51431812011-07-14 22:39:48 +00008567 // The default case is to treat the operation as if it were closed
8568 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008569 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8570 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8571 return IntRange::join(L, R);
8572 }
8573
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008574 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008575 switch (UO->getOpcode()) {
8576 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008577 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008578 return IntRange::forBoolType();
8579
8580 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008581 case UO_Deref:
8582 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008583 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008584
8585 default:
8586 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8587 }
8588 }
8589
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008590 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008591 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8592
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008593 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008594 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008595 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008596
Eli Friedmane6d33952013-07-08 20:20:06 +00008597 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008598}
John McCall263a48b2010-01-04 23:31:57 +00008599
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008600static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008601 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008602}
8603
John McCall263a48b2010-01-04 23:31:57 +00008604/// Checks whether the given value, which currently has the given
8605/// source semantics, has the same value when coerced through the
8606/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008607static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8608 const llvm::fltSemantics &Src,
8609 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008610 llvm::APFloat truncated = value;
8611
8612 bool ignored;
8613 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8614 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8615
8616 return truncated.bitwiseIsEqual(value);
8617}
8618
8619/// Checks whether the given value, which currently has the given
8620/// source semantics, has the same value when coerced through the
8621/// target semantics.
8622///
8623/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008624static bool IsSameFloatAfterCast(const APValue &value,
8625 const llvm::fltSemantics &Src,
8626 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008627 if (value.isFloat())
8628 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8629
8630 if (value.isVector()) {
8631 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8632 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8633 return false;
8634 return true;
8635 }
8636
8637 assert(value.isComplexFloat());
8638 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8639 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8640}
8641
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008642static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008643
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008644static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008645 // Suppress cases where we are comparing against an enum constant.
8646 if (const DeclRefExpr *DR =
8647 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8648 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008649 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008650
8651 // Suppress cases where the '0' value is expanded from a macro.
8652 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008653 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008654
Roman Lebedev6de129e2017-10-15 20:13:17 +00008655 return false;
8656}
8657
Richard Smith692f66ab2017-12-06 19:23:19 +00008658static bool isKnownToHaveUnsignedValue(Expr *E) {
8659 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00008660 (!E->getType()->isSignedIntegerType() ||
8661 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8662}
8663
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008664namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00008665/// The promoted range of values of a type. In general this has the
8666/// following structure:
8667///
8668/// |-----------| . . . |-----------|
8669/// ^ ^ ^ ^
8670/// Min HoleMin HoleMax Max
8671///
8672/// ... where there is only a hole if a signed type is promoted to unsigned
8673/// (in which case Min and Max are the smallest and largest representable
8674/// values).
8675struct PromotedRange {
8676 // Min, or HoleMax if there is a hole.
8677 llvm::APSInt PromotedMin;
8678 // Max, or HoleMin if there is a hole.
8679 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008680
Richard Smitha5370fb2017-12-08 22:57:11 +00008681 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8682 if (R.Width == 0)
8683 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8684 else if (R.Width >= BitWidth && !Unsigned) {
8685 // Promotion made the type *narrower*. This happens when promoting
8686 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8687 // Treat all values of 'signed int' as being in range for now.
8688 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8689 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8690 } else {
8691 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8692 .extOrTrunc(BitWidth);
8693 PromotedMin.setIsUnsigned(Unsigned);
8694
8695 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8696 .extOrTrunc(BitWidth);
8697 PromotedMax.setIsUnsigned(Unsigned);
8698 }
8699 }
8700
8701 // Determine whether this range is contiguous (has no hole).
8702 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8703
8704 // Where a constant value is within the range.
8705 enum ComparisonResult {
8706 LT = 0x1,
8707 LE = 0x2,
8708 GT = 0x4,
8709 GE = 0x8,
8710 EQ = 0x10,
8711 NE = 0x20,
8712 InRangeFlag = 0x40,
8713
8714 Less = LE | LT | NE,
8715 Min = LE | InRangeFlag,
8716 InRange = InRangeFlag,
8717 Max = GE | InRangeFlag,
8718 Greater = GE | GT | NE,
8719
8720 OnlyValue = LE | GE | EQ | InRangeFlag,
8721 InHole = NE
8722 };
8723
8724 ComparisonResult compare(const llvm::APSInt &Value) const {
8725 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8726 Value.isUnsigned() == PromotedMin.isUnsigned());
8727 if (!isContiguous()) {
8728 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8729 if (Value.isMinValue()) return Min;
8730 if (Value.isMaxValue()) return Max;
8731 if (Value >= PromotedMin) return InRange;
8732 if (Value <= PromotedMax) return InRange;
8733 return InHole;
8734 }
8735
8736 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8737 case -1: return Less;
8738 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8739 case 1:
8740 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8741 case -1: return InRange;
8742 case 0: return Max;
8743 case 1: return Greater;
8744 }
8745 }
8746
8747 llvm_unreachable("impossible compare result");
8748 }
8749
8750 static llvm::Optional<bool> constantValue(BinaryOperatorKind Op,
8751 ComparisonResult R,
8752 bool ConstantOnRHS) {
8753 ComparisonResult TrueFlag, FalseFlag;
8754 if (Op == BO_EQ) {
8755 TrueFlag = EQ;
8756 FalseFlag = NE;
8757 } else if (Op == BO_NE) {
8758 TrueFlag = NE;
8759 FalseFlag = EQ;
8760 } else {
8761 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8762 TrueFlag = LT;
8763 FalseFlag = GE;
8764 } else {
8765 TrueFlag = GT;
8766 FalseFlag = LE;
8767 }
8768 if (Op == BO_GE || Op == BO_LE)
8769 std::swap(TrueFlag, FalseFlag);
8770 }
8771 if (R & TrueFlag)
8772 return true;
8773 if (R & FalseFlag)
8774 return false;
8775 return llvm::None;
8776 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00008777};
John McCallcc7e5bf2010-05-06 08:58:33 +00008778}
8779
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008780static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008781 // Strip off implicit integral promotions.
8782 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008783 if (ICE->getCastKind() != CK_IntegralCast &&
8784 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008785 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008786 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008787 }
8788
8789 return E->getType()->isEnumeralType();
8790}
8791
Richard Smith692f66ab2017-12-06 19:23:19 +00008792static int classifyConstantValue(Expr *Constant) {
8793 // The values of this enumeration are used in the diagnostics
8794 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8795 enum ConstantValueKind {
8796 Miscellaneous = 0,
8797 LiteralTrue,
8798 LiteralFalse
8799 };
8800 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8801 return BL->getValue() ? ConstantValueKind::LiteralTrue
8802 : ConstantValueKind::LiteralFalse;
8803 return ConstantValueKind::Miscellaneous;
8804}
8805
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008806static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8807 Expr *Constant, Expr *Other,
8808 const llvm::APSInt &Value,
8809 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008810 if (S.inTemplateInstantiation())
8811 return false;
8812
Richard Smitha5370fb2017-12-08 22:57:11 +00008813 Expr *OriginalOther = Other;
8814
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008815 Constant = Constant->IgnoreParenImpCasts();
8816 Other = Other->IgnoreParenImpCasts();
8817
Richard Smitha5370fb2017-12-08 22:57:11 +00008818 // Suppress warnings on tautological comparisons between values of the same
8819 // enumeration type. There are only two ways we could warn on this:
8820 // - If the constant is outside the range of representable values of
8821 // the enumeration. In such a case, we should warn about the cast
8822 // to enumeration type, not about the comparison.
8823 // - If the constant is the maximum / minimum in-range value. For an
8824 // enumeratin type, such comparisons can be meaningful and useful.
8825 if (Constant->getType()->isEnumeralType() &&
8826 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8827 return false;
8828
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008829 // TODO: Investigate using GetExprRange() to get tighter bounds
8830 // on the bit ranges.
8831 QualType OtherT = Other->getType();
8832 if (const auto *AT = OtherT->getAs<AtomicType>())
8833 OtherT = AT->getValueType();
8834 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8835
8836 // Whether we're treating Other as being a bool because of the form of
8837 // expression despite it having another type (typically 'int' in C).
8838 bool OtherIsBooleanDespiteType =
8839 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8840 if (OtherIsBooleanDespiteType)
8841 OtherRange = IntRange::forBoolType();
8842
Richard Smitha5370fb2017-12-08 22:57:11 +00008843 // Determine the promoted range of the other type and see if a comparison of
8844 // the constant against that range is tautological.
8845 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8846 Value.isUnsigned());
8847 auto Cmp = OtherPromotedRange.compare(Value);
8848 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8849 if (!Result)
8850 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00008851
Richard Smitha5370fb2017-12-08 22:57:11 +00008852 // Suppress the diagnostic for an in-range comparison if the constant comes
8853 // from a macro or enumerator. We don't want to diagnose
8854 //
8855 // some_long_value <= INT_MAX
8856 //
8857 // when sizeof(int) == sizeof(long).
8858 bool InRange = Cmp & PromotedRange::InRangeFlag;
8859 if (InRange && IsEnumConstOrFromMacro(S, Constant))
8860 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008861
8862 // If this is a comparison to an enum constant, include that
8863 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00008864 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008865 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8866 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8867
Richard Smitha5370fb2017-12-08 22:57:11 +00008868 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008869 SmallString<64> PrettySourceValue;
8870 llvm::raw_svector_ostream OS(PrettySourceValue);
8871 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00008872 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00008873 else
8874 OS << Value;
8875
Richard Smitha5370fb2017-12-08 22:57:11 +00008876 // FIXME: We use a somewhat different formatting for the in-range cases and
8877 // cases involving boolean values for historical reasons. We should pick a
8878 // consistent way of presenting these diagnostics.
8879 if (!InRange || Other->isKnownToHaveBooleanValue()) {
8880 S.DiagRuntimeBehavior(
8881 E->getOperatorLoc(), E,
8882 S.PDiag(!InRange ? diag::warn_out_of_range_compare
8883 : diag::warn_tautological_bool_compare)
8884 << OS.str() << classifyConstantValue(Constant)
8885 << OtherT << OtherIsBooleanDespiteType << *Result
8886 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8887 } else {
8888 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8889 ? (HasEnumType(OriginalOther)
8890 ? diag::warn_unsigned_enum_always_true_comparison
8891 : diag::warn_unsigned_always_true_comparison)
8892 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00008893
Richard Smitha5370fb2017-12-08 22:57:11 +00008894 S.Diag(E->getOperatorLoc(), Diag)
8895 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8896 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8897 }
8898
8899 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008900}
8901
John McCallcc7e5bf2010-05-06 08:58:33 +00008902/// Analyze the operands of the given comparison. Implements the
8903/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008904static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00008905 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8906 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00008907}
John McCall263a48b2010-01-04 23:31:57 +00008908
John McCallca01b222010-01-04 23:21:16 +00008909/// \brief Implements -Wsign-compare.
8910///
Richard Trieu82402a02011-09-15 21:56:47 +00008911/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008912static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008913 // The type the comparison is being performed in.
8914 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00008915
8916 // Only analyze comparison operators where both sides have been converted to
8917 // the same type.
8918 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8919 return AnalyzeImpConvsInComparison(S, E);
8920
8921 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00008922 if (E->isValueDependent())
8923 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008924
Roman Lebedev6de129e2017-10-15 20:13:17 +00008925 Expr *LHS = E->getLHS();
8926 Expr *RHS = E->getRHS();
8927
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008928 if (T->isIntegralType(S.Context)) {
8929 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00008930 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008931
Roman Lebedev6de129e2017-10-15 20:13:17 +00008932 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8933 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00008934
Roman Lebedev6de129e2017-10-15 20:13:17 +00008935 // We don't care about expressions whose result is a constant.
8936 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8937 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00008938
Roman Lebedev6de129e2017-10-15 20:13:17 +00008939 // We only care about expressions where just one side is literal
8940 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8941 // Is the constant on the RHS or LHS?
8942 const bool RhsConstant = IsRHSIntegralLiteral;
8943 Expr *Const = RhsConstant ? RHS : LHS;
8944 Expr *Other = RhsConstant ? LHS : RHS;
8945 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8946
8947 // Check whether an integer constant comparison results in a value
8948 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00008949 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8950 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008951 }
8952 }
8953
8954 if (!T->hasUnsignedIntegerRepresentation()) {
8955 // We don't do anything special if this isn't an unsigned integral
8956 // comparison: we're only interested in integral comparisons, and
8957 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00008958 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00008959 }
8960
8961 LHS = LHS->IgnoreParenImpCasts();
8962 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008963
John McCallcc7e5bf2010-05-06 08:58:33 +00008964 // Check to see if one of the (unmodified) operands is of different
8965 // signedness.
8966 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00008967 if (LHS->getType()->hasSignedIntegerRepresentation()) {
8968 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00008969 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00008970 signedOperand = LHS;
8971 unsignedOperand = RHS;
8972 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8973 signedOperand = RHS;
8974 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00008975 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00008976 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00008977 }
8978
John McCallcc7e5bf2010-05-06 08:58:33 +00008979 // Otherwise, calculate the effective range of the signed operand.
8980 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00008981
John McCallcc7e5bf2010-05-06 08:58:33 +00008982 // Go ahead and analyze implicit conversions in the operands. Note
8983 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00008984 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8985 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00008986
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008987 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00008988 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00008989 return;
John McCallca01b222010-01-04 23:21:16 +00008990
8991 // For (in)equality comparisons, if the unsigned operand is a
8992 // constant which cannot collide with a overflowed signed operand,
8993 // then reinterpreting the signed operand as unsigned will not
8994 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00008995 if (E->isEqualityOp()) {
8996 unsigned comparisonWidth = S.Context.getIntWidth(T);
8997 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00008998
John McCallcc7e5bf2010-05-06 08:58:33 +00008999 // We should never be unable to prove that the unsigned operand is
9000 // non-negative.
9001 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9002
9003 if (unsignedRange.Width < comparisonWidth)
9004 return;
9005 }
9006
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009007 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9008 S.PDiag(diag::warn_mixed_sign_comparison)
9009 << LHS->getType() << RHS->getType()
9010 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009011}
9012
John McCall1f425642010-11-11 03:21:53 +00009013/// Analyzes an attempt to assign the given value to a bitfield.
9014///
9015/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009016static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9017 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009018 assert(Bitfield->isBitField());
9019 if (Bitfield->isInvalidDecl())
9020 return false;
9021
John McCalldeebbcf2010-11-11 05:33:51 +00009022 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009023 QualType BitfieldType = Bitfield->getType();
9024 if (BitfieldType->isBooleanType())
9025 return false;
9026
9027 if (BitfieldType->isEnumeralType()) {
9028 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9029 // If the underlying enum type was not explicitly specified as an unsigned
9030 // type and the enum contain only positive values, MSVC++ will cause an
9031 // inconsistency by storing this as a signed type.
9032 if (S.getLangOpts().CPlusPlus11 &&
9033 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9034 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9035 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9036 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9037 << BitfieldEnumDecl->getNameAsString();
9038 }
9039 }
9040
John McCalldeebbcf2010-11-11 05:33:51 +00009041 if (Bitfield->getType()->isBooleanType())
9042 return false;
9043
Douglas Gregor789adec2011-02-04 13:09:01 +00009044 // Ignore value- or type-dependent expressions.
9045 if (Bitfield->getBitWidth()->isValueDependent() ||
9046 Bitfield->getBitWidth()->isTypeDependent() ||
9047 Init->isValueDependent() ||
9048 Init->isTypeDependent())
9049 return false;
9050
John McCall1f425642010-11-11 03:21:53 +00009051 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009052 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009053
Richard Smith5fab0c92011-12-28 19:48:30 +00009054 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009055 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9056 Expr::SE_AllowSideEffects)) {
9057 // The RHS is not constant. If the RHS has an enum type, make sure the
9058 // bitfield is wide enough to hold all the values of the enum without
9059 // truncation.
9060 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9061 EnumDecl *ED = EnumTy->getDecl();
9062 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9063
9064 // Enum types are implicitly signed on Windows, so check if there are any
9065 // negative enumerators to see if the enum was intended to be signed or
9066 // not.
9067 bool SignedEnum = ED->getNumNegativeBits() > 0;
9068
9069 // Check for surprising sign changes when assigning enum values to a
9070 // bitfield of different signedness. If the bitfield is signed and we
9071 // have exactly the right number of bits to store this unsigned enum,
9072 // suggest changing the enum to an unsigned type. This typically happens
9073 // on Windows where unfixed enums always use an underlying type of 'int'.
9074 unsigned DiagID = 0;
9075 if (SignedEnum && !SignedBitfield) {
9076 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9077 } else if (SignedBitfield && !SignedEnum &&
9078 ED->getNumPositiveBits() == FieldWidth) {
9079 DiagID = diag::warn_signed_bitfield_enum_conversion;
9080 }
9081
9082 if (DiagID) {
9083 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9084 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9085 SourceRange TypeRange =
9086 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9087 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9088 << SignedEnum << TypeRange;
9089 }
9090
9091 // Compute the required bitwidth. If the enum has negative values, we need
9092 // one more bit than the normal number of positive bits to represent the
9093 // sign bit.
9094 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9095 ED->getNumNegativeBits())
9096 : ED->getNumPositiveBits();
9097
9098 // Check the bitwidth.
9099 if (BitsNeeded > FieldWidth) {
9100 Expr *WidthExpr = Bitfield->getBitWidth();
9101 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9102 << Bitfield << ED;
9103 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9104 << BitsNeeded << ED << WidthExpr->getSourceRange();
9105 }
9106 }
9107
John McCall1f425642010-11-11 03:21:53 +00009108 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009109 }
John McCall1f425642010-11-11 03:21:53 +00009110
John McCall1f425642010-11-11 03:21:53 +00009111 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009112
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009113 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009114 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009115 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9116 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009117
John McCall1f425642010-11-11 03:21:53 +00009118 if (OriginalWidth <= FieldWidth)
9119 return false;
9120
Eli Friedmanc267a322012-01-26 23:11:39 +00009121 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009122 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009123 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009124
Eli Friedmanc267a322012-01-26 23:11:39 +00009125 // Check whether the stored value is equal to the original value.
9126 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009127 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009128 return false;
9129
Eli Friedmanc267a322012-01-26 23:11:39 +00009130 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009131 // therefore don't strictly fit into a signed bitfield of width 1.
9132 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009133 return false;
9134
John McCall1f425642010-11-11 03:21:53 +00009135 std::string PrettyValue = Value.toString(10);
9136 std::string PrettyTrunc = TruncatedValue.toString(10);
9137
9138 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9139 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9140 << Init->getSourceRange();
9141
9142 return true;
9143}
9144
John McCalld2a53122010-11-09 23:24:47 +00009145/// Analyze the given simple or compound assignment for warning-worthy
9146/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009147static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009148 // Just recurse on the LHS.
9149 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9150
9151 // We want to recurse on the RHS as normal unless we're assigning to
9152 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009153 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009154 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009155 E->getOperatorLoc())) {
9156 // Recurse, ignoring any implicit conversions on the RHS.
9157 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9158 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009159 }
9160 }
9161
9162 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9163}
9164
John McCall263a48b2010-01-04 23:31:57 +00009165/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009166static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9167 SourceLocation CContext, unsigned diag,
9168 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009169 if (pruneControlFlow) {
9170 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9171 S.PDiag(diag)
9172 << SourceType << T << E->getSourceRange()
9173 << SourceRange(CContext));
9174 return;
9175 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009176 S.Diag(E->getExprLoc(), diag)
9177 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9178}
9179
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009180/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009181static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9182 SourceLocation CContext,
9183 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009184 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009185}
9186
Richard Trieube234c32016-04-21 21:04:55 +00009187
9188/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009189static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9190 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009191 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009192 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009193
9194 Expr *InnerE = E->IgnoreParenImpCasts();
9195 // We also want to warn on, e.g., "int i = -1.234"
9196 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9197 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9198 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9199
9200 const bool IsLiteral =
9201 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9202
9203 llvm::APFloat Value(0.0);
9204 bool IsConstant =
9205 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9206 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009207 return DiagnoseImpCast(S, E, T, CContext,
9208 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009209 }
9210
Chandler Carruth016ef402011-04-10 08:36:24 +00009211 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009212
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009213 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9214 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009215 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9216 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009217 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009218 if (IsLiteral) return;
9219 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9220 PruneWarnings);
9221 }
9222
9223 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009224 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009225 // Warn on floating point literal to integer.
9226 DiagID = diag::warn_impcast_literal_float_to_integer;
9227 } else if (IntegerValue == 0) {
9228 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9229 return DiagnoseImpCast(S, E, T, CContext,
9230 diag::warn_impcast_float_integer, PruneWarnings);
9231 }
9232 // Warn on non-zero to zero conversion.
9233 DiagID = diag::warn_impcast_float_to_integer_zero;
9234 } else {
9235 if (IntegerValue.isUnsigned()) {
9236 if (!IntegerValue.isMaxValue()) {
9237 return DiagnoseImpCast(S, E, T, CContext,
9238 diag::warn_impcast_float_integer, PruneWarnings);
9239 }
9240 } else { // IntegerValue.isSigned()
9241 if (!IntegerValue.isMaxSignedValue() &&
9242 !IntegerValue.isMinSignedValue()) {
9243 return DiagnoseImpCast(S, E, T, CContext,
9244 diag::warn_impcast_float_integer, PruneWarnings);
9245 }
9246 }
9247 // Warn on evaluatable floating point expression to integer conversion.
9248 DiagID = diag::warn_impcast_float_to_integer;
9249 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009250
Eli Friedman07185912013-08-29 23:44:43 +00009251 // FIXME: Force the precision of the source value down so we don't print
9252 // digits which are usually useless (we don't really care here if we
9253 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9254 // would automatically print the shortest representation, but it's a bit
9255 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009256 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009257 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9258 precision = (precision * 59 + 195) / 196;
9259 Value.toString(PrettySourceValue, precision);
9260
David Blaikie9b88cc02012-05-15 17:18:27 +00009261 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009262 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009263 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009264 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009265 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009266
Richard Trieube234c32016-04-21 21:04:55 +00009267 if (PruneWarnings) {
9268 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9269 S.PDiag(DiagID)
9270 << E->getType() << T.getUnqualifiedType()
9271 << PrettySourceValue << PrettyTargetValue
9272 << E->getSourceRange() << SourceRange(CContext));
9273 } else {
9274 S.Diag(E->getExprLoc(), DiagID)
9275 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9276 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9277 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009278}
9279
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009280static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9281 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009282 if (!Range.Width) return "0";
9283
9284 llvm::APSInt ValueInRange = Value;
9285 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009286 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009287 return ValueInRange.toString(10);
9288}
9289
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009290static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009291 if (!isa<ImplicitCastExpr>(Ex))
9292 return false;
9293
9294 Expr *InnerE = Ex->IgnoreParenImpCasts();
9295 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9296 const Type *Source =
9297 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9298 if (Target->isDependentType())
9299 return false;
9300
9301 const BuiltinType *FloatCandidateBT =
9302 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9303 const Type *BoolCandidateType = ToBool ? Target : Source;
9304
9305 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9306 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9307}
9308
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009309static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9310 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009311 unsigned NumArgs = TheCall->getNumArgs();
9312 for (unsigned i = 0; i < NumArgs; ++i) {
9313 Expr *CurrA = TheCall->getArg(i);
9314 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9315 continue;
9316
9317 bool IsSwapped = ((i > 0) &&
9318 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9319 IsSwapped |= ((i < (NumArgs - 1)) &&
9320 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9321 if (IsSwapped) {
9322 // Warn on this floating-point to bool conversion.
9323 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9324 CurrA->getType(), CC,
9325 diag::warn_impcast_floating_point_to_bool);
9326 }
9327 }
9328}
9329
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009330static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9331 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009332 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9333 E->getExprLoc()))
9334 return;
9335
Richard Trieu09d6b802016-01-08 23:35:06 +00009336 // Don't warn on functions which have return type nullptr_t.
9337 if (isa<CallExpr>(E))
9338 return;
9339
Richard Trieu5b993502014-10-15 03:42:06 +00009340 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9341 const Expr::NullPointerConstantKind NullKind =
9342 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9343 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9344 return;
9345
9346 // Return if target type is a safe conversion.
9347 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9348 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9349 return;
9350
9351 SourceLocation Loc = E->getSourceRange().getBegin();
9352
Richard Trieu0a5e1662016-02-13 00:58:53 +00009353 // Venture through the macro stacks to get to the source of macro arguments.
9354 // The new location is a better location than the complete location that was
9355 // passed in.
9356 while (S.SourceMgr.isMacroArgExpansion(Loc))
9357 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9358
9359 while (S.SourceMgr.isMacroArgExpansion(CC))
9360 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9361
Richard Trieu5b993502014-10-15 03:42:06 +00009362 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009363 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9364 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9365 Loc, S.SourceMgr, S.getLangOpts());
9366 if (MacroName == "NULL")
9367 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009368 }
9369
9370 // Only warn if the null and context location are in the same macro expansion.
9371 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9372 return;
9373
9374 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009375 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009376 << FixItHint::CreateReplacement(Loc,
9377 S.getFixItZeroLiteralForType(T, Loc));
9378}
9379
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009380static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9381 ObjCArrayLiteral *ArrayLiteral);
9382
9383static void
9384checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9385 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009386
9387/// Check a single element within a collection literal against the
9388/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009389static void checkObjCCollectionLiteralElement(Sema &S,
9390 QualType TargetElementType,
9391 Expr *Element,
9392 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009393 // Skip a bitcast to 'id' or qualified 'id'.
9394 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9395 if (ICE->getCastKind() == CK_BitCast &&
9396 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9397 Element = ICE->getSubExpr();
9398 }
9399
9400 QualType ElementType = Element->getType();
9401 ExprResult ElementResult(Element);
9402 if (ElementType->getAs<ObjCObjectPointerType>() &&
9403 S.CheckSingleAssignmentConstraints(TargetElementType,
9404 ElementResult,
9405 false, false)
9406 != Sema::Compatible) {
9407 S.Diag(Element->getLocStart(),
9408 diag::warn_objc_collection_literal_element)
9409 << ElementType << ElementKind << TargetElementType
9410 << Element->getSourceRange();
9411 }
9412
9413 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9414 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9415 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9416 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9417}
9418
9419/// Check an Objective-C array literal being converted to the given
9420/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009421static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9422 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009423 if (!S.NSArrayDecl)
9424 return;
9425
9426 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9427 if (!TargetObjCPtr)
9428 return;
9429
9430 if (TargetObjCPtr->isUnspecialized() ||
9431 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9432 != S.NSArrayDecl->getCanonicalDecl())
9433 return;
9434
9435 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9436 if (TypeArgs.size() != 1)
9437 return;
9438
9439 QualType TargetElementType = TypeArgs[0];
9440 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9441 checkObjCCollectionLiteralElement(S, TargetElementType,
9442 ArrayLiteral->getElement(I),
9443 0);
9444 }
9445}
9446
9447/// Check an Objective-C dictionary literal being converted to the given
9448/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009449static void
9450checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9451 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009452 if (!S.NSDictionaryDecl)
9453 return;
9454
9455 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9456 if (!TargetObjCPtr)
9457 return;
9458
9459 if (TargetObjCPtr->isUnspecialized() ||
9460 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9461 != S.NSDictionaryDecl->getCanonicalDecl())
9462 return;
9463
9464 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9465 if (TypeArgs.size() != 2)
9466 return;
9467
9468 QualType TargetKeyType = TypeArgs[0];
9469 QualType TargetObjectType = TypeArgs[1];
9470 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9471 auto Element = DictionaryLiteral->getKeyValueElement(I);
9472 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9473 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9474 }
9475}
9476
Richard Trieufc404c72016-02-05 23:02:38 +00009477// Helper function to filter out cases for constant width constant conversion.
9478// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009479static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9480 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009481 // If initializing from a constant, and the constant starts with '0',
9482 // then it is a binary, octal, or hexadecimal. Allow these constants
9483 // to fill all the bits, even if there is a sign change.
9484 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9485 const char FirstLiteralCharacter =
9486 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9487 if (FirstLiteralCharacter == '0')
9488 return false;
9489 }
9490
9491 // If the CC location points to a '{', and the type is char, then assume
9492 // assume it is an array initialization.
9493 if (CC.isValid() && T->isCharType()) {
9494 const char FirstContextCharacter =
9495 S.getSourceManager().getCharacterData(CC)[0];
9496 if (FirstContextCharacter == '{')
9497 return false;
9498 }
9499
9500 return true;
9501}
9502
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009503static void
9504CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9505 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009506 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009507
John McCallcc7e5bf2010-05-06 08:58:33 +00009508 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9509 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9510 if (Source == Target) return;
9511 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009512
Chandler Carruthc22845a2011-07-26 05:40:03 +00009513 // If the conversion context location is invalid don't complain. We also
9514 // don't want to emit a warning if the issue occurs from the expansion of
9515 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9516 // delay this check as long as possible. Once we detect we are in that
9517 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009518 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009519 return;
9520
Richard Trieu021baa32011-09-23 20:10:00 +00009521 // Diagnose implicit casts to bool.
9522 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9523 if (isa<StringLiteral>(E))
9524 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009525 // and expressions, for instance, assert(0 && "error here"), are
9526 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009527 return DiagnoseImpCast(S, E, T, CC,
9528 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009529 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9530 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9531 // This covers the literal expressions that evaluate to Objective-C
9532 // objects.
9533 return DiagnoseImpCast(S, E, T, CC,
9534 diag::warn_impcast_objective_c_literal_to_bool);
9535 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009536 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9537 // Warn on pointer to bool conversion that is always true.
9538 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9539 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009540 }
Richard Trieu021baa32011-09-23 20:10:00 +00009541 }
John McCall263a48b2010-01-04 23:31:57 +00009542
Douglas Gregor5054cb02015-07-07 03:58:22 +00009543 // Check implicit casts from Objective-C collection literals to specialized
9544 // collection types, e.g., NSArray<NSString *> *.
9545 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9546 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9547 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9548 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9549
John McCall263a48b2010-01-04 23:31:57 +00009550 // Strip vector types.
9551 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009552 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009553 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009554 return;
John McCallacf0ee52010-10-08 02:01:28 +00009555 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009556 }
Chris Lattneree7286f2011-06-14 04:51:15 +00009557
9558 // If the vector cast is cast between two vectors of the same size, it is
9559 // a bitcast, not a conversion.
9560 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9561 return;
John McCall263a48b2010-01-04 23:31:57 +00009562
9563 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9564 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9565 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009566 if (auto VecTy = dyn_cast<VectorType>(Target))
9567 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009568
9569 // Strip complex types.
9570 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009571 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009572 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009573 return;
9574
Tim Northover02416372017-08-08 23:18:05 +00009575 return DiagnoseImpCast(S, E, T, CC,
9576 S.getLangOpts().CPlusPlus
9577 ? diag::err_impcast_complex_scalar
9578 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009579 }
John McCall263a48b2010-01-04 23:31:57 +00009580
9581 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9582 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9583 }
9584
9585 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9586 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9587
9588 // If the source is floating point...
9589 if (SourceBT && SourceBT->isFloatingPoint()) {
9590 // ...and the target is floating point...
9591 if (TargetBT && TargetBT->isFloatingPoint()) {
9592 // ...then warn if we're dropping FP rank.
9593
9594 // Builtin FP kinds are ordered by increasing FP rank.
9595 if (SourceBT->getKind() > TargetBT->getKind()) {
9596 // Don't warn about float constants that are precisely
9597 // representable in the target type.
9598 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009599 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009600 // Value might be a float, a float vector, or a float complex.
9601 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009602 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9603 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009604 return;
9605 }
9606
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009607 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009608 return;
9609
John McCallacf0ee52010-10-08 02:01:28 +00009610 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009611 }
9612 // ... or possibly if we're increasing rank, too
9613 else if (TargetBT->getKind() > SourceBT->getKind()) {
9614 if (S.SourceMgr.isInSystemMacro(CC))
9615 return;
9616
9617 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009618 }
9619 return;
9620 }
9621
Richard Trieube234c32016-04-21 21:04:55 +00009622 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009623 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009624 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009625 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009626
Richard Trieube234c32016-04-21 21:04:55 +00009627 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009628 }
John McCall263a48b2010-01-04 23:31:57 +00009629
Richard Smith54894fd2015-12-30 01:06:52 +00009630 // Detect the case where a call result is converted from floating-point to
9631 // to bool, and the final argument to the call is converted from bool, to
9632 // discover this typo:
9633 //
9634 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9635 //
9636 // FIXME: This is an incredibly special case; is there some more general
9637 // way to detect this class of misplaced-parentheses bug?
9638 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009639 // Check last argument of function call to see if it is an
9640 // implicit cast from a type matching the type the result
9641 // is being cast to.
9642 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009643 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009644 Expr *LastA = CEx->getArg(NumArgs - 1);
9645 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009646 if (isa<ImplicitCastExpr>(LastA) &&
9647 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009648 // Warn on this floating-point to bool conversion
9649 DiagnoseImpCast(S, E, T, CC,
9650 diag::warn_impcast_floating_point_to_bool);
9651 }
9652 }
9653 }
John McCall263a48b2010-01-04 23:31:57 +00009654 return;
9655 }
9656
Richard Trieu5b993502014-10-15 03:42:06 +00009657 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009658
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009659 S.DiscardMisalignedMemberAddress(Target, E);
9660
David Blaikie9366d2b2012-06-19 21:19:06 +00009661 if (!Source->isIntegerType() || !Target->isIntegerType())
9662 return;
9663
David Blaikie7555b6a2012-05-15 16:56:36 +00009664 // TODO: remove this early return once the false positives for constant->bool
9665 // in templates, macros, etc, are reduced or removed.
9666 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9667 return;
9668
John McCallcc7e5bf2010-05-06 08:58:33 +00009669 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009670 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009671
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009672 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009673 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009674 // TODO: this should happen for bitfield stores, too.
9675 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009676 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009677 if (S.SourceMgr.isInSystemMacro(CC))
9678 return;
9679
John McCall18a2c2c2010-11-09 22:22:12 +00009680 std::string PrettySourceValue = Value.toString(10);
9681 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009682
Ted Kremenek33ba9952011-10-22 02:37:33 +00009683 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9684 S.PDiag(diag::warn_impcast_integer_precision_constant)
9685 << PrettySourceValue << PrettyTargetValue
9686 << E->getType() << T << E->getSourceRange()
9687 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009688 return;
9689 }
9690
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009691 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9692 if (S.SourceMgr.isInSystemMacro(CC))
9693 return;
9694
David Blaikie9455da02012-04-12 22:40:54 +00009695 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009696 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9697 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009698 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009699 }
9700
Richard Trieudcb55572016-01-29 23:51:16 +00009701 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9702 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9703 // Warn when doing a signed to signed conversion, warn if the positive
9704 // source value is exactly the width of the target type, which will
9705 // cause a negative value to be stored.
9706
9707 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009708 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9709 !S.SourceMgr.isInSystemMacro(CC)) {
9710 if (isSameWidthConstantConversion(S, E, T, CC)) {
9711 std::string PrettySourceValue = Value.toString(10);
9712 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009713
Richard Trieufc404c72016-02-05 23:02:38 +00009714 S.DiagRuntimeBehavior(
9715 E->getExprLoc(), E,
9716 S.PDiag(diag::warn_impcast_integer_precision_constant)
9717 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9718 << E->getSourceRange() << clang::SourceRange(CC));
9719 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009720 }
9721 }
Richard Trieufc404c72016-02-05 23:02:38 +00009722
Richard Trieudcb55572016-01-29 23:51:16 +00009723 // Fall through for non-constants to give a sign conversion warning.
9724 }
9725
John McCallcc7e5bf2010-05-06 08:58:33 +00009726 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9727 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9728 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009729 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009730 return;
9731
John McCallcc7e5bf2010-05-06 08:58:33 +00009732 unsigned DiagID = diag::warn_impcast_integer_sign;
9733
9734 // Traditionally, gcc has warned about this under -Wsign-compare.
9735 // We also want to warn about it in -Wconversion.
9736 // So if -Wconversion is off, use a completely identical diagnostic
9737 // in the sign-compare group.
9738 // The conditional-checking code will
9739 if (ICContext) {
9740 DiagID = diag::warn_impcast_integer_sign_conditional;
9741 *ICContext = true;
9742 }
9743
John McCallacf0ee52010-10-08 02:01:28 +00009744 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009745 }
9746
Douglas Gregora78f1932011-02-22 02:45:07 +00009747 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009748 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9749 // type, to give us better diagnostics.
9750 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009751 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009752 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9753 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9754 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9755 SourceType = S.Context.getTypeDeclType(Enum);
9756 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9757 }
9758 }
9759
Douglas Gregora78f1932011-02-22 02:45:07 +00009760 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9761 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009762 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9763 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009764 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009765 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009766 return;
9767
Douglas Gregor364f7db2011-03-12 00:14:31 +00009768 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009769 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009770 }
John McCall263a48b2010-01-04 23:31:57 +00009771}
9772
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009773static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9774 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009775
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009776static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9777 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009778 E = E->IgnoreParenImpCasts();
9779
9780 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009781 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009782
John McCallacf0ee52010-10-08 02:01:28 +00009783 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009784 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009785 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009786}
9787
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009788static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9789 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009790 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009791
9792 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009793 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9794 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009795
9796 // If -Wconversion would have warned about either of the candidates
9797 // for a signedness conversion to the context type...
9798 if (!Suspicious) return;
9799
9800 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009801 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00009802 return;
9803
John McCallcc7e5bf2010-05-06 08:58:33 +00009804 // ...then check whether it would have warned about either of the
9805 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00009806 if (E->getType() == T) return;
9807
9808 Suspicious = false;
9809 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9810 E->getType(), CC, &Suspicious);
9811 if (!Suspicious)
9812 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00009813 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009814}
9815
Richard Trieu65724892014-11-15 06:37:39 +00009816/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9817/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009818static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00009819 if (S.getLangOpts().Bool)
9820 return;
9821 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9822}
9823
John McCallcc7e5bf2010-05-06 08:58:33 +00009824/// AnalyzeImplicitConversions - Find and report any interesting
9825/// implicit conversions in the given expression. There are a couple
9826/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009827static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9828 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00009829 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00009830 Expr *E = OrigE->IgnoreParenImpCasts();
9831
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00009832 if (E->isTypeDependent() || E->isValueDependent())
9833 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00009834
John McCallcc7e5bf2010-05-06 08:58:33 +00009835 // For conditional operators, we analyze the arguments as if they
9836 // were being fed directly into the output.
9837 if (isa<ConditionalOperator>(E)) {
9838 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00009839 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009840 return;
9841 }
9842
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009843 // Check implicit argument conversions for function calls.
9844 if (CallExpr *Call = dyn_cast<CallExpr>(E))
9845 CheckImplicitArgumentConversions(S, Call, CC);
9846
John McCallcc7e5bf2010-05-06 08:58:33 +00009847 // Go ahead and check any implicit conversions we might have skipped.
9848 // The non-canonical typecheck is just an optimization;
9849 // CheckImplicitConversion will filter out dead implicit conversions.
9850 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009851 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009852
9853 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00009854
9855 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9856 // The bound subexpressions in a PseudoObjectExpr are not reachable
9857 // as transitive children.
9858 // FIXME: Use a more uniform representation for this.
9859 for (auto *SE : POE->semantics())
9860 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9861 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00009862 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00009863
John McCallcc7e5bf2010-05-06 08:58:33 +00009864 // Skip past explicit casts.
9865 if (isa<ExplicitCastExpr>(E)) {
9866 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00009867 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009868 }
9869
John McCalld2a53122010-11-09 23:24:47 +00009870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9871 // Do a somewhat different check with comparison operators.
9872 if (BO->isComparisonOp())
9873 return AnalyzeComparison(S, BO);
9874
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009875 // And with simple assignments.
9876 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00009877 return AnalyzeAssignment(S, BO);
9878 }
John McCallcc7e5bf2010-05-06 08:58:33 +00009879
9880 // These break the otherwise-useful invariant below. Fortunately,
9881 // we don't really need to recurse into them, because any internal
9882 // expressions should have been analyzed already when they were
9883 // built into statements.
9884 if (isa<StmtExpr>(E)) return;
9885
9886 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00009887 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00009888
9889 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00009890 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00009891 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00009892 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00009893 for (Stmt *SubStmt : E->children()) {
9894 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00009895 if (!ChildExpr)
9896 continue;
9897
Richard Trieu955231d2014-01-25 01:10:35 +00009898 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00009899 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00009900 // Ignore checking string literals that are in logical and operators.
9901 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00009902 continue;
9903 AnalyzeImplicitConversions(S, ChildExpr, CC);
9904 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009905
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009906 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00009907 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9908 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009909 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00009910
9911 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9912 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00009913 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009914 }
Richard Trieu791b86e2014-11-19 06:08:18 +00009915
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00009916 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9917 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00009918 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009919}
9920
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009921/// Diagnose integer type and any valid implicit convertion to it.
9922static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9923 // Taking into account implicit conversions,
9924 // allow any integer.
9925 if (!E->getType()->isIntegerType()) {
9926 S.Diag(E->getLocStart(),
9927 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9928 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009929 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +00009930 // Potentially emit standard warnings for implicit conversions if enabled
9931 // using -Wconversion.
9932 CheckImplicitConversion(S, E, IntT, E->getLocStart());
9933 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00009934}
9935
Richard Trieuc1888e02014-06-28 23:25:37 +00009936// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9937// Returns true when emitting a warning about taking the address of a reference.
9938static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +00009939 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +00009940 E = E->IgnoreParenImpCasts();
9941
9942 const FunctionDecl *FD = nullptr;
9943
9944 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9945 if (!DRE->getDecl()->getType()->isReferenceType())
9946 return false;
9947 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9948 if (!M->getMemberDecl()->getType()->isReferenceType())
9949 return false;
9950 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00009951 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00009952 return false;
9953 FD = Call->getDirectCallee();
9954 } else {
9955 return false;
9956 }
9957
9958 SemaRef.Diag(E->getExprLoc(), PD);
9959
9960 // If possible, point to location of function.
9961 if (FD) {
9962 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9963 }
9964
9965 return true;
9966}
9967
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009968// Returns true if the SourceLocation is expanded from any macro body.
9969// Returns false if the SourceLocation is invalid, is from not in a macro
9970// expansion, or is from expanded from a top-level macro argument.
9971static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9972 if (Loc.isInvalid())
9973 return false;
9974
9975 while (Loc.isMacroID()) {
9976 if (SM.isMacroBodyExpansion(Loc))
9977 return true;
9978 Loc = SM.getImmediateMacroCallerLoc(Loc);
9979 }
9980
9981 return false;
9982}
9983
Richard Trieu3bb8b562014-02-26 02:36:06 +00009984/// \brief Diagnose pointers that are always non-null.
9985/// \param E the expression containing the pointer
9986/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9987/// compared to a null pointer
9988/// \param IsEqual True when the comparison is equal to a null pointer
9989/// \param Range Extra SourceRange to highlight in the diagnostic
9990void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9991 Expr::NullPointerConstantKind NullKind,
9992 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00009993 if (!E)
9994 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00009995
9996 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00009997 if (E->getExprLoc().isMacroID()) {
9998 const SourceManager &SM = getSourceManager();
9999 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10000 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010001 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010002 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010003 E = E->IgnoreImpCasts();
10004
10005 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10006
Richard Trieuf7432752014-06-06 21:39:26 +000010007 if (isa<CXXThisExpr>(E)) {
10008 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10009 : diag::warn_this_bool_conversion;
10010 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10011 return;
10012 }
10013
Richard Trieu3bb8b562014-02-26 02:36:06 +000010014 bool IsAddressOf = false;
10015
10016 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10017 if (UO->getOpcode() != UO_AddrOf)
10018 return;
10019 IsAddressOf = true;
10020 E = UO->getSubExpr();
10021 }
10022
Richard Trieuc1888e02014-06-28 23:25:37 +000010023 if (IsAddressOf) {
10024 unsigned DiagID = IsCompare
10025 ? diag::warn_address_of_reference_null_compare
10026 : diag::warn_address_of_reference_bool_conversion;
10027 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10028 << IsEqual;
10029 if (CheckForReference(*this, E, PD)) {
10030 return;
10031 }
10032 }
10033
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010034 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10035 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010036 std::string Str;
10037 llvm::raw_string_ostream S(Str);
10038 E->printPretty(S, nullptr, getPrintingPolicy());
10039 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10040 : diag::warn_cast_nonnull_to_bool;
10041 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10042 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010043 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010044 };
10045
10046 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10047 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10048 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010049 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10050 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010051 return;
10052 }
10053 }
10054 }
10055
Richard Trieu3bb8b562014-02-26 02:36:06 +000010056 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010057 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010058 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10059 D = R->getDecl();
10060 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10061 D = M->getMemberDecl();
10062 }
10063
10064 // Weak Decls can be null.
10065 if (!D || D->isWeak())
10066 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010067
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010068 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010069 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10070 if (getCurFunction() &&
10071 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010072 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10073 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010074 return;
10075 }
10076
10077 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010078 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010079 assert(ParamIter != FD->param_end());
10080 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10081
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010082 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10083 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010084 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010085 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010086 }
George Burgess IV850269a2015-12-08 22:02:00 +000010087
10088 for (unsigned ArgNo : NonNull->args()) {
10089 if (ArgNo == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010090 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010091 return;
10092 }
George Burgess IV850269a2015-12-08 22:02:00 +000010093 }
10094 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010095 }
10096 }
George Burgess IV850269a2015-12-08 22:02:00 +000010097 }
10098
Richard Trieu3bb8b562014-02-26 02:36:06 +000010099 QualType T = D->getType();
10100 const bool IsArray = T->isArrayType();
10101 const bool IsFunction = T->isFunctionType();
10102
Richard Trieuc1888e02014-06-28 23:25:37 +000010103 // Address of function is used to silence the function warning.
10104 if (IsAddressOf && IsFunction) {
10105 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010106 }
10107
10108 // Found nothing.
10109 if (!IsAddressOf && !IsFunction && !IsArray)
10110 return;
10111
10112 // Pretty print the expression for the diagnostic.
10113 std::string Str;
10114 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010115 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010116
10117 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10118 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010119 enum {
10120 AddressOf,
10121 FunctionPointer,
10122 ArrayPointer
10123 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010124 if (IsAddressOf)
10125 DiagType = AddressOf;
10126 else if (IsFunction)
10127 DiagType = FunctionPointer;
10128 else if (IsArray)
10129 DiagType = ArrayPointer;
10130 else
10131 llvm_unreachable("Could not determine diagnostic.");
10132 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10133 << Range << IsEqual;
10134
10135 if (!IsFunction)
10136 return;
10137
10138 // Suggest '&' to silence the function warning.
10139 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10140 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10141
10142 // Check to see if '()' fixit should be emitted.
10143 QualType ReturnType;
10144 UnresolvedSet<4> NonTemplateOverloads;
10145 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10146 if (ReturnType.isNull())
10147 return;
10148
10149 if (IsCompare) {
10150 // There are two cases here. If there is null constant, the only suggest
10151 // for a pointer return type. If the null is 0, then suggest if the return
10152 // type is a pointer or an integer type.
10153 if (!ReturnType->isPointerType()) {
10154 if (NullKind == Expr::NPCK_ZeroExpression ||
10155 NullKind == Expr::NPCK_ZeroLiteral) {
10156 if (!ReturnType->isIntegerType())
10157 return;
10158 } else {
10159 return;
10160 }
10161 }
10162 } else { // !IsCompare
10163 // For function to bool, only suggest if the function pointer has bool
10164 // return type.
10165 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10166 return;
10167 }
10168 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010169 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010170}
10171
John McCallcc7e5bf2010-05-06 08:58:33 +000010172/// Diagnoses "dangerous" implicit conversions within the given
10173/// expression (which is a full expression). Implements -Wconversion
10174/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010175///
10176/// \param CC the "context" location of the implicit conversion, i.e.
10177/// the most location of the syntactic entity requiring the implicit
10178/// conversion
10179void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010180 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010181 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010182 return;
10183
10184 // Don't diagnose for value- or type-dependent expressions.
10185 if (E->isTypeDependent() || E->isValueDependent())
10186 return;
10187
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010188 // Check for array bounds violations in cases where the check isn't triggered
10189 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10190 // ArraySubscriptExpr is on the RHS of a variable initialization.
10191 CheckArrayAccess(E);
10192
John McCallacf0ee52010-10-08 02:01:28 +000010193 // This is not the right CC for (e.g.) a variable initialization.
10194 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010195}
10196
Richard Trieu65724892014-11-15 06:37:39 +000010197/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10198/// Input argument E is a logical expression.
10199void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10200 ::CheckBoolLikeConversion(*this, E, CC);
10201}
10202
Richard Smith9f7df0c2017-06-26 23:19:32 +000010203/// Diagnose when expression is an integer constant expression and its evaluation
10204/// results in integer overflow
10205void Sema::CheckForIntOverflow (Expr *E) {
10206 // Use a work list to deal with nested struct initializers.
10207 SmallVector<Expr *, 2> Exprs(1, E);
10208
10209 do {
10210 Expr *E = Exprs.pop_back_val();
10211
10212 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10213 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10214 continue;
10215 }
10216
10217 if (auto InitList = dyn_cast<InitListExpr>(E))
10218 Exprs.append(InitList->inits().begin(), InitList->inits().end());
10219
10220 if (isa<ObjCBoxedExpr>(E))
10221 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10222 } while (!Exprs.empty());
10223}
10224
Richard Smithc406cb72013-01-17 01:17:56 +000010225namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010226
Richard Smithc406cb72013-01-17 01:17:56 +000010227/// \brief Visitor for expressions which looks for unsequenced operations on the
10228/// same object.
10229class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010230 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010231
Richard Smithc406cb72013-01-17 01:17:56 +000010232 /// \brief A tree of sequenced regions within an expression. Two regions are
10233 /// unsequenced if one is an ancestor or a descendent of the other. When we
10234 /// finish processing an expression with sequencing, such as a comma
10235 /// expression, we fold its tree nodes into its parent, since they are
10236 /// unsequenced with respect to nodes we will visit later.
10237 class SequenceTree {
10238 struct Value {
10239 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10240 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010241 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010242 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010243 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010244
10245 public:
10246 /// \brief A region within an expression which may be sequenced with respect
10247 /// to some other region.
10248 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010249 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010250
10251 unsigned Index = 0;
10252
10253 explicit Seq(unsigned N) : Index(N) {}
10254
Richard Smithc406cb72013-01-17 01:17:56 +000010255 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010256 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010257 };
10258
10259 SequenceTree() { Values.push_back(Value(0)); }
10260 Seq root() const { return Seq(0); }
10261
10262 /// \brief Create a new sequence of operations, which is an unsequenced
10263 /// subset of \p Parent. This sequence of operations is sequenced with
10264 /// respect to other children of \p Parent.
10265 Seq allocate(Seq Parent) {
10266 Values.push_back(Value(Parent.Index));
10267 return Seq(Values.size() - 1);
10268 }
10269
10270 /// \brief Merge a sequence of operations into its parent.
10271 void merge(Seq S) {
10272 Values[S.Index].Merged = true;
10273 }
10274
10275 /// \brief Determine whether two operations are unsequenced. This operation
10276 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10277 /// should have been merged into its parent as appropriate.
10278 bool isUnsequenced(Seq Cur, Seq Old) {
10279 unsigned C = representative(Cur.Index);
10280 unsigned Target = representative(Old.Index);
10281 while (C >= Target) {
10282 if (C == Target)
10283 return true;
10284 C = Values[C].Parent;
10285 }
10286 return false;
10287 }
10288
10289 private:
10290 /// \brief Pick a representative for a sequence.
10291 unsigned representative(unsigned K) {
10292 if (Values[K].Merged)
10293 // Perform path compression as we go.
10294 return Values[K].Parent = representative(Values[K].Parent);
10295 return K;
10296 }
10297 };
10298
10299 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010300 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010301
10302 /// Different flavors of object usage which we track. We only track the
10303 /// least-sequenced usage of each kind.
10304 enum UsageKind {
10305 /// A read of an object. Multiple unsequenced reads are OK.
10306 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010307
Richard Smithc406cb72013-01-17 01:17:56 +000010308 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010309 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010310 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010311
Richard Smithc406cb72013-01-17 01:17:56 +000010312 /// A modification of an object which is not sequenced before the value
10313 /// computation of the expression, such as n++.
10314 UK_ModAsSideEffect,
10315
10316 UK_Count = UK_ModAsSideEffect + 1
10317 };
10318
10319 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010320 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010321 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010322
10323 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010324 };
10325
10326 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010327 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010328
Richard Smithc406cb72013-01-17 01:17:56 +000010329 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010330 bool Diagnosed = false;
10331
10332 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010333 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010334 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010335
10336 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010337
Richard Smithc406cb72013-01-17 01:17:56 +000010338 /// Sequenced regions within the expression.
10339 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010340
Richard Smithc406cb72013-01-17 01:17:56 +000010341 /// Declaration modifications and references which we have seen.
10342 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010343
Richard Smithc406cb72013-01-17 01:17:56 +000010344 /// The region we are currently within.
10345 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010346
Richard Smithc406cb72013-01-17 01:17:56 +000010347 /// Filled in with declarations which were modified as a side-effect
10348 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010349 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10350
Richard Smithd33f5202013-01-17 23:18:09 +000010351 /// Expressions to check later. We defer checking these to reduce
10352 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010353 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010354
10355 /// RAII object wrapping the visitation of a sequenced subexpression of an
10356 /// expression. At the end of this process, the side-effects of the evaluation
10357 /// become sequenced with respect to the value computation of the result, so
10358 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10359 /// UK_ModAsValue.
10360 struct SequencedSubexpression {
10361 SequencedSubexpression(SequenceChecker &Self)
10362 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10363 Self.ModAsSideEffect = &ModAsSideEffect;
10364 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010365
Richard Smithc406cb72013-01-17 01:17:56 +000010366 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010367 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10368 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010369 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010370 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10371 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010372 }
10373 Self.ModAsSideEffect = OldModAsSideEffect;
10374 }
10375
10376 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010377 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010378 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010379 };
10380
Richard Smith40238f02013-06-20 22:21:56 +000010381 /// RAII object wrapping the visitation of a subexpression which we might
10382 /// choose to evaluate as a constant. If any subexpression is evaluated and
10383 /// found to be non-constant, this allows us to suppress the evaluation of
10384 /// the outer expression.
10385 class EvaluationTracker {
10386 public:
10387 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010388 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010389 Self.EvalTracker = this;
10390 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010391
Richard Smith40238f02013-06-20 22:21:56 +000010392 ~EvaluationTracker() {
10393 Self.EvalTracker = Prev;
10394 if (Prev)
10395 Prev->EvalOK &= EvalOK;
10396 }
10397
10398 bool evaluate(const Expr *E, bool &Result) {
10399 if (!EvalOK || E->isValueDependent())
10400 return false;
10401 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10402 return EvalOK;
10403 }
10404
10405 private:
10406 SequenceChecker &Self;
10407 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010408 bool EvalOK = true;
10409 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010410
Richard Smithc406cb72013-01-17 01:17:56 +000010411 /// \brief Find the object which is produced by the specified expression,
10412 /// if any.
10413 Object getObject(Expr *E, bool Mod) const {
10414 E = E->IgnoreParenCasts();
10415 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10416 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10417 return getObject(UO->getSubExpr(), Mod);
10418 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10419 if (BO->getOpcode() == BO_Comma)
10420 return getObject(BO->getRHS(), Mod);
10421 if (Mod && BO->isAssignmentOp())
10422 return getObject(BO->getLHS(), Mod);
10423 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10424 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10425 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10426 return ME->getMemberDecl();
10427 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10428 // FIXME: If this is a reference, map through to its value.
10429 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010430 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010431 }
10432
10433 /// \brief Note that an object was modified or used by an expression.
10434 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10435 Usage &U = UI.Uses[UK];
10436 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10437 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10438 ModAsSideEffect->push_back(std::make_pair(O, U));
10439 U.Use = Ref;
10440 U.Seq = Region;
10441 }
10442 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010443
Richard Smithc406cb72013-01-17 01:17:56 +000010444 /// \brief Check whether a modification or use conflicts with a prior usage.
10445 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10446 bool IsModMod) {
10447 if (UI.Diagnosed)
10448 return;
10449
10450 const Usage &U = UI.Uses[OtherKind];
10451 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10452 return;
10453
10454 Expr *Mod = U.Use;
10455 Expr *ModOrUse = Ref;
10456 if (OtherKind == UK_Use)
10457 std::swap(Mod, ModOrUse);
10458
10459 SemaRef.Diag(Mod->getExprLoc(),
10460 IsModMod ? diag::warn_unsequenced_mod_mod
10461 : diag::warn_unsequenced_mod_use)
10462 << O << SourceRange(ModOrUse->getExprLoc());
10463 UI.Diagnosed = true;
10464 }
10465
10466 void notePreUse(Object O, Expr *Use) {
10467 UsageInfo &U = UsageMap[O];
10468 // Uses conflict with other modifications.
10469 checkUsage(O, U, Use, UK_ModAsValue, false);
10470 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010471
Richard Smithc406cb72013-01-17 01:17:56 +000010472 void notePostUse(Object O, Expr *Use) {
10473 UsageInfo &U = UsageMap[O];
10474 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10475 addUsage(U, O, Use, UK_Use);
10476 }
10477
10478 void notePreMod(Object O, Expr *Mod) {
10479 UsageInfo &U = UsageMap[O];
10480 // Modifications conflict with other modifications and with uses.
10481 checkUsage(O, U, Mod, UK_ModAsValue, true);
10482 checkUsage(O, U, Mod, UK_Use, false);
10483 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010484
Richard Smithc406cb72013-01-17 01:17:56 +000010485 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10486 UsageInfo &U = UsageMap[O];
10487 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10488 addUsage(U, O, Use, UK);
10489 }
10490
10491public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010492 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010493 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010494 Visit(E);
10495 }
10496
10497 void VisitStmt(Stmt *S) {
10498 // Skip all statements which aren't expressions for now.
10499 }
10500
10501 void VisitExpr(Expr *E) {
10502 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010503 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010504 }
10505
10506 void VisitCastExpr(CastExpr *E) {
10507 Object O = Object();
10508 if (E->getCastKind() == CK_LValueToRValue)
10509 O = getObject(E->getSubExpr(), false);
10510
10511 if (O)
10512 notePreUse(O, E);
10513 VisitExpr(E);
10514 if (O)
10515 notePostUse(O, E);
10516 }
10517
10518 void VisitBinComma(BinaryOperator *BO) {
10519 // C++11 [expr.comma]p1:
10520 // Every value computation and side effect associated with the left
10521 // expression is sequenced before every value computation and side
10522 // effect associated with the right expression.
10523 SequenceTree::Seq LHS = Tree.allocate(Region);
10524 SequenceTree::Seq RHS = Tree.allocate(Region);
10525 SequenceTree::Seq OldRegion = Region;
10526
10527 {
10528 SequencedSubexpression SeqLHS(*this);
10529 Region = LHS;
10530 Visit(BO->getLHS());
10531 }
10532
10533 Region = RHS;
10534 Visit(BO->getRHS());
10535
10536 Region = OldRegion;
10537
10538 // Forget that LHS and RHS are sequenced. They are both unsequenced
10539 // with respect to other stuff.
10540 Tree.merge(LHS);
10541 Tree.merge(RHS);
10542 }
10543
10544 void VisitBinAssign(BinaryOperator *BO) {
10545 // The modification is sequenced after the value computation of the LHS
10546 // and RHS, so check it before inspecting the operands and update the
10547 // map afterwards.
10548 Object O = getObject(BO->getLHS(), true);
10549 if (!O)
10550 return VisitExpr(BO);
10551
10552 notePreMod(O, BO);
10553
10554 // C++11 [expr.ass]p7:
10555 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10556 // only once.
10557 //
10558 // Therefore, for a compound assignment operator, O is considered used
10559 // everywhere except within the evaluation of E1 itself.
10560 if (isa<CompoundAssignOperator>(BO))
10561 notePreUse(O, BO);
10562
10563 Visit(BO->getLHS());
10564
10565 if (isa<CompoundAssignOperator>(BO))
10566 notePostUse(O, BO);
10567
10568 Visit(BO->getRHS());
10569
Richard Smith83e37bee2013-06-26 23:16:51 +000010570 // C++11 [expr.ass]p1:
10571 // the assignment is sequenced [...] before the value computation of the
10572 // assignment expression.
10573 // C11 6.5.16/3 has no such rule.
10574 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10575 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010576 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010577
Richard Smithc406cb72013-01-17 01:17:56 +000010578 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10579 VisitBinAssign(CAO);
10580 }
10581
10582 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10583 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10584 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10585 Object O = getObject(UO->getSubExpr(), true);
10586 if (!O)
10587 return VisitExpr(UO);
10588
10589 notePreMod(O, UO);
10590 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010591 // C++11 [expr.pre.incr]p1:
10592 // the expression ++x is equivalent to x+=1
10593 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10594 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010595 }
10596
10597 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10598 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10599 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10600 Object O = getObject(UO->getSubExpr(), true);
10601 if (!O)
10602 return VisitExpr(UO);
10603
10604 notePreMod(O, UO);
10605 Visit(UO->getSubExpr());
10606 notePostMod(O, UO, UK_ModAsSideEffect);
10607 }
10608
10609 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10610 void VisitBinLOr(BinaryOperator *BO) {
10611 // The side-effects of the LHS of an '&&' are sequenced before the
10612 // value computation of the RHS, and hence before the value computation
10613 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10614 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010615 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010616 {
10617 SequencedSubexpression Sequenced(*this);
10618 Visit(BO->getLHS());
10619 }
10620
10621 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010622 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010623 if (!Result)
10624 Visit(BO->getRHS());
10625 } else {
10626 // Check for unsequenced operations in the RHS, treating it as an
10627 // entirely separate evaluation.
10628 //
10629 // FIXME: If there are operations in the RHS which are unsequenced
10630 // with respect to operations outside the RHS, and those operations
10631 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010632 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010633 }
Richard Smithc406cb72013-01-17 01:17:56 +000010634 }
10635 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010636 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010637 {
10638 SequencedSubexpression Sequenced(*this);
10639 Visit(BO->getLHS());
10640 }
10641
10642 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010643 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010644 if (Result)
10645 Visit(BO->getRHS());
10646 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010647 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010648 }
Richard Smithc406cb72013-01-17 01:17:56 +000010649 }
10650
10651 // Only visit the condition, unless we can be sure which subexpression will
10652 // be chosen.
10653 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010654 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010655 {
10656 SequencedSubexpression Sequenced(*this);
10657 Visit(CO->getCond());
10658 }
Richard Smithc406cb72013-01-17 01:17:56 +000010659
10660 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010661 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010662 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010663 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010664 WorkList.push_back(CO->getTrueExpr());
10665 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010666 }
Richard Smithc406cb72013-01-17 01:17:56 +000010667 }
10668
Richard Smithe3dbfe02013-06-30 10:40:20 +000010669 void VisitCallExpr(CallExpr *CE) {
10670 // C++11 [intro.execution]p15:
10671 // When calling a function [...], every value computation and side effect
10672 // associated with any argument expression, or with the postfix expression
10673 // designating the called function, is sequenced before execution of every
10674 // expression or statement in the body of the function [and thus before
10675 // the value computation of its result].
10676 SequencedSubexpression Sequenced(*this);
10677 Base::VisitCallExpr(CE);
10678
10679 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10680 }
10681
Richard Smithc406cb72013-01-17 01:17:56 +000010682 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010683 // This is a call, so all subexpressions are sequenced before the result.
10684 SequencedSubexpression Sequenced(*this);
10685
Richard Smithc406cb72013-01-17 01:17:56 +000010686 if (!CCE->isListInitialization())
10687 return VisitExpr(CCE);
10688
10689 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010690 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010691 SequenceTree::Seq Parent = Region;
10692 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10693 E = CCE->arg_end();
10694 I != E; ++I) {
10695 Region = Tree.allocate(Parent);
10696 Elts.push_back(Region);
10697 Visit(*I);
10698 }
10699
10700 // Forget that the initializers are sequenced.
10701 Region = Parent;
10702 for (unsigned I = 0; I < Elts.size(); ++I)
10703 Tree.merge(Elts[I]);
10704 }
10705
10706 void VisitInitListExpr(InitListExpr *ILE) {
10707 if (!SemaRef.getLangOpts().CPlusPlus11)
10708 return VisitExpr(ILE);
10709
10710 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010711 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010712 SequenceTree::Seq Parent = Region;
10713 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10714 Expr *E = ILE->getInit(I);
10715 if (!E) continue;
10716 Region = Tree.allocate(Parent);
10717 Elts.push_back(Region);
10718 Visit(E);
10719 }
10720
10721 // Forget that the initializers are sequenced.
10722 Region = Parent;
10723 for (unsigned I = 0; I < Elts.size(); ++I)
10724 Tree.merge(Elts[I]);
10725 }
10726};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010727
10728} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010729
10730void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010731 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010732 WorkList.push_back(E);
10733 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010734 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010735 SequenceChecker(*this, Item, WorkList);
10736 }
Richard Smithc406cb72013-01-17 01:17:56 +000010737}
10738
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010739void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10740 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010741 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010742 if (!E->isInstantiationDependent())
10743 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010744 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010745 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010746 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010747}
10748
John McCall1f425642010-11-11 03:21:53 +000010749void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10750 FieldDecl *BitField,
10751 Expr *Init) {
10752 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10753}
10754
David Majnemer61a5bbf2015-04-07 22:08:51 +000010755static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10756 SourceLocation Loc) {
10757 if (!PType->isVariablyModifiedType())
10758 return;
10759 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10760 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10761 return;
10762 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010763 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10764 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10765 return;
10766 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010767 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10768 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10769 return;
10770 }
10771
10772 const ArrayType *AT = S.Context.getAsArrayType(PType);
10773 if (!AT)
10774 return;
10775
10776 if (AT->getSizeModifier() != ArrayType::Star) {
10777 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10778 return;
10779 }
10780
10781 S.Diag(Loc, diag::err_array_star_in_function_definition);
10782}
10783
Mike Stump0c2ec772010-01-21 03:59:47 +000010784/// CheckParmsForFunctionDef - Check that the parameters of the given
10785/// function are appropriate for the definition of a function. This
10786/// takes care of any checks that cannot be performed on the
10787/// declaration itself, e.g., that the types of each of the function
10788/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010789bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010790 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010791 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010792 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010793 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10794 // function declarator that is part of a function definition of
10795 // that function shall not have incomplete type.
10796 //
10797 // This is also C++ [dcl.fct]p6.
10798 if (!Param->isInvalidDecl() &&
10799 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010800 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010801 Param->setInvalidDecl();
10802 HasInvalidParm = true;
10803 }
10804
10805 // C99 6.9.1p5: If the declarator includes a parameter type list, the
10806 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000010807 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000010808 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000010809 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000010810 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000010811 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000010812
10813 // C99 6.7.5.3p12:
10814 // If the function declarator is not part of a definition of that
10815 // function, parameters may have incomplete type and may use the [*]
10816 // notation in their sequences of declarator specifiers to specify
10817 // variable length array types.
10818 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000010819 // FIXME: This diagnostic should point the '[*]' if source-location
10820 // information is added for it.
10821 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010822
10823 // MSVC destroys objects passed by value in the callee. Therefore a
10824 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010825 // object's destructor. However, we don't perform any direct access check
10826 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +000010827 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10828 .getCXXABI()
10829 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +000010830 if (!Param->isInvalidDecl()) {
10831 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10832 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10833 if (!ClassDecl->isInvalidDecl() &&
10834 !ClassDecl->hasIrrelevantDestructor() &&
10835 !ClassDecl->isDependentContext()) {
10836 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10837 MarkFunctionReferenced(Param->getLocation(), Destructor);
10838 DiagnoseUseOfDecl(Destructor, Param->getLocation());
10839 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000010840 }
10841 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000010842 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010843
10844 // Parameters with the pass_object_size attribute only need to be marked
10845 // constant at function definitions. Because we lack information about
10846 // whether we're on a declaration or definition when we're instantiating the
10847 // attribute, we need to check for constness here.
10848 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10849 if (!Param->getType().isConstQualified())
10850 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10851 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000010852 }
10853
10854 return HasInvalidParm;
10855}
John McCall2b5c1b22010-08-12 21:44:57 +000010856
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010857/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10858/// or MemberExpr.
10859static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10860 ASTContext &Context) {
10861 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10862 return Context.getDeclAlign(DRE->getDecl());
10863
10864 if (const auto *ME = dyn_cast<MemberExpr>(E))
10865 return Context.getDeclAlign(ME->getMemberDecl());
10866
10867 return TypeAlign;
10868}
10869
John McCall2b5c1b22010-08-12 21:44:57 +000010870/// CheckCastAlign - Implements -Wcast-align, which warns when a
10871/// pointer cast increases the alignment requirements.
10872void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10873 // This is actually a lot of work to potentially be doing on every
10874 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010875 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000010876 return;
10877
10878 // Ignore dependent types.
10879 if (T->isDependentType() || Op->getType()->isDependentType())
10880 return;
10881
10882 // Require that the destination be a pointer type.
10883 const PointerType *DestPtr = T->getAs<PointerType>();
10884 if (!DestPtr) return;
10885
10886 // If the destination has alignment 1, we're done.
10887 QualType DestPointee = DestPtr->getPointeeType();
10888 if (DestPointee->isIncompleteType()) return;
10889 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10890 if (DestAlign.isOne()) return;
10891
10892 // Require that the source be a pointer type.
10893 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10894 if (!SrcPtr) return;
10895 QualType SrcPointee = SrcPtr->getPointeeType();
10896
10897 // Whitelist casts from cv void*. We already implicitly
10898 // whitelisted casts to cv void*, since they have alignment 1.
10899 // Also whitelist casts involving incomplete types, which implicitly
10900 // includes 'void'.
10901 if (SrcPointee->isIncompleteType()) return;
10902
10903 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000010904
10905 if (auto *CE = dyn_cast<CastExpr>(Op)) {
10906 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10907 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10908 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10909 if (UO->getOpcode() == UO_AddrOf)
10910 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10911 }
10912
John McCall2b5c1b22010-08-12 21:44:57 +000010913 if (SrcAlign >= DestAlign) return;
10914
10915 Diag(TRange.getBegin(), diag::warn_cast_align)
10916 << Op->getType() << T
10917 << static_cast<unsigned>(SrcAlign.getQuantity())
10918 << static_cast<unsigned>(DestAlign.getQuantity())
10919 << TRange << Op->getSourceRange();
10920}
10921
Chandler Carruth28389f02011-08-05 09:10:50 +000010922/// \brief Check whether this array fits the idiom of a size-one tail padded
10923/// array member of a struct.
10924///
10925/// We avoid emitting out-of-bounds access warnings for such arrays as they are
10926/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000010927static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000010928 const NamedDecl *ND) {
10929 if (Size != 1 || !ND) return false;
10930
10931 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10932 if (!FD) return false;
10933
10934 // Don't consider sizes resulting from macro expansions or template argument
10935 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000010936
10937 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010938 while (TInfo) {
10939 TypeLoc TL = TInfo->getTypeLoc();
10940 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000010941 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10942 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010943 TInfo = TDL->getTypeSourceInfo();
10944 continue;
10945 }
David Blaikie6adc78e2013-02-18 22:06:02 +000010946 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10947 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000010948 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10949 return false;
10950 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000010951 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000010952 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010953
10954 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000010955 if (!RD) return false;
10956 if (RD->isUnion()) return false;
10957 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10958 if (!CRD->isStandardLayout()) return false;
10959 }
Chandler Carruth28389f02011-08-05 09:10:50 +000010960
Benjamin Kramer8c543672011-08-06 03:04:42 +000010961 // See if this is the last field decl in the record.
10962 const Decl *D = FD;
10963 while ((D = D->getNextDeclInContext()))
10964 if (isa<FieldDecl>(D))
10965 return false;
10966 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000010967}
10968
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010969void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010970 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000010971 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000010972 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000010973 if (IndexExpr->isValueDependent())
10974 return;
10975
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010976 const Type *EffectiveType =
10977 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010978 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010979 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010980 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010981 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000010982 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000010983
Chandler Carruth2a666fc2011-02-17 20:55:08 +000010984 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000010985 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000010986 return;
Richard Smith13f67182011-12-16 19:31:14 +000010987 if (IndexNegated)
10988 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000010989
Craig Topperc3ec1492014-05-26 06:22:03 +000010990 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000010991 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10992 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +000010993 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +000010994 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +000010995
Ted Kremeneke4b316c2011-02-23 23:06:04 +000010996 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000010997 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000010998 if (!size.isStrictlyPositive())
10999 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011000
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011001 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011002 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011003 // Make sure we're comparing apples to apples when comparing index to size
11004 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11005 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011006 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011007 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011008 if (ptrarith_typesize != array_typesize) {
11009 // There's a cast to a different size type involved
11010 uint64_t ratio = array_typesize / ptrarith_typesize;
11011 // TODO: Be smarter about handling cases where array_typesize is not a
11012 // multiple of ptrarith_typesize
11013 if (ptrarith_typesize * ratio == array_typesize)
11014 size *= llvm::APInt(size.getBitWidth(), ratio);
11015 }
11016 }
11017
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011018 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011019 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011020 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011021 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011022
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011023 // For array subscripting the index must be less than size, but for pointer
11024 // arithmetic also allow the index (offset) to be equal to size since
11025 // computing the next address after the end of the array is legal and
11026 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011027 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011028 return;
11029
11030 // Also don't warn for arrays of size 1 which are members of some
11031 // structure. These are often used to approximate flexible arrays in C89
11032 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011033 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011034 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011035
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011036 // Suppress the warning if the subscript expression (as identified by the
11037 // ']' location) and the index expression are both from macro expansions
11038 // within a system header.
11039 if (ASE) {
11040 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11041 ASE->getRBracketLoc());
11042 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11043 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11044 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011045 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011046 return;
11047 }
11048 }
11049
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011050 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011051 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011052 DiagID = diag::warn_array_index_exceeds_bounds;
11053
11054 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11055 PDiag(DiagID) << index.toString(10, true)
11056 << size.toString(10, true)
11057 << (unsigned)size.getLimitedValue(~0U)
11058 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011059 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011060 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011061 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011062 DiagID = diag::warn_ptr_arith_precedes_bounds;
11063 if (index.isNegative()) index = -index;
11064 }
11065
11066 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11067 PDiag(DiagID) << index.toString(10, true)
11068 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011069 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011070
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011071 if (!ND) {
11072 // Try harder to find a NamedDecl to point at in the note.
11073 while (const ArraySubscriptExpr *ASE =
11074 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11075 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11076 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11077 ND = dyn_cast<NamedDecl>(DRE->getDecl());
11078 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11079 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11080 }
11081
Chandler Carruth1af88f12011-02-17 21:10:52 +000011082 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011083 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11084 PDiag(diag::note_array_index_out_of_bounds)
11085 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011086}
11087
Ted Kremenekdf26df72011-03-01 18:41:00 +000011088void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011089 int AllowOnePastEnd = 0;
11090 while (expr) {
11091 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011092 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011093 case Stmt::ArraySubscriptExprClass: {
11094 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011095 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011096 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +000011097 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011098 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011099 case Stmt::OMPArraySectionExprClass: {
11100 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11101 if (ASE->getLowerBound())
11102 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11103 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11104 return;
11105 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011106 case Stmt::UnaryOperatorClass: {
11107 // Only unwrap the * and & unary operators
11108 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11109 expr = UO->getSubExpr();
11110 switch (UO->getOpcode()) {
11111 case UO_AddrOf:
11112 AllowOnePastEnd++;
11113 break;
11114 case UO_Deref:
11115 AllowOnePastEnd--;
11116 break;
11117 default:
11118 return;
11119 }
11120 break;
11121 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011122 case Stmt::ConditionalOperatorClass: {
11123 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11124 if (const Expr *lhs = cond->getLHS())
11125 CheckArrayAccess(lhs);
11126 if (const Expr *rhs = cond->getRHS())
11127 CheckArrayAccess(rhs);
11128 return;
11129 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011130 case Stmt::CXXOperatorCallExprClass: {
11131 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11132 for (const auto *Arg : OCE->arguments())
11133 CheckArrayAccess(Arg);
11134 return;
11135 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011136 default:
11137 return;
11138 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011139 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011140}
John McCall31168b02011-06-15 23:02:42 +000011141
11142//===--- CHECK: Objective-C retain cycles ----------------------------------//
11143
11144namespace {
John McCall31168b02011-06-15 23:02:42 +000011145
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011146struct RetainCycleOwner {
11147 VarDecl *Variable = nullptr;
11148 SourceRange Range;
11149 SourceLocation Loc;
11150 bool Indirect = false;
11151
11152 RetainCycleOwner() = default;
11153
11154 void setLocsFrom(Expr *e) {
11155 Loc = e->getExprLoc();
11156 Range = e->getSourceRange();
11157 }
11158};
11159
11160} // namespace
John McCall31168b02011-06-15 23:02:42 +000011161
11162/// Consider whether capturing the given variable can possibly lead to
11163/// a retain cycle.
11164static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011165 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011166 // lifetime. In MRR, it's captured strongly if the variable is
11167 // __block and has an appropriate type.
11168 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11169 return false;
11170
11171 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011172 if (ref)
11173 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011174 return true;
11175}
11176
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011177static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011178 while (true) {
11179 e = e->IgnoreParens();
11180 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11181 switch (cast->getCastKind()) {
11182 case CK_BitCast:
11183 case CK_LValueBitCast:
11184 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011185 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011186 e = cast->getSubExpr();
11187 continue;
11188
John McCall31168b02011-06-15 23:02:42 +000011189 default:
11190 return false;
11191 }
11192 }
11193
11194 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11195 ObjCIvarDecl *ivar = ref->getDecl();
11196 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11197 return false;
11198
11199 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011200 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011201 return false;
11202
11203 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11204 owner.Indirect = true;
11205 return true;
11206 }
11207
11208 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11209 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11210 if (!var) return false;
11211 return considerVariable(var, ref, owner);
11212 }
11213
John McCall31168b02011-06-15 23:02:42 +000011214 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11215 if (member->isArrow()) return false;
11216
11217 // Don't count this as an indirect ownership.
11218 e = member->getBase();
11219 continue;
11220 }
11221
John McCallfe96e0b2011-11-06 09:01:30 +000011222 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11223 // Only pay attention to pseudo-objects on property references.
11224 ObjCPropertyRefExpr *pre
11225 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11226 ->IgnoreParens());
11227 if (!pre) return false;
11228 if (pre->isImplicitProperty()) return false;
11229 ObjCPropertyDecl *property = pre->getExplicitProperty();
11230 if (!property->isRetaining() &&
11231 !(property->getPropertyIvarDecl() &&
11232 property->getPropertyIvarDecl()->getType()
11233 .getObjCLifetime() == Qualifiers::OCL_Strong))
11234 return false;
11235
11236 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011237 if (pre->isSuperReceiver()) {
11238 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11239 if (!owner.Variable)
11240 return false;
11241 owner.Loc = pre->getLocation();
11242 owner.Range = pre->getSourceRange();
11243 return true;
11244 }
John McCallfe96e0b2011-11-06 09:01:30 +000011245 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11246 ->getSourceExpr());
11247 continue;
11248 }
11249
John McCall31168b02011-06-15 23:02:42 +000011250 // Array ivars?
11251
11252 return false;
11253 }
11254}
11255
11256namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011257
John McCall31168b02011-06-15 23:02:42 +000011258 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011259 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011260 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011261 Expr *Capturer = nullptr;
11262 bool VarWillBeReased = false;
11263
11264 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11265 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11266 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011267
11268 void VisitDeclRefExpr(DeclRefExpr *ref) {
11269 if (ref->getDecl() == Variable && !Capturer)
11270 Capturer = ref;
11271 }
11272
John McCall31168b02011-06-15 23:02:42 +000011273 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11274 if (Capturer) return;
11275 Visit(ref->getBase());
11276 if (Capturer && ref->isFreeIvar())
11277 Capturer = ref;
11278 }
11279
11280 void VisitBlockExpr(BlockExpr *block) {
11281 // Look inside nested blocks
11282 if (block->getBlockDecl()->capturesVariable(Variable))
11283 Visit(block->getBlockDecl()->getBody());
11284 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011285
11286 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11287 if (Capturer) return;
11288 if (OVE->getSourceExpr())
11289 Visit(OVE->getSourceExpr());
11290 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011291
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011292 void VisitBinaryOperator(BinaryOperator *BinOp) {
11293 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11294 return;
11295 Expr *LHS = BinOp->getLHS();
11296 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11297 if (DRE->getDecl() != Variable)
11298 return;
11299 if (Expr *RHS = BinOp->getRHS()) {
11300 RHS = RHS->IgnoreParenCasts();
11301 llvm::APSInt Value;
11302 VarWillBeReased =
11303 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11304 }
11305 }
11306 }
John McCall31168b02011-06-15 23:02:42 +000011307 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011308
11309} // namespace
John McCall31168b02011-06-15 23:02:42 +000011310
11311/// Check whether the given argument is a block which captures a
11312/// variable.
11313static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11314 assert(owner.Variable && owner.Loc.isValid());
11315
11316 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011317
11318 // Look through [^{...} copy] and Block_copy(^{...}).
11319 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11320 Selector Cmd = ME->getSelector();
11321 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11322 e = ME->getInstanceReceiver();
11323 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011324 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011325 e = e->IgnoreParenCasts();
11326 }
11327 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11328 if (CE->getNumArgs() == 1) {
11329 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011330 if (Fn) {
11331 const IdentifierInfo *FnI = Fn->getIdentifier();
11332 if (FnI && FnI->isStr("_Block_copy")) {
11333 e = CE->getArg(0)->IgnoreParenCasts();
11334 }
11335 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011336 }
11337 }
11338
John McCall31168b02011-06-15 23:02:42 +000011339 BlockExpr *block = dyn_cast<BlockExpr>(e);
11340 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011341 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011342
11343 FindCaptureVisitor visitor(S.Context, owner.Variable);
11344 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011345 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011346}
11347
11348static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11349 RetainCycleOwner &owner) {
11350 assert(capturer);
11351 assert(owner.Variable && owner.Loc.isValid());
11352
11353 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11354 << owner.Variable << capturer->getSourceRange();
11355 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11356 << owner.Indirect << owner.Range;
11357}
11358
11359/// Check for a keyword selector that starts with the word 'add' or
11360/// 'set'.
11361static bool isSetterLikeSelector(Selector sel) {
11362 if (sel.isUnarySelector()) return false;
11363
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011364 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011365 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011366 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011367 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011368 else if (str.startswith("add")) {
11369 // Specially whitelist 'addOperationWithBlock:'.
11370 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11371 return false;
11372 str = str.substr(3);
11373 }
John McCall31168b02011-06-15 23:02:42 +000011374 else
11375 return false;
11376
11377 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011378 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011379}
11380
Benjamin Kramer3a743452015-03-09 15:03:32 +000011381static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11382 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011383 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11384 Message->getReceiverInterface(),
11385 NSAPI::ClassId_NSMutableArray);
11386 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011387 return None;
11388 }
11389
11390 Selector Sel = Message->getSelector();
11391
11392 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11393 S.NSAPIObj->getNSArrayMethodKind(Sel);
11394 if (!MKOpt) {
11395 return None;
11396 }
11397
11398 NSAPI::NSArrayMethodKind MK = *MKOpt;
11399
11400 switch (MK) {
11401 case NSAPI::NSMutableArr_addObject:
11402 case NSAPI::NSMutableArr_insertObjectAtIndex:
11403 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11404 return 0;
11405 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11406 return 1;
11407
11408 default:
11409 return None;
11410 }
11411
11412 return None;
11413}
11414
11415static
11416Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11417 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011418 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11419 Message->getReceiverInterface(),
11420 NSAPI::ClassId_NSMutableDictionary);
11421 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011422 return None;
11423 }
11424
11425 Selector Sel = Message->getSelector();
11426
11427 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11428 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11429 if (!MKOpt) {
11430 return None;
11431 }
11432
11433 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11434
11435 switch (MK) {
11436 case NSAPI::NSMutableDict_setObjectForKey:
11437 case NSAPI::NSMutableDict_setValueForKey:
11438 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11439 return 0;
11440
11441 default:
11442 return None;
11443 }
11444
11445 return None;
11446}
11447
11448static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011449 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11450 Message->getReceiverInterface(),
11451 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011452
Alex Denisov5dfac812015-08-06 04:51:14 +000011453 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11454 Message->getReceiverInterface(),
11455 NSAPI::ClassId_NSMutableOrderedSet);
11456 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011457 return None;
11458 }
11459
11460 Selector Sel = Message->getSelector();
11461
11462 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11463 if (!MKOpt) {
11464 return None;
11465 }
11466
11467 NSAPI::NSSetMethodKind MK = *MKOpt;
11468
11469 switch (MK) {
11470 case NSAPI::NSMutableSet_addObject:
11471 case NSAPI::NSOrderedSet_setObjectAtIndex:
11472 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11473 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11474 return 0;
11475 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11476 return 1;
11477 }
11478
11479 return None;
11480}
11481
11482void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11483 if (!Message->isInstanceMessage()) {
11484 return;
11485 }
11486
11487 Optional<int> ArgOpt;
11488
11489 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11490 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11491 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11492 return;
11493 }
11494
11495 int ArgIndex = *ArgOpt;
11496
Alex Denisove1d882c2015-03-04 17:55:52 +000011497 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11498 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11499 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11500 }
11501
Alex Denisov5dfac812015-08-06 04:51:14 +000011502 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011503 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011504 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011505 Diag(Message->getSourceRange().getBegin(),
11506 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +000011507 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +000011508 }
11509 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011510 } else {
11511 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11512
11513 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11514 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11515 }
11516
11517 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11518 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11519 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11520 ValueDecl *Decl = ReceiverRE->getDecl();
11521 Diag(Message->getSourceRange().getBegin(),
11522 diag::warn_objc_circular_container)
11523 << Decl->getName() << Decl->getName();
11524 if (!ArgRE->isObjCSelfExpr()) {
11525 Diag(Decl->getLocation(),
11526 diag::note_objc_circular_container_declared_here)
11527 << Decl->getName();
11528 }
11529 }
11530 }
11531 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11532 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11533 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11534 ObjCIvarDecl *Decl = IvarRE->getDecl();
11535 Diag(Message->getSourceRange().getBegin(),
11536 diag::warn_objc_circular_container)
11537 << Decl->getName() << Decl->getName();
11538 Diag(Decl->getLocation(),
11539 diag::note_objc_circular_container_declared_here)
11540 << Decl->getName();
11541 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011542 }
11543 }
11544 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011545}
11546
John McCall31168b02011-06-15 23:02:42 +000011547/// Check a message send to see if it's likely to cause a retain cycle.
11548void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11549 // Only check instance methods whose selector looks like a setter.
11550 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11551 return;
11552
11553 // Try to find a variable that the receiver is strongly owned by.
11554 RetainCycleOwner owner;
11555 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011556 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011557 return;
11558 } else {
11559 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11560 owner.Variable = getCurMethodDecl()->getSelfDecl();
11561 owner.Loc = msg->getSuperLoc();
11562 owner.Range = msg->getSuperLoc();
11563 }
11564
11565 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011566 const ObjCMethodDecl *MD = msg->getMethodDecl();
11567 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11568 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11569 // noescape blocks should not be retained by the method.
11570 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11571 continue;
John McCall31168b02011-06-15 23:02:42 +000011572 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011573 }
11574 }
John McCall31168b02011-06-15 23:02:42 +000011575}
11576
11577/// Check a property assign to see if it's likely to cause a retain cycle.
11578void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11579 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011580 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011581 return;
11582
11583 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11584 diagnoseRetainCycle(*this, capturer, owner);
11585}
11586
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011587void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11588 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011589 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011590 return;
11591
11592 // Because we don't have an expression for the variable, we have to set the
11593 // location explicitly here.
11594 Owner.Loc = Var->getLocation();
11595 Owner.Range = Var->getSourceRange();
11596
11597 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11598 diagnoseRetainCycle(*this, Capturer, Owner);
11599}
11600
Ted Kremenek9304da92012-12-21 08:04:28 +000011601static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11602 Expr *RHS, bool isProperty) {
11603 // Check if RHS is an Objective-C object literal, which also can get
11604 // immediately zapped in a weak reference. Note that we explicitly
11605 // allow ObjCStringLiterals, since those are designed to never really die.
11606 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011607
Ted Kremenek64873352012-12-21 22:46:35 +000011608 // This enum needs to match with the 'select' in
11609 // warn_objc_arc_literal_assign (off-by-1).
11610 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11611 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11612 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011613
11614 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011615 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011616 << (isProperty ? 0 : 1)
11617 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011618
11619 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011620}
11621
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011622static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11623 Qualifiers::ObjCLifetime LT,
11624 Expr *RHS, bool isProperty) {
11625 // Strip off any implicit cast added to get to the one ARC-specific.
11626 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11627 if (cast->getCastKind() == CK_ARCConsumeObject) {
11628 S.Diag(Loc, diag::warn_arc_retained_assign)
11629 << (LT == Qualifiers::OCL_ExplicitNone)
11630 << (isProperty ? 0 : 1)
11631 << RHS->getSourceRange();
11632 return true;
11633 }
11634 RHS = cast->getSubExpr();
11635 }
11636
11637 if (LT == Qualifiers::OCL_Weak &&
11638 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11639 return true;
11640
11641 return false;
11642}
11643
Ted Kremenekb36234d2012-12-21 08:04:20 +000011644bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11645 QualType LHS, Expr *RHS) {
11646 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11647
11648 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11649 return false;
11650
11651 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11652 return true;
11653
11654 return false;
11655}
11656
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011657void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11658 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011659 QualType LHSType;
11660 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011661 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011662 ObjCPropertyRefExpr *PRE
11663 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11664 if (PRE && !PRE->isImplicitProperty()) {
11665 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11666 if (PD)
11667 LHSType = PD->getType();
11668 }
11669
11670 if (LHSType.isNull())
11671 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011672
11673 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11674
11675 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011676 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011677 getCurFunction()->markSafeWeakUse(LHS);
11678 }
11679
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011680 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11681 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011682
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011683 // FIXME. Check for other life times.
11684 if (LT != Qualifiers::OCL_None)
11685 return;
11686
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011687 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011688 if (PRE->isImplicitProperty())
11689 return;
11690 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11691 if (!PD)
11692 return;
11693
Bill Wendling44426052012-12-20 19:22:21 +000011694 unsigned Attributes = PD->getPropertyAttributes();
11695 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011696 // when 'assign' attribute was not explicitly specified
11697 // by user, ignore it and rely on property type itself
11698 // for lifetime info.
11699 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11700 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11701 LHSType->isObjCRetainableType())
11702 return;
11703
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011704 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011705 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011706 Diag(Loc, diag::warn_arc_retained_property_assign)
11707 << RHS->getSourceRange();
11708 return;
11709 }
11710 RHS = cast->getSubExpr();
11711 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011712 }
Bill Wendling44426052012-12-20 19:22:21 +000011713 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011714 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11715 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011716 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011717 }
11718}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011719
11720//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11721
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011722static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11723 SourceLocation StmtLoc,
11724 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011725 // Do not warn if the body is a macro that expands to nothing, e.g:
11726 //
11727 // #define CALL(x)
11728 // if (condition)
11729 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011730 if (Body->hasLeadingEmptyMacro())
11731 return false;
11732
11733 // Get line numbers of statement and body.
11734 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011735 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011736 &StmtLineInvalid);
11737 if (StmtLineInvalid)
11738 return false;
11739
11740 bool BodyLineInvalid;
11741 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11742 &BodyLineInvalid);
11743 if (BodyLineInvalid)
11744 return false;
11745
11746 // Warn if null statement and body are on the same line.
11747 if (StmtLine != BodyLine)
11748 return false;
11749
11750 return true;
11751}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011752
11753void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11754 const Stmt *Body,
11755 unsigned DiagID) {
11756 // Since this is a syntactic check, don't emit diagnostic for template
11757 // instantiations, this just adds noise.
11758 if (CurrentInstantiationScope)
11759 return;
11760
11761 // The body should be a null statement.
11762 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11763 if (!NBody)
11764 return;
11765
11766 // Do the usual checks.
11767 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11768 return;
11769
11770 Diag(NBody->getSemiLoc(), DiagID);
11771 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11772}
11773
11774void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11775 const Stmt *PossibleBody) {
11776 assert(!CurrentInstantiationScope); // Ensured by caller
11777
11778 SourceLocation StmtLoc;
11779 const Stmt *Body;
11780 unsigned DiagID;
11781 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11782 StmtLoc = FS->getRParenLoc();
11783 Body = FS->getBody();
11784 DiagID = diag::warn_empty_for_body;
11785 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11786 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11787 Body = WS->getBody();
11788 DiagID = diag::warn_empty_while_body;
11789 } else
11790 return; // Neither `for' nor `while'.
11791
11792 // The body should be a null statement.
11793 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11794 if (!NBody)
11795 return;
11796
11797 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011798 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011799 return;
11800
11801 // Do the usual checks.
11802 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11803 return;
11804
11805 // `for(...);' and `while(...);' are popular idioms, so in order to keep
11806 // noise level low, emit diagnostics only if for/while is followed by a
11807 // CompoundStmt, e.g.:
11808 // for (int i = 0; i < n; i++);
11809 // {
11810 // a(i);
11811 // }
11812 // or if for/while is followed by a statement with more indentation
11813 // than for/while itself:
11814 // for (int i = 0; i < n; i++);
11815 // a(i);
11816 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11817 if (!ProbableTypo) {
11818 bool BodyColInvalid;
11819 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11820 PossibleBody->getLocStart(),
11821 &BodyColInvalid);
11822 if (BodyColInvalid)
11823 return;
11824
11825 bool StmtColInvalid;
11826 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11827 S->getLocStart(),
11828 &StmtColInvalid);
11829 if (StmtColInvalid)
11830 return;
11831
11832 if (BodyCol > StmtCol)
11833 ProbableTypo = true;
11834 }
11835
11836 if (ProbableTypo) {
11837 Diag(NBody->getSemiLoc(), DiagID);
11838 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11839 }
11840}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011841
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011842//===--- CHECK: Warn on self move with std::move. -------------------------===//
11843
11844/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11845void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11846 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011847 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11848 return;
11849
Richard Smith51ec0cf2017-02-21 01:17:38 +000011850 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011851 return;
11852
11853 // Strip parens and casts away.
11854 LHSExpr = LHSExpr->IgnoreParenImpCasts();
11855 RHSExpr = RHSExpr->IgnoreParenImpCasts();
11856
11857 // Check for a call expression
11858 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11859 if (!CE || CE->getNumArgs() != 1)
11860 return;
11861
11862 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000011863 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011864 return;
11865
11866 // Get argument from std::move
11867 RHSExpr = CE->getArg(0);
11868
11869 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11870 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11871
11872 // Two DeclRefExpr's, check that the decls are the same.
11873 if (LHSDeclRef && RHSDeclRef) {
11874 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11875 return;
11876 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11877 RHSDeclRef->getDecl()->getCanonicalDecl())
11878 return;
11879
11880 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11881 << LHSExpr->getSourceRange()
11882 << RHSExpr->getSourceRange();
11883 return;
11884 }
11885
11886 // Member variables require a different approach to check for self moves.
11887 // MemberExpr's are the same if every nested MemberExpr refers to the same
11888 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11889 // the base Expr's are CXXThisExpr's.
11890 const Expr *LHSBase = LHSExpr;
11891 const Expr *RHSBase = RHSExpr;
11892 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11893 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11894 if (!LHSME || !RHSME)
11895 return;
11896
11897 while (LHSME && RHSME) {
11898 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11899 RHSME->getMemberDecl()->getCanonicalDecl())
11900 return;
11901
11902 LHSBase = LHSME->getBase();
11903 RHSBase = RHSME->getBase();
11904 LHSME = dyn_cast<MemberExpr>(LHSBase);
11905 RHSME = dyn_cast<MemberExpr>(RHSBase);
11906 }
11907
11908 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11909 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11910 if (LHSDeclRef && RHSDeclRef) {
11911 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11912 return;
11913 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11914 RHSDeclRef->getDecl()->getCanonicalDecl())
11915 return;
11916
11917 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11918 << LHSExpr->getSourceRange()
11919 << RHSExpr->getSourceRange();
11920 return;
11921 }
11922
11923 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11924 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11925 << LHSExpr->getSourceRange()
11926 << RHSExpr->getSourceRange();
11927}
11928
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011929//===--- Layout compatibility ----------------------------------------------//
11930
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011931static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011932
11933/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011934static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011935 // C++11 [dcl.enum] p8:
11936 // Two enumeration types are layout-compatible if they have the same
11937 // underlying type.
11938 return ED1->isComplete() && ED2->isComplete() &&
11939 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11940}
11941
11942/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011943static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11944 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011945 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11946 return false;
11947
11948 if (Field1->isBitField() != Field2->isBitField())
11949 return false;
11950
11951 if (Field1->isBitField()) {
11952 // Make sure that the bit-fields are the same length.
11953 unsigned Bits1 = Field1->getBitWidthValue(C);
11954 unsigned Bits2 = Field2->getBitWidthValue(C);
11955
11956 if (Bits1 != Bits2)
11957 return false;
11958 }
11959
11960 return true;
11961}
11962
11963/// \brief Check if two standard-layout structs are layout-compatible.
11964/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011965static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11966 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000011967 // If both records are C++ classes, check that base classes match.
11968 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11969 // If one of records is a CXXRecordDecl we are in C++ mode,
11970 // thus the other one is a CXXRecordDecl, too.
11971 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11972 // Check number of base classes.
11973 if (D1CXX->getNumBases() != D2CXX->getNumBases())
11974 return false;
11975
11976 // Check the base classes.
11977 for (CXXRecordDecl::base_class_const_iterator
11978 Base1 = D1CXX->bases_begin(),
11979 BaseEnd1 = D1CXX->bases_end(),
11980 Base2 = D2CXX->bases_begin();
11981 Base1 != BaseEnd1;
11982 ++Base1, ++Base2) {
11983 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11984 return false;
11985 }
11986 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11987 // If only RD2 is a C++ class, it should have zero base classes.
11988 if (D2CXX->getNumBases() > 0)
11989 return false;
11990 }
11991
11992 // Check the fields.
11993 RecordDecl::field_iterator Field2 = RD2->field_begin(),
11994 Field2End = RD2->field_end(),
11995 Field1 = RD1->field_begin(),
11996 Field1End = RD1->field_end();
11997 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11998 if (!isLayoutCompatible(C, *Field1, *Field2))
11999 return false;
12000 }
12001 if (Field1 != Field1End || Field2 != Field2End)
12002 return false;
12003
12004 return true;
12005}
12006
12007/// \brief Check if two standard-layout unions are layout-compatible.
12008/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012009static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12010 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012011 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012012 for (auto *Field2 : RD2->fields())
12013 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012014
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012015 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012016 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12017 I = UnmatchedFields.begin(),
12018 E = UnmatchedFields.end();
12019
12020 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012021 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012022 bool Result = UnmatchedFields.erase(*I);
12023 (void) Result;
12024 assert(Result);
12025 break;
12026 }
12027 }
12028 if (I == E)
12029 return false;
12030 }
12031
12032 return UnmatchedFields.empty();
12033}
12034
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012035static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12036 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012037 if (RD1->isUnion() != RD2->isUnion())
12038 return false;
12039
12040 if (RD1->isUnion())
12041 return isLayoutCompatibleUnion(C, RD1, RD2);
12042 else
12043 return isLayoutCompatibleStruct(C, RD1, RD2);
12044}
12045
12046/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012047static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012048 if (T1.isNull() || T2.isNull())
12049 return false;
12050
12051 // C++11 [basic.types] p11:
12052 // If two types T1 and T2 are the same type, then T1 and T2 are
12053 // layout-compatible types.
12054 if (C.hasSameType(T1, T2))
12055 return true;
12056
12057 T1 = T1.getCanonicalType().getUnqualifiedType();
12058 T2 = T2.getCanonicalType().getUnqualifiedType();
12059
12060 const Type::TypeClass TC1 = T1->getTypeClass();
12061 const Type::TypeClass TC2 = T2->getTypeClass();
12062
12063 if (TC1 != TC2)
12064 return false;
12065
12066 if (TC1 == Type::Enum) {
12067 return isLayoutCompatible(C,
12068 cast<EnumType>(T1)->getDecl(),
12069 cast<EnumType>(T2)->getDecl());
12070 } else if (TC1 == Type::Record) {
12071 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12072 return false;
12073
12074 return isLayoutCompatible(C,
12075 cast<RecordType>(T1)->getDecl(),
12076 cast<RecordType>(T2)->getDecl());
12077 }
12078
12079 return false;
12080}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012081
12082//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12083
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012084/// \brief Given a type tag expression find the type tag itself.
12085///
12086/// \param TypeExpr Type tag expression, as it appears in user's code.
12087///
12088/// \param VD Declaration of an identifier that appears in a type tag.
12089///
12090/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012091static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12092 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012093 while(true) {
12094 if (!TypeExpr)
12095 return false;
12096
12097 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12098
12099 switch (TypeExpr->getStmtClass()) {
12100 case Stmt::UnaryOperatorClass: {
12101 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12102 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12103 TypeExpr = UO->getSubExpr();
12104 continue;
12105 }
12106 return false;
12107 }
12108
12109 case Stmt::DeclRefExprClass: {
12110 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12111 *VD = DRE->getDecl();
12112 return true;
12113 }
12114
12115 case Stmt::IntegerLiteralClass: {
12116 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12117 llvm::APInt MagicValueAPInt = IL->getValue();
12118 if (MagicValueAPInt.getActiveBits() <= 64) {
12119 *MagicValue = MagicValueAPInt.getZExtValue();
12120 return true;
12121 } else
12122 return false;
12123 }
12124
12125 case Stmt::BinaryConditionalOperatorClass:
12126 case Stmt::ConditionalOperatorClass: {
12127 const AbstractConditionalOperator *ACO =
12128 cast<AbstractConditionalOperator>(TypeExpr);
12129 bool Result;
12130 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12131 if (Result)
12132 TypeExpr = ACO->getTrueExpr();
12133 else
12134 TypeExpr = ACO->getFalseExpr();
12135 continue;
12136 }
12137 return false;
12138 }
12139
12140 case Stmt::BinaryOperatorClass: {
12141 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12142 if (BO->getOpcode() == BO_Comma) {
12143 TypeExpr = BO->getRHS();
12144 continue;
12145 }
12146 return false;
12147 }
12148
12149 default:
12150 return false;
12151 }
12152 }
12153}
12154
12155/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12156///
12157/// \param TypeExpr Expression that specifies a type tag.
12158///
12159/// \param MagicValues Registered magic values.
12160///
12161/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12162/// kind.
12163///
12164/// \param TypeInfo Information about the corresponding C type.
12165///
12166/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012167static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012168 const IdentifierInfo *ArgumentKind,
12169 const Expr *TypeExpr, const ASTContext &Ctx,
12170 const llvm::DenseMap<Sema::TypeTagMagicValue,
12171 Sema::TypeTagData> *MagicValues,
12172 bool &FoundWrongKind,
12173 Sema::TypeTagData &TypeInfo) {
12174 FoundWrongKind = false;
12175
12176 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012177 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012178
12179 uint64_t MagicValue;
12180
12181 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12182 return false;
12183
12184 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012185 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012186 if (I->getArgumentKind() != ArgumentKind) {
12187 FoundWrongKind = true;
12188 return false;
12189 }
12190 TypeInfo.Type = I->getMatchingCType();
12191 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12192 TypeInfo.MustBeNull = I->getMustBeNull();
12193 return true;
12194 }
12195 return false;
12196 }
12197
12198 if (!MagicValues)
12199 return false;
12200
12201 llvm::DenseMap<Sema::TypeTagMagicValue,
12202 Sema::TypeTagData>::const_iterator I =
12203 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12204 if (I == MagicValues->end())
12205 return false;
12206
12207 TypeInfo = I->second;
12208 return true;
12209}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012210
12211void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12212 uint64_t MagicValue, QualType Type,
12213 bool LayoutCompatible,
12214 bool MustBeNull) {
12215 if (!TypeTagForDatatypeMagicValues)
12216 TypeTagForDatatypeMagicValues.reset(
12217 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12218
12219 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12220 (*TypeTagForDatatypeMagicValues)[Magic] =
12221 TypeTagData(Type, LayoutCompatible, MustBeNull);
12222}
12223
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012224static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012225 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12226 if (!BT1)
12227 return false;
12228
12229 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12230 if (!BT2)
12231 return false;
12232
12233 BuiltinType::Kind T1Kind = BT1->getKind();
12234 BuiltinType::Kind T2Kind = BT2->getKind();
12235
12236 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12237 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12238 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12239 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12240}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012241
12242void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012243 const ArrayRef<const Expr *> ExprArgs,
12244 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012245 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12246 bool IsPointerAttr = Attr->getIsPointer();
12247
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012248 // Retrieve the argument representing the 'type_tag'.
12249 if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12250 // Add 1 to display the user's specified value.
12251 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12252 << 0 << Attr->getTypeTagIdx() + 1;
12253 return;
12254 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012255 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12256 bool FoundWrongKind;
12257 TypeTagData TypeInfo;
12258 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12259 TypeTagForDatatypeMagicValues.get(),
12260 FoundWrongKind, TypeInfo)) {
12261 if (FoundWrongKind)
12262 Diag(TypeTagExpr->getExprLoc(),
12263 diag::warn_type_tag_for_datatype_wrong_kind)
12264 << TypeTagExpr->getSourceRange();
12265 return;
12266 }
12267
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012268 // Retrieve the argument representing the 'arg_idx'.
12269 if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12270 // Add 1 to display the user's specified value.
12271 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12272 << 1 << Attr->getArgumentIdx() + 1;
12273 return;
12274 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012275 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12276 if (IsPointerAttr) {
12277 // Skip implicit cast of pointer to `void *' (as a function argument).
12278 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012279 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012280 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012281 ArgumentExpr = ICE->getSubExpr();
12282 }
12283 QualType ArgumentType = ArgumentExpr->getType();
12284
12285 // Passing a `void*' pointer shouldn't trigger a warning.
12286 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12287 return;
12288
12289 if (TypeInfo.MustBeNull) {
12290 // Type tag with matching void type requires a null pointer.
12291 if (!ArgumentExpr->isNullPointerConstant(Context,
12292 Expr::NPC_ValueDependentIsNotNull)) {
12293 Diag(ArgumentExpr->getExprLoc(),
12294 diag::warn_type_safety_null_pointer_required)
12295 << ArgumentKind->getName()
12296 << ArgumentExpr->getSourceRange()
12297 << TypeTagExpr->getSourceRange();
12298 }
12299 return;
12300 }
12301
12302 QualType RequiredType = TypeInfo.Type;
12303 if (IsPointerAttr)
12304 RequiredType = Context.getPointerType(RequiredType);
12305
12306 bool mismatch = false;
12307 if (!TypeInfo.LayoutCompatible) {
12308 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12309
12310 // C++11 [basic.fundamental] p1:
12311 // Plain char, signed char, and unsigned char are three distinct types.
12312 //
12313 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12314 // char' depending on the current char signedness mode.
12315 if (mismatch)
12316 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12317 RequiredType->getPointeeType())) ||
12318 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12319 mismatch = false;
12320 } else
12321 if (IsPointerAttr)
12322 mismatch = !isLayoutCompatible(Context,
12323 ArgumentType->getPointeeType(),
12324 RequiredType->getPointeeType());
12325 else
12326 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12327
12328 if (mismatch)
12329 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012330 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012331 << TypeInfo.LayoutCompatible << RequiredType
12332 << ArgumentExpr->getSourceRange()
12333 << TypeTagExpr->getSourceRange();
12334}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012335
12336void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12337 CharUnits Alignment) {
12338 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12339}
12340
12341void Sema::DiagnoseMisalignedMembers() {
12342 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012343 const NamedDecl *ND = m.RD;
12344 if (ND->getName().empty()) {
12345 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12346 ND = TD;
12347 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012348 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012349 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012350 }
12351 MisalignedMembers.clear();
12352}
12353
12354void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012355 E = E->IgnoreParens();
12356 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012357 return;
12358 if (isa<UnaryOperator>(E) &&
12359 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12360 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12361 if (isa<MemberExpr>(Op)) {
12362 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12363 MisalignedMember(Op));
12364 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012365 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012366 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12367 Context.getTypeAlignInChars(
12368 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012369 MisalignedMembers.erase(MA);
12370 }
12371 }
12372}
12373
12374void Sema::RefersToMemberWithReducedAlignment(
12375 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012376 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12377 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012378 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012379 if (!ME)
12380 return;
12381
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012382 // No need to check expressions with an __unaligned-qualified type.
12383 if (E->getType().getQualifiers().hasUnaligned())
12384 return;
12385
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012386 // For a chain of MemberExpr like "a.b.c.d" this list
12387 // will keep FieldDecl's like [d, c, b].
12388 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12389 const MemberExpr *TopME = nullptr;
12390 bool AnyIsPacked = false;
12391 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012392 QualType BaseType = ME->getBase()->getType();
12393 if (ME->isArrow())
12394 BaseType = BaseType->getPointeeType();
12395 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012396 if (RD->isInvalidDecl())
12397 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012398
12399 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012400 auto *FD = dyn_cast<FieldDecl>(MD);
12401 // We do not care about non-data members.
12402 if (!FD || FD->isInvalidDecl())
12403 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012404
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012405 AnyIsPacked =
12406 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12407 ReverseMemberChain.push_back(FD);
12408
12409 TopME = ME;
12410 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12411 } while (ME);
12412 assert(TopME && "We did not compute a topmost MemberExpr!");
12413
12414 // Not the scope of this diagnostic.
12415 if (!AnyIsPacked)
12416 return;
12417
12418 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12419 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12420 // TODO: The innermost base of the member expression may be too complicated.
12421 // For now, just disregard these cases. This is left for future
12422 // improvement.
12423 if (!DRE && !isa<CXXThisExpr>(TopBase))
12424 return;
12425
12426 // Alignment expected by the whole expression.
12427 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12428
12429 // No need to do anything else with this case.
12430 if (ExpectedAlignment.isOne())
12431 return;
12432
12433 // Synthesize offset of the whole access.
12434 CharUnits Offset;
12435 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12436 I++) {
12437 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12438 }
12439
12440 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12441 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12442 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12443
12444 // The base expression of the innermost MemberExpr may give
12445 // stronger guarantees than the class containing the member.
12446 if (DRE && !TopME->isArrow()) {
12447 const ValueDecl *VD = DRE->getDecl();
12448 if (!VD->getType()->isReferenceType())
12449 CompleteObjectAlignment =
12450 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12451 }
12452
12453 // Check if the synthesized offset fulfills the alignment.
12454 if (Offset % ExpectedAlignment != 0 ||
12455 // It may fulfill the offset it but the effective alignment may still be
12456 // lower than the expected expression alignment.
12457 CompleteObjectAlignment < ExpectedAlignment) {
12458 // If this happens, we want to determine a sensible culprit of this.
12459 // Intuitively, watching the chain of member expressions from right to
12460 // left, we start with the required alignment (as required by the field
12461 // type) but some packed attribute in that chain has reduced the alignment.
12462 // It may happen that another packed structure increases it again. But if
12463 // we are here such increase has not been enough. So pointing the first
12464 // FieldDecl that either is packed or else its RecordDecl is,
12465 // seems reasonable.
12466 FieldDecl *FD = nullptr;
12467 CharUnits Alignment;
12468 for (FieldDecl *FDI : ReverseMemberChain) {
12469 if (FDI->hasAttr<PackedAttr>() ||
12470 FDI->getParent()->hasAttr<PackedAttr>()) {
12471 FD = FDI;
12472 Alignment = std::min(
12473 Context.getTypeAlignInChars(FD->getType()),
12474 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12475 break;
12476 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012477 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012478 assert(FD && "We did not find a packed FieldDecl!");
12479 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012480 }
12481}
12482
12483void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12484 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012485
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012486 RefersToMemberWithReducedAlignment(
12487 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12488 _2, _3, _4));
12489}