1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
getLocationOfStringLiteralByte(const StringLiteral * SL,unsigned ByteNo) const106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
checkArgCount(Sema & S,CallExpr * call,unsigned desiredArgCount)114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
SemaBuiltinAnnotation(Sema & S,CallExpr * TheCall)134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
SemaBuiltinMSVCAnnotation(Sema & S,CallExpr * TheCall)160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
SemaBuiltinAddressof(Sema & S,CallExpr * TheCall)184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
SemaBuiltinPreserveAI(Sema & S,CallExpr * TheCall)200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
SemaBuiltinAlignment(Sema & S,CallExpr * TheCall,unsigned ID)211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
SemaBuiltinOverflow(Sema & S,CallExpr * TheCall,unsigned BuiltinID)289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
SemaBuiltinCallWithStaticChain(Sema & S,CallExpr * BuiltinCall)346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
EstimateSizeFormatHandler(StringRef Format)416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier & FS,const char *,unsigned SpecifierLen)420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
getSizeLowerBound() const532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
computeFieldWidth(const analyze_printf::PrintfSpecifier & FS)535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
computePrecision(const analyze_printf::PrintfSpecifier & FS)543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
checkFortifiedBuiltinMemoryFunction(FunctionDecl * FD,CallExpr * TheCall)594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << toString(ObjectSize, /*Radix=*/10)
776                           << toString(UsedSize.getValue(), /*Radix=*/10));
777 }
778 
SemaBuiltinSEHScopeCheck(Sema & SemaRef,CallExpr * TheCall,Scope::ScopeFlags NeededScopeFlags,unsigned DiagID)779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
isBlockPointer(Expr * Arg)801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
checkOpenCLBlockArgs(Sema & S,Expr * BlockArg)807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
checkOpenCLSubgroupExt(Sema & S,CallExpr * Call)840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
SemaOpenCLBuiltinNDRangeAndBlock(Sema & S,CallExpr * TheCall)849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
SemaOpenCLBuiltinKernelWorkGroupSize(Sema & S,CallExpr * TheCall)876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
checkOpenCLEnqueueLocalSizeArgs(Sema & S,CallExpr * TheCall,unsigned Start,unsigned End)893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
checkOpenCLEnqueueVariadicArgs(Sema & S,CallExpr * TheCall,Expr * BlockArg,unsigned NumNonVarArgs)904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
SemaOpenCLBuiltinEnqueueKernel(Sema & S,CallExpr * TheCall)952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
getOpenCLArgAccess(const Decl * D)1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
checkOpenCLPipeArg(Sema & S,CallExpr * Call)1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
checkOpenCLPipePacketType(Sema & S,CallExpr * Call,unsigned Idx)1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
SemaBuiltinRWPipe(Sema & S,CallExpr * Call)1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
SemaBuiltinReserveRWPipe(Sema & S,CallExpr * Call)1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
SemaBuiltinCommitRWPipe(Sema & S,CallExpr * Call)1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
SemaBuiltinPipePackets(Sema & S,CallExpr * Call)1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
SemaOpenCLBuiltinToAddr(Sema & S,unsigned BuiltinID,CallExpr * Call)1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
SemaBuiltinLaunder(Sema & S,CallExpr * TheCall)1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
CheckBuiltinTargetSupport(Sema & S,unsigned BuiltinID,CallExpr * TheCall,ArrayRef<llvm::Triple::ArchType> SupportedArchs)1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
CheckTSBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
CheckBuiltinFunctionCall(FunctionDecl * FDecl,unsigned BuiltinID,CallExpr * TheCall)1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__arithmetic_fence:
1558     if (SemaBuiltinArithmeticFence(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__assume:
1562   case Builtin::BI__builtin_assume:
1563     if (SemaBuiltinAssume(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_assume_aligned:
1567     if (SemaBuiltinAssumeAligned(TheCall))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_dynamic_object_size:
1571   case Builtin::BI__builtin_object_size:
1572     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_longjmp:
1576     if (SemaBuiltinLongjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_setjmp:
1580     if (SemaBuiltinSetjmp(TheCall))
1581       return ExprError();
1582     break;
1583   case Builtin::BI__builtin_classify_type:
1584     if (checkArgCount(*this, TheCall, 1)) return true;
1585     TheCall->setType(Context.IntTy);
1586     break;
1587   case Builtin::BI__builtin_complex:
1588     if (SemaBuiltinComplex(TheCall))
1589       return ExprError();
1590     break;
1591   case Builtin::BI__builtin_constant_p: {
1592     if (checkArgCount(*this, TheCall, 1)) return true;
1593     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1594     if (Arg.isInvalid()) return true;
1595     TheCall->setArg(0, Arg.get());
1596     TheCall->setType(Context.IntTy);
1597     break;
1598   }
1599   case Builtin::BI__builtin_launder:
1600     return SemaBuiltinLaunder(*this, TheCall);
1601   case Builtin::BI__sync_fetch_and_add:
1602   case Builtin::BI__sync_fetch_and_add_1:
1603   case Builtin::BI__sync_fetch_and_add_2:
1604   case Builtin::BI__sync_fetch_and_add_4:
1605   case Builtin::BI__sync_fetch_and_add_8:
1606   case Builtin::BI__sync_fetch_and_add_16:
1607   case Builtin::BI__sync_fetch_and_sub:
1608   case Builtin::BI__sync_fetch_and_sub_1:
1609   case Builtin::BI__sync_fetch_and_sub_2:
1610   case Builtin::BI__sync_fetch_and_sub_4:
1611   case Builtin::BI__sync_fetch_and_sub_8:
1612   case Builtin::BI__sync_fetch_and_sub_16:
1613   case Builtin::BI__sync_fetch_and_or:
1614   case Builtin::BI__sync_fetch_and_or_1:
1615   case Builtin::BI__sync_fetch_and_or_2:
1616   case Builtin::BI__sync_fetch_and_or_4:
1617   case Builtin::BI__sync_fetch_and_or_8:
1618   case Builtin::BI__sync_fetch_and_or_16:
1619   case Builtin::BI__sync_fetch_and_and:
1620   case Builtin::BI__sync_fetch_and_and_1:
1621   case Builtin::BI__sync_fetch_and_and_2:
1622   case Builtin::BI__sync_fetch_and_and_4:
1623   case Builtin::BI__sync_fetch_and_and_8:
1624   case Builtin::BI__sync_fetch_and_and_16:
1625   case Builtin::BI__sync_fetch_and_xor:
1626   case Builtin::BI__sync_fetch_and_xor_1:
1627   case Builtin::BI__sync_fetch_and_xor_2:
1628   case Builtin::BI__sync_fetch_and_xor_4:
1629   case Builtin::BI__sync_fetch_and_xor_8:
1630   case Builtin::BI__sync_fetch_and_xor_16:
1631   case Builtin::BI__sync_fetch_and_nand:
1632   case Builtin::BI__sync_fetch_and_nand_1:
1633   case Builtin::BI__sync_fetch_and_nand_2:
1634   case Builtin::BI__sync_fetch_and_nand_4:
1635   case Builtin::BI__sync_fetch_and_nand_8:
1636   case Builtin::BI__sync_fetch_and_nand_16:
1637   case Builtin::BI__sync_add_and_fetch:
1638   case Builtin::BI__sync_add_and_fetch_1:
1639   case Builtin::BI__sync_add_and_fetch_2:
1640   case Builtin::BI__sync_add_and_fetch_4:
1641   case Builtin::BI__sync_add_and_fetch_8:
1642   case Builtin::BI__sync_add_and_fetch_16:
1643   case Builtin::BI__sync_sub_and_fetch:
1644   case Builtin::BI__sync_sub_and_fetch_1:
1645   case Builtin::BI__sync_sub_and_fetch_2:
1646   case Builtin::BI__sync_sub_and_fetch_4:
1647   case Builtin::BI__sync_sub_and_fetch_8:
1648   case Builtin::BI__sync_sub_and_fetch_16:
1649   case Builtin::BI__sync_and_and_fetch:
1650   case Builtin::BI__sync_and_and_fetch_1:
1651   case Builtin::BI__sync_and_and_fetch_2:
1652   case Builtin::BI__sync_and_and_fetch_4:
1653   case Builtin::BI__sync_and_and_fetch_8:
1654   case Builtin::BI__sync_and_and_fetch_16:
1655   case Builtin::BI__sync_or_and_fetch:
1656   case Builtin::BI__sync_or_and_fetch_1:
1657   case Builtin::BI__sync_or_and_fetch_2:
1658   case Builtin::BI__sync_or_and_fetch_4:
1659   case Builtin::BI__sync_or_and_fetch_8:
1660   case Builtin::BI__sync_or_and_fetch_16:
1661   case Builtin::BI__sync_xor_and_fetch:
1662   case Builtin::BI__sync_xor_and_fetch_1:
1663   case Builtin::BI__sync_xor_and_fetch_2:
1664   case Builtin::BI__sync_xor_and_fetch_4:
1665   case Builtin::BI__sync_xor_and_fetch_8:
1666   case Builtin::BI__sync_xor_and_fetch_16:
1667   case Builtin::BI__sync_nand_and_fetch:
1668   case Builtin::BI__sync_nand_and_fetch_1:
1669   case Builtin::BI__sync_nand_and_fetch_2:
1670   case Builtin::BI__sync_nand_and_fetch_4:
1671   case Builtin::BI__sync_nand_and_fetch_8:
1672   case Builtin::BI__sync_nand_and_fetch_16:
1673   case Builtin::BI__sync_val_compare_and_swap:
1674   case Builtin::BI__sync_val_compare_and_swap_1:
1675   case Builtin::BI__sync_val_compare_and_swap_2:
1676   case Builtin::BI__sync_val_compare_and_swap_4:
1677   case Builtin::BI__sync_val_compare_and_swap_8:
1678   case Builtin::BI__sync_val_compare_and_swap_16:
1679   case Builtin::BI__sync_bool_compare_and_swap:
1680   case Builtin::BI__sync_bool_compare_and_swap_1:
1681   case Builtin::BI__sync_bool_compare_and_swap_2:
1682   case Builtin::BI__sync_bool_compare_and_swap_4:
1683   case Builtin::BI__sync_bool_compare_and_swap_8:
1684   case Builtin::BI__sync_bool_compare_and_swap_16:
1685   case Builtin::BI__sync_lock_test_and_set:
1686   case Builtin::BI__sync_lock_test_and_set_1:
1687   case Builtin::BI__sync_lock_test_and_set_2:
1688   case Builtin::BI__sync_lock_test_and_set_4:
1689   case Builtin::BI__sync_lock_test_and_set_8:
1690   case Builtin::BI__sync_lock_test_and_set_16:
1691   case Builtin::BI__sync_lock_release:
1692   case Builtin::BI__sync_lock_release_1:
1693   case Builtin::BI__sync_lock_release_2:
1694   case Builtin::BI__sync_lock_release_4:
1695   case Builtin::BI__sync_lock_release_8:
1696   case Builtin::BI__sync_lock_release_16:
1697   case Builtin::BI__sync_swap:
1698   case Builtin::BI__sync_swap_1:
1699   case Builtin::BI__sync_swap_2:
1700   case Builtin::BI__sync_swap_4:
1701   case Builtin::BI__sync_swap_8:
1702   case Builtin::BI__sync_swap_16:
1703     return SemaBuiltinAtomicOverloaded(TheCallResult);
1704   case Builtin::BI__sync_synchronize:
1705     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1706         << TheCall->getCallee()->getSourceRange();
1707     break;
1708   case Builtin::BI__builtin_nontemporal_load:
1709   case Builtin::BI__builtin_nontemporal_store:
1710     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1711   case Builtin::BI__builtin_memcpy_inline: {
1712     clang::Expr *SizeOp = TheCall->getArg(2);
1713     // We warn about copying to or from `nullptr` pointers when `size` is
1714     // greater than 0. When `size` is value dependent we cannot evaluate its
1715     // value so we bail out.
1716     if (SizeOp->isValueDependent())
1717       break;
1718     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1719       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1720       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1721     }
1722     break;
1723   }
1724 #define BUILTIN(ID, TYPE, ATTRS)
1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1726   case Builtin::BI##ID: \
1727     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1728 #include "clang/Basic/Builtins.def"
1729   case Builtin::BI__annotation:
1730     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_annotation:
1734     if (SemaBuiltinAnnotation(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_addressof:
1738     if (SemaBuiltinAddressof(*this, TheCall))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_is_aligned:
1742   case Builtin::BI__builtin_align_up:
1743   case Builtin::BI__builtin_align_down:
1744     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_add_overflow:
1748   case Builtin::BI__builtin_sub_overflow:
1749   case Builtin::BI__builtin_mul_overflow:
1750     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1751       return ExprError();
1752     break;
1753   case Builtin::BI__builtin_operator_new:
1754   case Builtin::BI__builtin_operator_delete: {
1755     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1756     ExprResult Res =
1757         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1758     if (Res.isInvalid())
1759       CorrectDelayedTyposInExpr(TheCallResult.get());
1760     return Res;
1761   }
1762   case Builtin::BI__builtin_dump_struct: {
1763     // We first want to ensure we are called with 2 arguments
1764     if (checkArgCount(*this, TheCall, 2))
1765       return ExprError();
1766     // Ensure that the first argument is of type 'struct XX *'
1767     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1768     const QualType PtrArgType = PtrArg->getType();
1769     if (!PtrArgType->isPointerType() ||
1770         !PtrArgType->getPointeeType()->isRecordType()) {
1771       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1773           << "structure pointer";
1774       return ExprError();
1775     }
1776 
1777     // Ensure that the second argument is of type 'FunctionType'
1778     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1779     const QualType FnPtrArgType = FnPtrArg->getType();
1780     if (!FnPtrArgType->isPointerType()) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     const auto *FuncType =
1788         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1789 
1790     if (!FuncType) {
1791       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1792           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1793           << FnPtrArgType << "'int (*)(const char *, ...)'";
1794       return ExprError();
1795     }
1796 
1797     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1798       if (!FT->getNumParams()) {
1799         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1800             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1801             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1802         return ExprError();
1803       }
1804       QualType PT = FT->getParamType(0);
1805       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1806           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1807           !PT->getPointeeType().isConstQualified()) {
1808         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1809             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1810             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1811         return ExprError();
1812       }
1813     }
1814 
1815     TheCall->setType(Context.IntTy);
1816     break;
1817   }
1818   case Builtin::BI__builtin_expect_with_probability: {
1819     // We first want to ensure we are called with 3 arguments
1820     if (checkArgCount(*this, TheCall, 3))
1821       return ExprError();
1822     // then check probability is constant float in range [0.0, 1.0]
1823     const Expr *ProbArg = TheCall->getArg(2);
1824     SmallVector<PartialDiagnosticAt, 8> Notes;
1825     Expr::EvalResult Eval;
1826     Eval.Diag = &Notes;
1827     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1828         !Eval.Val.isFloat()) {
1829       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1830           << ProbArg->getSourceRange();
1831       for (const PartialDiagnosticAt &PDiag : Notes)
1832         Diag(PDiag.first, PDiag.second);
1833       return ExprError();
1834     }
1835     llvm::APFloat Probability = Eval.Val.getFloat();
1836     bool LoseInfo = false;
1837     Probability.convert(llvm::APFloat::IEEEdouble(),
1838                         llvm::RoundingMode::Dynamic, &LoseInfo);
1839     if (!(Probability >= llvm::APFloat(0.0) &&
1840           Probability <= llvm::APFloat(1.0))) {
1841       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1842           << ProbArg->getSourceRange();
1843       return ExprError();
1844     }
1845     break;
1846   }
1847   case Builtin::BI__builtin_preserve_access_index:
1848     if (SemaBuiltinPreserveAI(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__builtin_call_with_static_chain:
1852     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1853       return ExprError();
1854     break;
1855   case Builtin::BI__exception_code:
1856   case Builtin::BI_exception_code:
1857     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1858                                  diag::err_seh___except_block))
1859       return ExprError();
1860     break;
1861   case Builtin::BI__exception_info:
1862   case Builtin::BI_exception_info:
1863     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1864                                  diag::err_seh___except_filter))
1865       return ExprError();
1866     break;
1867   case Builtin::BI__GetExceptionInfo:
1868     if (checkArgCount(*this, TheCall, 1))
1869       return ExprError();
1870 
1871     if (CheckCXXThrowOperand(
1872             TheCall->getBeginLoc(),
1873             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1874             TheCall))
1875       return ExprError();
1876 
1877     TheCall->setType(Context.VoidPtrTy);
1878     break;
1879   // OpenCL v2.0, s6.13.16 - Pipe functions
1880   case Builtin::BIread_pipe:
1881   case Builtin::BIwrite_pipe:
1882     // Since those two functions are declared with var args, we need a semantic
1883     // check for the argument.
1884     if (SemaBuiltinRWPipe(*this, TheCall))
1885       return ExprError();
1886     break;
1887   case Builtin::BIreserve_read_pipe:
1888   case Builtin::BIreserve_write_pipe:
1889   case Builtin::BIwork_group_reserve_read_pipe:
1890   case Builtin::BIwork_group_reserve_write_pipe:
1891     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1892       return ExprError();
1893     break;
1894   case Builtin::BIsub_group_reserve_read_pipe:
1895   case Builtin::BIsub_group_reserve_write_pipe:
1896     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1897         SemaBuiltinReserveRWPipe(*this, TheCall))
1898       return ExprError();
1899     break;
1900   case Builtin::BIcommit_read_pipe:
1901   case Builtin::BIcommit_write_pipe:
1902   case Builtin::BIwork_group_commit_read_pipe:
1903   case Builtin::BIwork_group_commit_write_pipe:
1904     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1905       return ExprError();
1906     break;
1907   case Builtin::BIsub_group_commit_read_pipe:
1908   case Builtin::BIsub_group_commit_write_pipe:
1909     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1910         SemaBuiltinCommitRWPipe(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIget_pipe_num_packets:
1914   case Builtin::BIget_pipe_max_packets:
1915     if (SemaBuiltinPipePackets(*this, TheCall))
1916       return ExprError();
1917     break;
1918   case Builtin::BIto_global:
1919   case Builtin::BIto_local:
1920   case Builtin::BIto_private:
1921     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1922       return ExprError();
1923     break;
1924   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1925   case Builtin::BIenqueue_kernel:
1926     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_work_group_size:
1930   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1931     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1935   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1936     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1937       return ExprError();
1938     break;
1939   case Builtin::BI__builtin_os_log_format:
1940     Cleanup.setExprNeedsCleanups(true);
1941     LLVM_FALLTHROUGH;
1942   case Builtin::BI__builtin_os_log_format_buffer_size:
1943     if (SemaBuiltinOSLogFormat(TheCall))
1944       return ExprError();
1945     break;
1946   case Builtin::BI__builtin_frame_address:
1947   case Builtin::BI__builtin_return_address: {
1948     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1949       return ExprError();
1950 
1951     // -Wframe-address warning if non-zero passed to builtin
1952     // return/frame address.
1953     Expr::EvalResult Result;
1954     if (!TheCall->getArg(0)->isValueDependent() &&
1955         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1956         Result.Val.getInt() != 0)
1957       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1958           << ((BuiltinID == Builtin::BI__builtin_return_address)
1959                   ? "__builtin_return_address"
1960                   : "__builtin_frame_address")
1961           << TheCall->getSourceRange();
1962     break;
1963   }
1964 
1965   case Builtin::BI__builtin_matrix_transpose:
1966     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_load:
1969     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_matrix_column_major_store:
1972     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1973 
1974   case Builtin::BI__builtin_get_device_side_mangled_name: {
1975     auto Check = [](CallExpr *TheCall) {
1976       if (TheCall->getNumArgs() != 1)
1977         return false;
1978       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1979       if (!DRE)
1980         return false;
1981       auto *D = DRE->getDecl();
1982       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1983         return false;
1984       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1985              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1986     };
1987     if (!Check(TheCall)) {
1988       Diag(TheCall->getBeginLoc(),
1989            diag::err_hip_invalid_args_builtin_mangled_name);
1990       return ExprError();
1991     }
1992   }
1993   }
1994 
1995   // Since the target specific builtins for each arch overlap, only check those
1996   // of the arch we are compiling for.
1997   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1998     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1999       assert(Context.getAuxTargetInfo() &&
2000              "Aux Target Builtin, but not an aux target?");
2001 
2002       if (CheckTSBuiltinFunctionCall(
2003               *Context.getAuxTargetInfo(),
2004               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2005         return ExprError();
2006     } else {
2007       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2008                                      TheCall))
2009         return ExprError();
2010     }
2011   }
2012 
2013   return TheCallResult;
2014 }
2015 
2016 // Get the valid immediate range for the specified NEON type code.
RFT(unsigned t,bool shift=false,bool ForceQuad=false)2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2018   NeonTypeFlags Type(t);
2019   int IsQuad = ForceQuad ? true : Type.isQuad();
2020   switch (Type.getEltType()) {
2021   case NeonTypeFlags::Int8:
2022   case NeonTypeFlags::Poly8:
2023     return shift ? 7 : (8 << IsQuad) - 1;
2024   case NeonTypeFlags::Int16:
2025   case NeonTypeFlags::Poly16:
2026     return shift ? 15 : (4 << IsQuad) - 1;
2027   case NeonTypeFlags::Int32:
2028     return shift ? 31 : (2 << IsQuad) - 1;
2029   case NeonTypeFlags::Int64:
2030   case NeonTypeFlags::Poly64:
2031     return shift ? 63 : (1 << IsQuad) - 1;
2032   case NeonTypeFlags::Poly128:
2033     return shift ? 127 : (1 << IsQuad) - 1;
2034   case NeonTypeFlags::Float16:
2035     assert(!shift && "cannot shift float types!");
2036     return (4 << IsQuad) - 1;
2037   case NeonTypeFlags::Float32:
2038     assert(!shift && "cannot shift float types!");
2039     return (2 << IsQuad) - 1;
2040   case NeonTypeFlags::Float64:
2041     assert(!shift && "cannot shift float types!");
2042     return (1 << IsQuad) - 1;
2043   case NeonTypeFlags::BFloat16:
2044     assert(!shift && "cannot shift float types!");
2045     return (4 << IsQuad) - 1;
2046   }
2047   llvm_unreachable("Invalid NeonTypeFlag!");
2048 }
2049 
2050 /// getNeonEltType - Return the QualType corresponding to the elements of
2051 /// the vector type specified by the NeonTypeFlags.  This is used to check
2052 /// the pointer arguments for Neon load/store intrinsics.
getNeonEltType(NeonTypeFlags Flags,ASTContext & Context,bool IsPolyUnsigned,bool IsInt64Long)2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2054                                bool IsPolyUnsigned, bool IsInt64Long) {
2055   switch (Flags.getEltType()) {
2056   case NeonTypeFlags::Int8:
2057     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2058   case NeonTypeFlags::Int16:
2059     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2060   case NeonTypeFlags::Int32:
2061     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2062   case NeonTypeFlags::Int64:
2063     if (IsInt64Long)
2064       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2065     else
2066       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2067                                 : Context.LongLongTy;
2068   case NeonTypeFlags::Poly8:
2069     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2070   case NeonTypeFlags::Poly16:
2071     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2072   case NeonTypeFlags::Poly64:
2073     if (IsInt64Long)
2074       return Context.UnsignedLongTy;
2075     else
2076       return Context.UnsignedLongLongTy;
2077   case NeonTypeFlags::Poly128:
2078     break;
2079   case NeonTypeFlags::Float16:
2080     return Context.HalfTy;
2081   case NeonTypeFlags::Float32:
2082     return Context.FloatTy;
2083   case NeonTypeFlags::Float64:
2084     return Context.DoubleTy;
2085   case NeonTypeFlags::BFloat16:
2086     return Context.BFloat16Ty;
2087   }
2088   llvm_unreachable("Invalid NeonTypeFlag!");
2089 }
2090 
CheckSVEBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2092   // Range check SVE intrinsics that take immediate values.
2093   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2094 
2095   switch (BuiltinID) {
2096   default:
2097     return false;
2098 #define GET_SVE_IMMEDIATE_CHECK
2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2100 #undef GET_SVE_IMMEDIATE_CHECK
2101   }
2102 
2103   // Perform all the immediate checks for this builtin call.
2104   bool HasError = false;
2105   for (auto &I : ImmChecks) {
2106     int ArgNum, CheckTy, ElementSizeInBits;
2107     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2108 
2109     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2110 
2111     // Function that checks whether the operand (ArgNum) is an immediate
2112     // that is one of the predefined values.
2113     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2114                                    int ErrDiag) -> bool {
2115       // We can't check the value of a dependent argument.
2116       Expr *Arg = TheCall->getArg(ArgNum);
2117       if (Arg->isTypeDependent() || Arg->isValueDependent())
2118         return false;
2119 
2120       // Check constant-ness first.
2121       llvm::APSInt Imm;
2122       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2123         return true;
2124 
2125       if (!CheckImm(Imm.getSExtValue()))
2126         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2127       return false;
2128     };
2129 
2130     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2131     case SVETypeFlags::ImmCheck0_31:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck0_13:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck1_16:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheck0_7:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckExtract:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (2048 / ElementSizeInBits) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRight:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckShiftRightNarrow:
2157       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2158                                       ElementSizeInBits / 2))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckShiftLeft:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       ElementSizeInBits - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckLaneIndex:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2168                                       (128 / (1 * ElementSizeInBits)) - 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2173                                       (128 / (2 * ElementSizeInBits)) - 1))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheckLaneIndexDot:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2178                                       (128 / (4 * ElementSizeInBits)) - 1))
2179         HasError = true;
2180       break;
2181     case SVETypeFlags::ImmCheckComplexRot90_270:
2182       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2183                               diag::err_rotation_argument_to_cadd))
2184         HasError = true;
2185       break;
2186     case SVETypeFlags::ImmCheckComplexRotAll90:
2187       if (CheckImmediateInSet(
2188               [](int64_t V) {
2189                 return V == 0 || V == 90 || V == 180 || V == 270;
2190               },
2191               diag::err_rotation_argument_to_cmla))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_1:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_2:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2200         HasError = true;
2201       break;
2202     case SVETypeFlags::ImmCheck0_3:
2203       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2204         HasError = true;
2205       break;
2206     }
2207   }
2208 
2209   return HasError;
2210 }
2211 
CheckNeonBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2213                                         unsigned BuiltinID, CallExpr *TheCall) {
2214   llvm::APSInt Result;
2215   uint64_t mask = 0;
2216   unsigned TV = 0;
2217   int PtrArgNum = -1;
2218   bool HasConstPtr = false;
2219   switch (BuiltinID) {
2220 #define GET_NEON_OVERLOAD_CHECK
2221 #include "clang/Basic/arm_neon.inc"
2222 #include "clang/Basic/arm_fp16.inc"
2223 #undef GET_NEON_OVERLOAD_CHECK
2224   }
2225 
2226   // For NEON intrinsics which are overloaded on vector element type, validate
2227   // the immediate which specifies which variant to emit.
2228   unsigned ImmArg = TheCall->getNumArgs()-1;
2229   if (mask) {
2230     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2231       return true;
2232 
2233     TV = Result.getLimitedValue(64);
2234     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2235       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2236              << TheCall->getArg(ImmArg)->getSourceRange();
2237   }
2238 
2239   if (PtrArgNum >= 0) {
2240     // Check that pointer arguments have the specified type.
2241     Expr *Arg = TheCall->getArg(PtrArgNum);
2242     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2243       Arg = ICE->getSubExpr();
2244     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2245     QualType RHSTy = RHS.get()->getType();
2246 
2247     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2248     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2249                           Arch == llvm::Triple::aarch64_32 ||
2250                           Arch == llvm::Triple::aarch64_be;
2251     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2252     QualType EltTy =
2253         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2254     if (HasConstPtr)
2255       EltTy = EltTy.withConst();
2256     QualType LHSTy = Context.getPointerType(EltTy);
2257     AssignConvertType ConvTy;
2258     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2259     if (RHS.isInvalid())
2260       return true;
2261     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2262                                  RHS.get(), AA_Assigning))
2263       return true;
2264   }
2265 
2266   // For NEON intrinsics which take an immediate value as part of the
2267   // instruction, range check them here.
2268   unsigned i = 0, l = 0, u = 0;
2269   switch (BuiltinID) {
2270   default:
2271     return false;
2272   #define GET_NEON_IMMEDIATE_CHECK
2273   #include "clang/Basic/arm_neon.inc"
2274   #include "clang/Basic/arm_fp16.inc"
2275   #undef GET_NEON_IMMEDIATE_CHECK
2276   }
2277 
2278   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2279 }
2280 
CheckMVEBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2282   switch (BuiltinID) {
2283   default:
2284     return false;
2285   #include "clang/Basic/arm_mve_builtin_sema.inc"
2286   }
2287 }
2288 
CheckCDEBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2290                                        CallExpr *TheCall) {
2291   bool Err = false;
2292   switch (BuiltinID) {
2293   default:
2294     return false;
2295 #include "clang/Basic/arm_cde_builtin_sema.inc"
2296   }
2297 
2298   if (Err)
2299     return true;
2300 
2301   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2302 }
2303 
CheckARMCoprocessorImmediate(const TargetInfo & TI,const Expr * CoprocArg,bool WantCDE)2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2305                                         const Expr *CoprocArg, bool WantCDE) {
2306   if (isConstantEvaluated())
2307     return false;
2308 
2309   // We can't check the value of a dependent argument.
2310   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2311     return false;
2312 
2313   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2314   int64_t CoprocNo = CoprocNoAP.getExtValue();
2315   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2316 
2317   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2318   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2319 
2320   if (IsCDECoproc != WantCDE)
2321     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2322            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2323 
2324   return false;
2325 }
2326 
CheckARMBuiltinExclusiveCall(unsigned BuiltinID,CallExpr * TheCall,unsigned MaxWidth)2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2328                                         unsigned MaxWidth) {
2329   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2330           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2331           BuiltinID == ARM::BI__builtin_arm_strex ||
2332           BuiltinID == ARM::BI__builtin_arm_stlex ||
2333           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2334           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2335           BuiltinID == AArch64::BI__builtin_arm_strex ||
2336           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2337          "unexpected ARM builtin");
2338   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2339                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2340                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2341                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2342 
2343   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2344 
2345   // Ensure that we have the proper number of arguments.
2346   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2347     return true;
2348 
2349   // Inspect the pointer argument of the atomic builtin.  This should always be
2350   // a pointer type, whose element is an integral scalar or pointer type.
2351   // Because it is a pointer type, we don't have to worry about any implicit
2352   // casts here.
2353   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2354   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2360   if (!pointerType) {
2361     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2362         << PointerArg->getType() << PointerArg->getSourceRange();
2363     return true;
2364   }
2365 
2366   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2367   // task is to insert the appropriate casts into the AST. First work out just
2368   // what the appropriate type is.
2369   QualType ValType = pointerType->getPointeeType();
2370   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2371   if (IsLdrex)
2372     AddrType.addConst();
2373 
2374   // Issue a warning if the cast is dodgy.
2375   CastKind CastNeeded = CK_NoOp;
2376   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2377     CastNeeded = CK_BitCast;
2378     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2379         << PointerArg->getType() << Context.getPointerType(AddrType)
2380         << AA_Passing << PointerArg->getSourceRange();
2381   }
2382 
2383   // Finally, do the cast and replace the argument with the corrected version.
2384   AddrType = Context.getPointerType(AddrType);
2385   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2386   if (PointerArgRes.isInvalid())
2387     return true;
2388   PointerArg = PointerArgRes.get();
2389 
2390   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2391 
2392   // In general, we allow ints, floats and pointers to be loaded and stored.
2393   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2394       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2395     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2396         << PointerArg->getType() << PointerArg->getSourceRange();
2397     return true;
2398   }
2399 
2400   // But ARM doesn't have instructions to deal with 128-bit versions.
2401   if (Context.getTypeSize(ValType) > MaxWidth) {
2402     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2403     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2404         << PointerArg->getType() << PointerArg->getSourceRange();
2405     return true;
2406   }
2407 
2408   switch (ValType.getObjCLifetime()) {
2409   case Qualifiers::OCL_None:
2410   case Qualifiers::OCL_ExplicitNone:
2411     // okay
2412     break;
2413 
2414   case Qualifiers::OCL_Weak:
2415   case Qualifiers::OCL_Strong:
2416   case Qualifiers::OCL_Autoreleasing:
2417     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2418         << ValType << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   if (IsLdrex) {
2423     TheCall->setType(ValType);
2424     return false;
2425   }
2426 
2427   // Initialize the argument to be stored.
2428   ExprResult ValArg = TheCall->getArg(0);
2429   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2430       Context, ValType, /*consume*/ false);
2431   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2432   if (ValArg.isInvalid())
2433     return true;
2434   TheCall->setArg(0, ValArg.get());
2435 
2436   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2437   // but the custom checker bypasses all default analysis.
2438   TheCall->setType(Context.IntTy);
2439   return false;
2440 }
2441 
CheckARMBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2443                                        CallExpr *TheCall) {
2444   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2445       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2446       BuiltinID == ARM::BI__builtin_arm_strex ||
2447       BuiltinID == ARM::BI__builtin_arm_stlex) {
2448     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2449   }
2450 
2451   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2453       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2454   }
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2457       BuiltinID == ARM::BI__builtin_arm_wsr64)
2458     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2459 
2460   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2461       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2462       BuiltinID == ARM::BI__builtin_arm_wsr ||
2463       BuiltinID == ARM::BI__builtin_arm_wsrp)
2464     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2465 
2466   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2471     return true;
2472 
2473   // For intrinsics which take an immediate value as part of the instruction,
2474   // range check them here.
2475   // FIXME: VFP Intrinsics should error if VFP not present.
2476   switch (BuiltinID) {
2477   default: return false;
2478   case ARM::BI__builtin_arm_ssat:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2480   case ARM::BI__builtin_arm_usat:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2482   case ARM::BI__builtin_arm_ssat16:
2483     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2484   case ARM::BI__builtin_arm_usat16:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2486   case ARM::BI__builtin_arm_vcvtr_f:
2487   case ARM::BI__builtin_arm_vcvtr_d:
2488     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2489   case ARM::BI__builtin_arm_dmb:
2490   case ARM::BI__builtin_arm_dsb:
2491   case ARM::BI__builtin_arm_isb:
2492   case ARM::BI__builtin_arm_dbg:
2493     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2494   case ARM::BI__builtin_arm_cdp:
2495   case ARM::BI__builtin_arm_cdp2:
2496   case ARM::BI__builtin_arm_mcr:
2497   case ARM::BI__builtin_arm_mcr2:
2498   case ARM::BI__builtin_arm_mrc:
2499   case ARM::BI__builtin_arm_mrc2:
2500   case ARM::BI__builtin_arm_mcrr:
2501   case ARM::BI__builtin_arm_mcrr2:
2502   case ARM::BI__builtin_arm_mrrc:
2503   case ARM::BI__builtin_arm_mrrc2:
2504   case ARM::BI__builtin_arm_ldc:
2505   case ARM::BI__builtin_arm_ldcl:
2506   case ARM::BI__builtin_arm_ldc2:
2507   case ARM::BI__builtin_arm_ldc2l:
2508   case ARM::BI__builtin_arm_stc:
2509   case ARM::BI__builtin_arm_stcl:
2510   case ARM::BI__builtin_arm_stc2:
2511   case ARM::BI__builtin_arm_stc2l:
2512     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2513            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2514                                         /*WantCDE*/ false);
2515   }
2516 }
2517 
CheckAArch64BuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2519                                            unsigned BuiltinID,
2520                                            CallExpr *TheCall) {
2521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2523       BuiltinID == AArch64::BI__builtin_arm_strex ||
2524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2526   }
2527 
2528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2533   }
2534 
2535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2538 
2539   // Memory Tagging Extensions (MTE) Intrinsics
2540   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2541       BuiltinID == AArch64::BI__builtin_arm_addg ||
2542       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2543       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2544       BuiltinID == AArch64::BI__builtin_arm_stg ||
2545       BuiltinID == AArch64::BI__builtin_arm_subp) {
2546     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2550       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2551       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2552       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2553     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2554 
2555   // Only check the valid encoding range. Any constant in this range would be
2556   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2557   // an exception for incorrect registers. This matches MSVC behavior.
2558   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2559       BuiltinID == AArch64::BI_WriteStatusReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2561 
2562   if (BuiltinID == AArch64::BI__getReg)
2563     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2564 
2565   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2566     return true;
2567 
2568   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2569     return true;
2570 
2571   // For intrinsics which take an immediate value as part of the instruction,
2572   // range check them here.
2573   unsigned i = 0, l = 0, u = 0;
2574   switch (BuiltinID) {
2575   default: return false;
2576   case AArch64::BI__builtin_arm_dmb:
2577   case AArch64::BI__builtin_arm_dsb:
2578   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2579   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2580   }
2581 
2582   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2583 }
2584 
isValidBPFPreserveFieldInfoArg(Expr * Arg)2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2586   if (Arg->getType()->getAsPlaceholderType())
2587     return false;
2588 
2589   // The first argument needs to be a record field access.
2590   // If it is an array element access, we delay decision
2591   // to BPF backend to check whether the access is a
2592   // field access or not.
2593   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2594           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2595           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2596 }
2597 
isEltOfVectorTy(ASTContext & Context,CallExpr * Call,Sema & S,QualType VectorTy,QualType EltTy)2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2599                             QualType VectorTy, QualType EltTy) {
2600   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2601   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2602     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2603         << Call->getSourceRange() << VectorEltTy << EltTy;
2604     return false;
2605   }
2606   return true;
2607 }
2608 
isValidBPFPreserveTypeInfoArg(Expr * Arg)2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2615   // format:
2616   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2617   //   2. <type> var;
2618   //      __builtin_preserve_type_info(var, flag);
2619   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2620       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2621     return false;
2622 
2623   // Typedef type.
2624   if (ArgType->getAs<TypedefType>())
2625     return true;
2626 
2627   // Record type or Enum type.
2628   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2629   if (const auto *RT = Ty->getAs<RecordType>()) {
2630     if (!RT->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2633     if (!ET->getDecl()->getDeclName().isEmpty())
2634       return true;
2635   }
2636 
2637   return false;
2638 }
2639 
isValidBPFPreserveEnumValueArg(Expr * Arg)2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2641   QualType ArgType = Arg->getType();
2642   if (ArgType->getAsPlaceholderType())
2643     return false;
2644 
2645   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2646   // format:
2647   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2648   //                                 flag);
2649   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2650   if (!UO)
2651     return false;
2652 
2653   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2654   if (!CE)
2655     return false;
2656   if (CE->getCastKind() != CK_IntegralToPointer &&
2657       CE->getCastKind() != CK_NullToPointer)
2658     return false;
2659 
2660   // The integer must be from an EnumConstantDecl.
2661   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2662   if (!DR)
2663     return false;
2664 
2665   const EnumConstantDecl *Enumerator =
2666       dyn_cast<EnumConstantDecl>(DR->getDecl());
2667   if (!Enumerator)
2668     return false;
2669 
2670   // The type must be EnumType.
2671   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2672   const auto *ET = Ty->getAs<EnumType>();
2673   if (!ET)
2674     return false;
2675 
2676   // The enum value must be supported.
2677   for (auto *EDI : ET->getDecl()->enumerators()) {
2678     if (EDI == Enumerator)
2679       return true;
2680   }
2681 
2682   return false;
2683 }
2684 
CheckBPFBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2686                                        CallExpr *TheCall) {
2687   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2688           BuiltinID == BPF::BI__builtin_btf_type_id ||
2689           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2690           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2691          "unexpected BPF builtin");
2692 
2693   if (checkArgCount(*this, TheCall, 2))
2694     return true;
2695 
2696   // The second argument needs to be a constant int
2697   Expr *Arg = TheCall->getArg(1);
2698   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2699   diag::kind kind;
2700   if (!Value) {
2701     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2702       kind = diag::err_preserve_field_info_not_const;
2703     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2704       kind = diag::err_btf_type_id_not_const;
2705     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2706       kind = diag::err_preserve_type_info_not_const;
2707     else
2708       kind = diag::err_preserve_enum_value_not_const;
2709     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2710     return true;
2711   }
2712 
2713   // The first argument
2714   Arg = TheCall->getArg(0);
2715   bool InvalidArg = false;
2716   bool ReturnUnsignedInt = true;
2717   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2718     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2719       InvalidArg = true;
2720       kind = diag::err_preserve_field_info_not_field;
2721     }
2722   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2723     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2724       InvalidArg = true;
2725       kind = diag::err_preserve_type_info_invalid;
2726     }
2727   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2728     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2729       InvalidArg = true;
2730       kind = diag::err_preserve_enum_value_invalid;
2731     }
2732     ReturnUnsignedInt = false;
2733   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2734     ReturnUnsignedInt = false;
2735   }
2736 
2737   if (InvalidArg) {
2738     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2739     return true;
2740   }
2741 
2742   if (ReturnUnsignedInt)
2743     TheCall->setType(Context.UnsignedIntTy);
2744   else
2745     TheCall->setType(Context.UnsignedLongTy);
2746   return false;
2747 }
2748 
CheckHexagonBuiltinArgument(unsigned BuiltinID,CallExpr * TheCall)2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2750   struct ArgInfo {
2751     uint8_t OpNum;
2752     bool IsSigned;
2753     uint8_t BitWidth;
2754     uint8_t Align;
2755   };
2756   struct BuiltinInfo {
2757     unsigned BuiltinID;
2758     ArgInfo Infos[2];
2759   };
2760 
2761   static BuiltinInfo Infos[] = {
2762     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2763     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2764     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2765     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2766     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2767     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2768     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2769     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2770     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2771     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2772     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2773 
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2777     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2779     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2785 
2786     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2838                                                       {{ 1, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2846                                                       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2853                                                        { 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2855                                                        { 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2857                                                        { 3, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2859                                                        { 3, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2885                                                       {{ 2, false, 4,  0 },
2886                                                        { 3, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2898                                                        { 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2900                                                        { 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2913                                                       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2934                                                       {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2939                                                       {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2944                                                       {{ 3, false, 1,  0 }} },
2945   };
2946 
2947   // Use a dynamically initialized static to sort the table exactly once on
2948   // first run.
2949   static const bool SortOnce =
2950       (llvm::sort(Infos,
2951                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2952                    return LHS.BuiltinID < RHS.BuiltinID;
2953                  }),
2954        true);
2955   (void)SortOnce;
2956 
2957   const BuiltinInfo *F = llvm::partition_point(
2958       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2959   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2960     return false;
2961 
2962   bool Error = false;
2963 
2964   for (const ArgInfo &A : F->Infos) {
2965     // Ignore empty ArgInfo elements.
2966     if (A.BitWidth == 0)
2967       continue;
2968 
2969     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2970     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2971     if (!A.Align) {
2972       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2973     } else {
2974       unsigned M = 1 << A.Align;
2975       Min *= M;
2976       Max *= M;
2977       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2978                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2979     }
2980   }
2981   return Error;
2982 }
2983 
CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2985                                            CallExpr *TheCall) {
2986   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2987 }
2988 
CheckMipsBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2990                                         unsigned BuiltinID, CallExpr *TheCall) {
2991   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2992          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2993 }
2994 
CheckMipsBuiltinCpu(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2996                                CallExpr *TheCall) {
2997 
2998   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2999       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3000     if (!TI.hasFeature("dsp"))
3001       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3002   }
3003 
3004   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3005       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3006     if (!TI.hasFeature("dspr2"))
3007       return Diag(TheCall->getBeginLoc(),
3008                   diag::err_mips_builtin_requires_dspr2);
3009   }
3010 
3011   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3012       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3013     if (!TI.hasFeature("msa"))
3014       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3015   }
3016 
3017   return false;
3018 }
3019 
3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3022 // ordering for DSP is unspecified. MSA is ordered by the data format used
3023 // by the underlying instruction i.e., df/m, df/n and then by size.
3024 //
3025 // FIXME: The size tests here should instead be tablegen'd along with the
3026 //        definitions from include/clang/Basic/BuiltinsMips.def.
3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3028 //        be too.
CheckMipsBuiltinArgument(unsigned BuiltinID,CallExpr * TheCall)3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3030   unsigned i = 0, l = 0, u = 0, m = 0;
3031   switch (BuiltinID) {
3032   default: return false;
3033   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3034   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3035   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3037   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3038   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3039   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3040   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3041   // df/m field.
3042   // These intrinsics take an unsigned 3 bit immediate.
3043   case Mips::BI__builtin_msa_bclri_b:
3044   case Mips::BI__builtin_msa_bnegi_b:
3045   case Mips::BI__builtin_msa_bseti_b:
3046   case Mips::BI__builtin_msa_sat_s_b:
3047   case Mips::BI__builtin_msa_sat_u_b:
3048   case Mips::BI__builtin_msa_slli_b:
3049   case Mips::BI__builtin_msa_srai_b:
3050   case Mips::BI__builtin_msa_srari_b:
3051   case Mips::BI__builtin_msa_srli_b:
3052   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3053   case Mips::BI__builtin_msa_binsli_b:
3054   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3055   // These intrinsics take an unsigned 4 bit immediate.
3056   case Mips::BI__builtin_msa_bclri_h:
3057   case Mips::BI__builtin_msa_bnegi_h:
3058   case Mips::BI__builtin_msa_bseti_h:
3059   case Mips::BI__builtin_msa_sat_s_h:
3060   case Mips::BI__builtin_msa_sat_u_h:
3061   case Mips::BI__builtin_msa_slli_h:
3062   case Mips::BI__builtin_msa_srai_h:
3063   case Mips::BI__builtin_msa_srari_h:
3064   case Mips::BI__builtin_msa_srli_h:
3065   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3066   case Mips::BI__builtin_msa_binsli_h:
3067   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3068   // These intrinsics take an unsigned 5 bit immediate.
3069   // The first block of intrinsics actually have an unsigned 5 bit field,
3070   // not a df/n field.
3071   case Mips::BI__builtin_msa_cfcmsa:
3072   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3073   case Mips::BI__builtin_msa_clei_u_b:
3074   case Mips::BI__builtin_msa_clei_u_h:
3075   case Mips::BI__builtin_msa_clei_u_w:
3076   case Mips::BI__builtin_msa_clei_u_d:
3077   case Mips::BI__builtin_msa_clti_u_b:
3078   case Mips::BI__builtin_msa_clti_u_h:
3079   case Mips::BI__builtin_msa_clti_u_w:
3080   case Mips::BI__builtin_msa_clti_u_d:
3081   case Mips::BI__builtin_msa_maxi_u_b:
3082   case Mips::BI__builtin_msa_maxi_u_h:
3083   case Mips::BI__builtin_msa_maxi_u_w:
3084   case Mips::BI__builtin_msa_maxi_u_d:
3085   case Mips::BI__builtin_msa_mini_u_b:
3086   case Mips::BI__builtin_msa_mini_u_h:
3087   case Mips::BI__builtin_msa_mini_u_w:
3088   case Mips::BI__builtin_msa_mini_u_d:
3089   case Mips::BI__builtin_msa_addvi_b:
3090   case Mips::BI__builtin_msa_addvi_h:
3091   case Mips::BI__builtin_msa_addvi_w:
3092   case Mips::BI__builtin_msa_addvi_d:
3093   case Mips::BI__builtin_msa_bclri_w:
3094   case Mips::BI__builtin_msa_bnegi_w:
3095   case Mips::BI__builtin_msa_bseti_w:
3096   case Mips::BI__builtin_msa_sat_s_w:
3097   case Mips::BI__builtin_msa_sat_u_w:
3098   case Mips::BI__builtin_msa_slli_w:
3099   case Mips::BI__builtin_msa_srai_w:
3100   case Mips::BI__builtin_msa_srari_w:
3101   case Mips::BI__builtin_msa_srli_w:
3102   case Mips::BI__builtin_msa_srlri_w:
3103   case Mips::BI__builtin_msa_subvi_b:
3104   case Mips::BI__builtin_msa_subvi_h:
3105   case Mips::BI__builtin_msa_subvi_w:
3106   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3107   case Mips::BI__builtin_msa_binsli_w:
3108   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3109   // These intrinsics take an unsigned 6 bit immediate.
3110   case Mips::BI__builtin_msa_bclri_d:
3111   case Mips::BI__builtin_msa_bnegi_d:
3112   case Mips::BI__builtin_msa_bseti_d:
3113   case Mips::BI__builtin_msa_sat_s_d:
3114   case Mips::BI__builtin_msa_sat_u_d:
3115   case Mips::BI__builtin_msa_slli_d:
3116   case Mips::BI__builtin_msa_srai_d:
3117   case Mips::BI__builtin_msa_srari_d:
3118   case Mips::BI__builtin_msa_srli_d:
3119   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3120   case Mips::BI__builtin_msa_binsli_d:
3121   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3122   // These intrinsics take a signed 5 bit immediate.
3123   case Mips::BI__builtin_msa_ceqi_b:
3124   case Mips::BI__builtin_msa_ceqi_h:
3125   case Mips::BI__builtin_msa_ceqi_w:
3126   case Mips::BI__builtin_msa_ceqi_d:
3127   case Mips::BI__builtin_msa_clti_s_b:
3128   case Mips::BI__builtin_msa_clti_s_h:
3129   case Mips::BI__builtin_msa_clti_s_w:
3130   case Mips::BI__builtin_msa_clti_s_d:
3131   case Mips::BI__builtin_msa_clei_s_b:
3132   case Mips::BI__builtin_msa_clei_s_h:
3133   case Mips::BI__builtin_msa_clei_s_w:
3134   case Mips::BI__builtin_msa_clei_s_d:
3135   case Mips::BI__builtin_msa_maxi_s_b:
3136   case Mips::BI__builtin_msa_maxi_s_h:
3137   case Mips::BI__builtin_msa_maxi_s_w:
3138   case Mips::BI__builtin_msa_maxi_s_d:
3139   case Mips::BI__builtin_msa_mini_s_b:
3140   case Mips::BI__builtin_msa_mini_s_h:
3141   case Mips::BI__builtin_msa_mini_s_w:
3142   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3143   // These intrinsics take an unsigned 8 bit immediate.
3144   case Mips::BI__builtin_msa_andi_b:
3145   case Mips::BI__builtin_msa_nori_b:
3146   case Mips::BI__builtin_msa_ori_b:
3147   case Mips::BI__builtin_msa_shf_b:
3148   case Mips::BI__builtin_msa_shf_h:
3149   case Mips::BI__builtin_msa_shf_w:
3150   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3151   case Mips::BI__builtin_msa_bseli_b:
3152   case Mips::BI__builtin_msa_bmnzi_b:
3153   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3154   // df/n format
3155   // These intrinsics take an unsigned 4 bit immediate.
3156   case Mips::BI__builtin_msa_copy_s_b:
3157   case Mips::BI__builtin_msa_copy_u_b:
3158   case Mips::BI__builtin_msa_insve_b:
3159   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3160   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3161   // These intrinsics take an unsigned 3 bit immediate.
3162   case Mips::BI__builtin_msa_copy_s_h:
3163   case Mips::BI__builtin_msa_copy_u_h:
3164   case Mips::BI__builtin_msa_insve_h:
3165   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3166   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3167   // These intrinsics take an unsigned 2 bit immediate.
3168   case Mips::BI__builtin_msa_copy_s_w:
3169   case Mips::BI__builtin_msa_copy_u_w:
3170   case Mips::BI__builtin_msa_insve_w:
3171   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3172   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3173   // These intrinsics take an unsigned 1 bit immediate.
3174   case Mips::BI__builtin_msa_copy_s_d:
3175   case Mips::BI__builtin_msa_copy_u_d:
3176   case Mips::BI__builtin_msa_insve_d:
3177   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3178   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3179   // Memory offsets and immediate loads.
3180   // These intrinsics take a signed 10 bit immediate.
3181   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3182   case Mips::BI__builtin_msa_ldi_h:
3183   case Mips::BI__builtin_msa_ldi_w:
3184   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3185   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3186   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3187   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3189   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3190   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3192   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3193   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3195   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3196   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3197   }
3198 
3199   if (!m)
3200     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3201 
3202   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3203          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3204 }
3205 
3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3207 /// advancing the pointer over the consumed characters. The decoded type is
3208 /// returned. If the decoded type represents a constant integer with a
3209 /// constraint on its value then Mask is set to that value. The type descriptors
3210 /// used in Str are specific to PPC MMA builtins and are documented in the file
3211 /// defining the PPC builtins.
DecodePPCMMATypeFromStr(ASTContext & Context,const char * & Str,unsigned & Mask)3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3213                                         unsigned &Mask) {
3214   bool RequireICE = false;
3215   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3216   switch (*Str++) {
3217   case 'V':
3218     return Context.getVectorType(Context.UnsignedCharTy, 16,
3219                                  VectorType::VectorKind::AltiVecVector);
3220   case 'i': {
3221     char *End;
3222     unsigned size = strtoul(Str, &End, 10);
3223     assert(End != Str && "Missing constant parameter constraint");
3224     Str = End;
3225     Mask = size;
3226     return Context.IntTy;
3227   }
3228   case 'W': {
3229     char *End;
3230     unsigned size = strtoul(Str, &End, 10);
3231     assert(End != Str && "Missing PowerPC MMA type size");
3232     Str = End;
3233     QualType Type;
3234     switch (size) {
3235   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3236     case size: Type = Context.Id##Ty; break;
3237   #include "clang/Basic/PPCTypes.def"
3238     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3239     }
3240     bool CheckVectorArgs = false;
3241     while (!CheckVectorArgs) {
3242       switch (*Str++) {
3243       case '*':
3244         Type = Context.getPointerType(Type);
3245         break;
3246       case 'C':
3247         Type = Type.withConst();
3248         break;
3249       default:
3250         CheckVectorArgs = true;
3251         --Str;
3252         break;
3253       }
3254     }
3255     return Type;
3256   }
3257   default:
3258     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3259   }
3260 }
3261 
isPPC_64Builtin(unsigned BuiltinID)3262 static bool isPPC_64Builtin(unsigned BuiltinID) {
3263   // These builtins only work on PPC 64bit targets.
3264   switch (BuiltinID) {
3265   case PPC::BI__builtin_divde:
3266   case PPC::BI__builtin_divdeu:
3267   case PPC::BI__builtin_bpermd:
3268   case PPC::BI__builtin_ppc_ldarx:
3269   case PPC::BI__builtin_ppc_stdcx:
3270   case PPC::BI__builtin_ppc_tdw:
3271   case PPC::BI__builtin_ppc_trapd:
3272   case PPC::BI__builtin_ppc_cmpeqb:
3273   case PPC::BI__builtin_ppc_setb:
3274   case PPC::BI__builtin_ppc_mulhd:
3275   case PPC::BI__builtin_ppc_mulhdu:
3276   case PPC::BI__builtin_ppc_maddhd:
3277   case PPC::BI__builtin_ppc_maddhdu:
3278   case PPC::BI__builtin_ppc_maddld:
3279   case PPC::BI__builtin_ppc_load8r:
3280   case PPC::BI__builtin_ppc_store8r:
3281   case PPC::BI__builtin_ppc_insert_exp:
3282   case PPC::BI__builtin_ppc_extract_sig:
3283     return true;
3284   }
3285   return false;
3286 }
3287 
SemaFeatureCheck(Sema & S,CallExpr * TheCall,StringRef FeatureToCheck,unsigned DiagID,StringRef DiagArg="")3288 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3289                              StringRef FeatureToCheck, unsigned DiagID,
3290                              StringRef DiagArg = "") {
3291   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3292     return false;
3293 
3294   if (DiagArg.empty())
3295     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3296   else
3297     S.Diag(TheCall->getBeginLoc(), DiagID)
3298         << DiagArg << TheCall->getSourceRange();
3299 
3300   return true;
3301 }
3302 
3303 /// Returns true if the argument consists of one contiguous run of 1s with any
3304 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3305 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3306 /// since all 1s are not contiguous.
SemaValueIsRunOfOnes(CallExpr * TheCall,unsigned ArgNum)3307 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3308   llvm::APSInt Result;
3309   // We can't check the value of a dependent argument.
3310   Expr *Arg = TheCall->getArg(ArgNum);
3311   if (Arg->isTypeDependent() || Arg->isValueDependent())
3312     return false;
3313 
3314   // Check constant-ness first.
3315   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3316     return true;
3317 
3318   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3319   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3320     return false;
3321 
3322   return Diag(TheCall->getBeginLoc(),
3323               diag::err_argument_not_contiguous_bit_field)
3324          << ArgNum << Arg->getSourceRange();
3325 }
3326 
CheckPPCBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)3327 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3328                                        CallExpr *TheCall) {
3329   unsigned i = 0, l = 0, u = 0;
3330   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3331   llvm::APSInt Result;
3332 
3333   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3334     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3335            << TheCall->getSourceRange();
3336 
3337   switch (BuiltinID) {
3338   default: return false;
3339   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3340   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3341     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3342            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3343   case PPC::BI__builtin_altivec_dss:
3344     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3345   case PPC::BI__builtin_tbegin:
3346   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3347   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3348   case PPC::BI__builtin_tabortwc:
3349   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3350   case PPC::BI__builtin_tabortwci:
3351   case PPC::BI__builtin_tabortdci:
3352     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3353            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3354   case PPC::BI__builtin_altivec_dst:
3355   case PPC::BI__builtin_altivec_dstt:
3356   case PPC::BI__builtin_altivec_dstst:
3357   case PPC::BI__builtin_altivec_dststt:
3358     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3359   case PPC::BI__builtin_vsx_xxpermdi:
3360   case PPC::BI__builtin_vsx_xxsldwi:
3361     return SemaBuiltinVSX(TheCall);
3362   case PPC::BI__builtin_divwe:
3363   case PPC::BI__builtin_divweu:
3364   case PPC::BI__builtin_divde:
3365   case PPC::BI__builtin_divdeu:
3366     return SemaFeatureCheck(*this, TheCall, "extdiv",
3367                             diag::err_ppc_builtin_only_on_arch, "7");
3368   case PPC::BI__builtin_bpermd:
3369     return SemaFeatureCheck(*this, TheCall, "bpermd",
3370                             diag::err_ppc_builtin_only_on_arch, "7");
3371   case PPC::BI__builtin_unpack_vector_int128:
3372     return SemaFeatureCheck(*this, TheCall, "vsx",
3373                             diag::err_ppc_builtin_only_on_arch, "7") ||
3374            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3375   case PPC::BI__builtin_pack_vector_int128:
3376     return SemaFeatureCheck(*this, TheCall, "vsx",
3377                             diag::err_ppc_builtin_only_on_arch, "7");
3378   case PPC::BI__builtin_altivec_vgnb:
3379      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3380   case PPC::BI__builtin_altivec_vec_replace_elt:
3381   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3382     QualType VecTy = TheCall->getArg(0)->getType();
3383     QualType EltTy = TheCall->getArg(1)->getType();
3384     unsigned Width = Context.getIntWidth(EltTy);
3385     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3386            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3387   }
3388   case PPC::BI__builtin_vsx_xxeval:
3389      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3390   case PPC::BI__builtin_altivec_vsldbi:
3391      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3392   case PPC::BI__builtin_altivec_vsrdbi:
3393      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3394   case PPC::BI__builtin_vsx_xxpermx:
3395      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3396   case PPC::BI__builtin_ppc_tw:
3397   case PPC::BI__builtin_ppc_tdw:
3398     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3399   case PPC::BI__builtin_ppc_cmpeqb:
3400   case PPC::BI__builtin_ppc_setb:
3401   case PPC::BI__builtin_ppc_maddhd:
3402   case PPC::BI__builtin_ppc_maddhdu:
3403   case PPC::BI__builtin_ppc_maddld:
3404     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3405                             diag::err_ppc_builtin_only_on_arch, "9");
3406   case PPC::BI__builtin_ppc_cmprb:
3407     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3408                             diag::err_ppc_builtin_only_on_arch, "9") ||
3409            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3410   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3411   // be a constant that represents a contiguous bit field.
3412   case PPC::BI__builtin_ppc_rlwnm:
3413     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3414            SemaValueIsRunOfOnes(TheCall, 2);
3415   case PPC::BI__builtin_ppc_rlwimi:
3416   case PPC::BI__builtin_ppc_rldimi:
3417     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3418            SemaValueIsRunOfOnes(TheCall, 3);
3419   case PPC::BI__builtin_ppc_extract_exp:
3420   case PPC::BI__builtin_ppc_extract_sig:
3421   case PPC::BI__builtin_ppc_insert_exp:
3422     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3423                             diag::err_ppc_builtin_only_on_arch, "9");
3424   case PPC::BI__builtin_ppc_mtfsb0:
3425   case PPC::BI__builtin_ppc_mtfsb1:
3426     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3427   case PPC::BI__builtin_ppc_mtfsf:
3428     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3429   case PPC::BI__builtin_ppc_mtfsfi:
3430     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3431            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3432   case PPC::BI__builtin_ppc_alignx:
3433     return SemaBuiltinConstantArgPower2(TheCall, 0);
3434   case PPC::BI__builtin_ppc_rdlam:
3435     return SemaValueIsRunOfOnes(TheCall, 2);
3436   case PPC::BI__builtin_ppc_icbt:
3437   case PPC::BI__builtin_ppc_sthcx:
3438   case PPC::BI__builtin_ppc_stbcx:
3439   case PPC::BI__builtin_ppc_lharx:
3440   case PPC::BI__builtin_ppc_lbarx:
3441     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3442                             diag::err_ppc_builtin_only_on_arch, "8");
3443   case PPC::BI__builtin_vsx_ldrmb:
3444   case PPC::BI__builtin_vsx_strmb:
3445     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3446                             diag::err_ppc_builtin_only_on_arch, "8") ||
3447            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3448 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3449   case PPC::BI__builtin_##Name: \
3450     return SemaBuiltinPPCMMACall(TheCall, Types);
3451 #include "clang/Basic/BuiltinsPPC.def"
3452   }
3453   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3454 }
3455 
3456 // Check if the given type is a non-pointer PPC MMA type. This function is used
3457 // in Sema to prevent invalid uses of restricted PPC MMA types.
CheckPPCMMAType(QualType Type,SourceLocation TypeLoc)3458 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3459   if (Type->isPointerType() || Type->isArrayType())
3460     return false;
3461 
3462   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3463 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3464   if (false
3465 #include "clang/Basic/PPCTypes.def"
3466      ) {
3467     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3468     return true;
3469   }
3470   return false;
3471 }
3472 
CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)3473 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3474                                           CallExpr *TheCall) {
3475   // position of memory order and scope arguments in the builtin
3476   unsigned OrderIndex, ScopeIndex;
3477   switch (BuiltinID) {
3478   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3479   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3480   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3481   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3482     OrderIndex = 2;
3483     ScopeIndex = 3;
3484     break;
3485   case AMDGPU::BI__builtin_amdgcn_fence:
3486     OrderIndex = 0;
3487     ScopeIndex = 1;
3488     break;
3489   default:
3490     return false;
3491   }
3492 
3493   ExprResult Arg = TheCall->getArg(OrderIndex);
3494   auto ArgExpr = Arg.get();
3495   Expr::EvalResult ArgResult;
3496 
3497   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3498     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3499            << ArgExpr->getType();
3500   auto Ord = ArgResult.Val.getInt().getZExtValue();
3501 
3502   // Check valididty of memory ordering as per C11 / C++11's memody model.
3503   // Only fence needs check. Atomic dec/inc allow all memory orders.
3504   if (!llvm::isValidAtomicOrderingCABI(Ord))
3505     return Diag(ArgExpr->getBeginLoc(),
3506                 diag::warn_atomic_op_has_invalid_memory_order)
3507            << ArgExpr->getSourceRange();
3508   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3509   case llvm::AtomicOrderingCABI::relaxed:
3510   case llvm::AtomicOrderingCABI::consume:
3511     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3512       return Diag(ArgExpr->getBeginLoc(),
3513                   diag::warn_atomic_op_has_invalid_memory_order)
3514              << ArgExpr->getSourceRange();
3515     break;
3516   case llvm::AtomicOrderingCABI::acquire:
3517   case llvm::AtomicOrderingCABI::release:
3518   case llvm::AtomicOrderingCABI::acq_rel:
3519   case llvm::AtomicOrderingCABI::seq_cst:
3520     break;
3521   }
3522 
3523   Arg = TheCall->getArg(ScopeIndex);
3524   ArgExpr = Arg.get();
3525   Expr::EvalResult ArgResult1;
3526   // Check that sync scope is a constant literal
3527   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3528     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3529            << ArgExpr->getType();
3530 
3531   return false;
3532 }
3533 
CheckRISCVLMUL(CallExpr * TheCall,unsigned ArgNum)3534 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3535   llvm::APSInt Result;
3536 
3537   // We can't check the value of a dependent argument.
3538   Expr *Arg = TheCall->getArg(ArgNum);
3539   if (Arg->isTypeDependent() || Arg->isValueDependent())
3540     return false;
3541 
3542   // Check constant-ness first.
3543   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3544     return true;
3545 
3546   int64_t Val = Result.getSExtValue();
3547   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3548     return false;
3549 
3550   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3551          << Arg->getSourceRange();
3552 }
3553 
CheckRISCVBuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)3554 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3555                                          unsigned BuiltinID,
3556                                          CallExpr *TheCall) {
3557   // CodeGenFunction can also detect this, but this gives a better error
3558   // message.
3559   bool FeatureMissing = false;
3560   SmallVector<StringRef> ReqFeatures;
3561   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3562   Features.split(ReqFeatures, ',');
3563 
3564   // Check if each required feature is included
3565   for (StringRef F : ReqFeatures) {
3566     if (TI.hasFeature(F))
3567       continue;
3568 
3569     // If the feature is 64bit, alter the string so it will print better in
3570     // the diagnostic.
3571     if (F == "64bit")
3572       F = "RV64";
3573 
3574     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3575     F.consume_front("experimental-");
3576     std::string FeatureStr = F.str();
3577     FeatureStr[0] = std::toupper(FeatureStr[0]);
3578 
3579     // Error message
3580     FeatureMissing = true;
3581     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3582         << TheCall->getSourceRange() << StringRef(FeatureStr);
3583   }
3584 
3585   if (FeatureMissing)
3586     return true;
3587 
3588   switch (BuiltinID) {
3589   case RISCV::BI__builtin_rvv_vsetvli:
3590     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3591            CheckRISCVLMUL(TheCall, 2);
3592   case RISCV::BI__builtin_rvv_vsetvlimax:
3593     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3594            CheckRISCVLMUL(TheCall, 1);
3595   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3596   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3597   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3598   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3599   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3600   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3601   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3602   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3603   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3604   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3605   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3606   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3607   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3608   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3609   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3610   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3611   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3612   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3613   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3614   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3615   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3616   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3617   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3618   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3619   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3620   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3621   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3622   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3623   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3624   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3625     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3626   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3627   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3628   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3629   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3630   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3631   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3632   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3633   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3634   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3635   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3636   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3637   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3638   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3639   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3640   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3641   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3642   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3643   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3644   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3645   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3646     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3647   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3648   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3649   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3650   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3651   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3652   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3653   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3654   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3655   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3656   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3657     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3658   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3659   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3660   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3661   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3662   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3663   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3664   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3665   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3666   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3667   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3668   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3669   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3670   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3671   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3672   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3673   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3674   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3675   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3676   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3677   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3678   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3679   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3680   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3681   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3682   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3683   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3684   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3685   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3686   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3687   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3688     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3689   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3690   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3691   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3692   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3693   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3694   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3695   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3696   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3697   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3698   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3699   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3700   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3701   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3702   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3703   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3704   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3705   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3706   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3707   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3708   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3709     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3710   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3711   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3712   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3713   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3714   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3715   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3716   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3717   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3718   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3719   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3720     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3721   }
3722 
3723   return false;
3724 }
3725 
CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)3726 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3727                                            CallExpr *TheCall) {
3728   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3729     Expr *Arg = TheCall->getArg(0);
3730     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3731       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3732         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3733                << Arg->getSourceRange();
3734   }
3735 
3736   // For intrinsics which take an immediate value as part of the instruction,
3737   // range check them here.
3738   unsigned i = 0, l = 0, u = 0;
3739   switch (BuiltinID) {
3740   default: return false;
3741   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3742   case SystemZ::BI__builtin_s390_verimb:
3743   case SystemZ::BI__builtin_s390_verimh:
3744   case SystemZ::BI__builtin_s390_verimf:
3745   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3746   case SystemZ::BI__builtin_s390_vfaeb:
3747   case SystemZ::BI__builtin_s390_vfaeh:
3748   case SystemZ::BI__builtin_s390_vfaef:
3749   case SystemZ::BI__builtin_s390_vfaebs:
3750   case SystemZ::BI__builtin_s390_vfaehs:
3751   case SystemZ::BI__builtin_s390_vfaefs:
3752   case SystemZ::BI__builtin_s390_vfaezb:
3753   case SystemZ::BI__builtin_s390_vfaezh:
3754   case SystemZ::BI__builtin_s390_vfaezf:
3755   case SystemZ::BI__builtin_s390_vfaezbs:
3756   case SystemZ::BI__builtin_s390_vfaezhs:
3757   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3758   case SystemZ::BI__builtin_s390_vfisb:
3759   case SystemZ::BI__builtin_s390_vfidb:
3760     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3761            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3762   case SystemZ::BI__builtin_s390_vftcisb:
3763   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3764   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3765   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3766   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3767   case SystemZ::BI__builtin_s390_vstrcb:
3768   case SystemZ::BI__builtin_s390_vstrch:
3769   case SystemZ::BI__builtin_s390_vstrcf:
3770   case SystemZ::BI__builtin_s390_vstrczb:
3771   case SystemZ::BI__builtin_s390_vstrczh:
3772   case SystemZ::BI__builtin_s390_vstrczf:
3773   case SystemZ::BI__builtin_s390_vstrcbs:
3774   case SystemZ::BI__builtin_s390_vstrchs:
3775   case SystemZ::BI__builtin_s390_vstrcfs:
3776   case SystemZ::BI__builtin_s390_vstrczbs:
3777   case SystemZ::BI__builtin_s390_vstrczhs:
3778   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3779   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3780   case SystemZ::BI__builtin_s390_vfminsb:
3781   case SystemZ::BI__builtin_s390_vfmaxsb:
3782   case SystemZ::BI__builtin_s390_vfmindb:
3783   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3784   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3785   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3786   case SystemZ::BI__builtin_s390_vclfnhs:
3787   case SystemZ::BI__builtin_s390_vclfnls:
3788   case SystemZ::BI__builtin_s390_vcfn:
3789   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3790   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3791   }
3792   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3793 }
3794 
3795 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3796 /// This checks that the target supports __builtin_cpu_supports and
3797 /// that the string argument is constant and valid.
SemaBuiltinCpuSupports(Sema & S,const TargetInfo & TI,CallExpr * TheCall)3798 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3799                                    CallExpr *TheCall) {
3800   Expr *Arg = TheCall->getArg(0);
3801 
3802   // Check if the argument is a string literal.
3803   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3804     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3805            << Arg->getSourceRange();
3806 
3807   // Check the contents of the string.
3808   StringRef Feature =
3809       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3810   if (!TI.validateCpuSupports(Feature))
3811     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3812            << Arg->getSourceRange();
3813   return false;
3814 }
3815 
3816 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3817 /// This checks that the target supports __builtin_cpu_is and
3818 /// that the string argument is constant and valid.
SemaBuiltinCpuIs(Sema & S,const TargetInfo & TI,CallExpr * TheCall)3819 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3820   Expr *Arg = TheCall->getArg(0);
3821 
3822   // Check if the argument is a string literal.
3823   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3824     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3825            << Arg->getSourceRange();
3826 
3827   // Check the contents of the string.
3828   StringRef Feature =
3829       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3830   if (!TI.validateCpuIs(Feature))
3831     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3832            << Arg->getSourceRange();
3833   return false;
3834 }
3835 
3836 // Check if the rounding mode is legal.
CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID,CallExpr * TheCall)3837 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3838   // Indicates if this instruction has rounding control or just SAE.
3839   bool HasRC = false;
3840 
3841   unsigned ArgNum = 0;
3842   switch (BuiltinID) {
3843   default:
3844     return false;
3845   case X86::BI__builtin_ia32_vcvttsd2si32:
3846   case X86::BI__builtin_ia32_vcvttsd2si64:
3847   case X86::BI__builtin_ia32_vcvttsd2usi32:
3848   case X86::BI__builtin_ia32_vcvttsd2usi64:
3849   case X86::BI__builtin_ia32_vcvttss2si32:
3850   case X86::BI__builtin_ia32_vcvttss2si64:
3851   case X86::BI__builtin_ia32_vcvttss2usi32:
3852   case X86::BI__builtin_ia32_vcvttss2usi64:
3853     ArgNum = 1;
3854     break;
3855   case X86::BI__builtin_ia32_maxpd512:
3856   case X86::BI__builtin_ia32_maxps512:
3857   case X86::BI__builtin_ia32_minpd512:
3858   case X86::BI__builtin_ia32_minps512:
3859     ArgNum = 2;
3860     break;
3861   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3862   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3863   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3864   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3865   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3866   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3867   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3868   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3869   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3870   case X86::BI__builtin_ia32_exp2pd_mask:
3871   case X86::BI__builtin_ia32_exp2ps_mask:
3872   case X86::BI__builtin_ia32_getexppd512_mask:
3873   case X86::BI__builtin_ia32_getexpps512_mask:
3874   case X86::BI__builtin_ia32_rcp28pd_mask:
3875   case X86::BI__builtin_ia32_rcp28ps_mask:
3876   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3877   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3878   case X86::BI__builtin_ia32_vcomisd:
3879   case X86::BI__builtin_ia32_vcomiss:
3880   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3881     ArgNum = 3;
3882     break;
3883   case X86::BI__builtin_ia32_cmppd512_mask:
3884   case X86::BI__builtin_ia32_cmpps512_mask:
3885   case X86::BI__builtin_ia32_cmpsd_mask:
3886   case X86::BI__builtin_ia32_cmpss_mask:
3887   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3888   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3889   case X86::BI__builtin_ia32_getexpss128_round_mask:
3890   case X86::BI__builtin_ia32_getmantpd512_mask:
3891   case X86::BI__builtin_ia32_getmantps512_mask:
3892   case X86::BI__builtin_ia32_maxsd_round_mask:
3893   case X86::BI__builtin_ia32_maxss_round_mask:
3894   case X86::BI__builtin_ia32_minsd_round_mask:
3895   case X86::BI__builtin_ia32_minss_round_mask:
3896   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3897   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3898   case X86::BI__builtin_ia32_reducepd512_mask:
3899   case X86::BI__builtin_ia32_reduceps512_mask:
3900   case X86::BI__builtin_ia32_rndscalepd_mask:
3901   case X86::BI__builtin_ia32_rndscaleps_mask:
3902   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3903   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3904     ArgNum = 4;
3905     break;
3906   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3907   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3908   case X86::BI__builtin_ia32_fixupimmps512_mask:
3909   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3910   case X86::BI__builtin_ia32_fixupimmsd_mask:
3911   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3912   case X86::BI__builtin_ia32_fixupimmss_mask:
3913   case X86::BI__builtin_ia32_fixupimmss_maskz:
3914   case X86::BI__builtin_ia32_getmantsd_round_mask:
3915   case X86::BI__builtin_ia32_getmantss_round_mask:
3916   case X86::BI__builtin_ia32_rangepd512_mask:
3917   case X86::BI__builtin_ia32_rangeps512_mask:
3918   case X86::BI__builtin_ia32_rangesd128_round_mask:
3919   case X86::BI__builtin_ia32_rangess128_round_mask:
3920   case X86::BI__builtin_ia32_reducesd_mask:
3921   case X86::BI__builtin_ia32_reducess_mask:
3922   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3923   case X86::BI__builtin_ia32_rndscaless_round_mask:
3924     ArgNum = 5;
3925     break;
3926   case X86::BI__builtin_ia32_vcvtsd2si64:
3927   case X86::BI__builtin_ia32_vcvtsd2si32:
3928   case X86::BI__builtin_ia32_vcvtsd2usi32:
3929   case X86::BI__builtin_ia32_vcvtsd2usi64:
3930   case X86::BI__builtin_ia32_vcvtss2si32:
3931   case X86::BI__builtin_ia32_vcvtss2si64:
3932   case X86::BI__builtin_ia32_vcvtss2usi32:
3933   case X86::BI__builtin_ia32_vcvtss2usi64:
3934   case X86::BI__builtin_ia32_sqrtpd512:
3935   case X86::BI__builtin_ia32_sqrtps512:
3936     ArgNum = 1;
3937     HasRC = true;
3938     break;
3939   case X86::BI__builtin_ia32_addpd512:
3940   case X86::BI__builtin_ia32_addps512:
3941   case X86::BI__builtin_ia32_divpd512:
3942   case X86::BI__builtin_ia32_divps512:
3943   case X86::BI__builtin_ia32_mulpd512:
3944   case X86::BI__builtin_ia32_mulps512:
3945   case X86::BI__builtin_ia32_subpd512:
3946   case X86::BI__builtin_ia32_subps512:
3947   case X86::BI__builtin_ia32_cvtsi2sd64:
3948   case X86::BI__builtin_ia32_cvtsi2ss32:
3949   case X86::BI__builtin_ia32_cvtsi2ss64:
3950   case X86::BI__builtin_ia32_cvtusi2sd64:
3951   case X86::BI__builtin_ia32_cvtusi2ss32:
3952   case X86::BI__builtin_ia32_cvtusi2ss64:
3953     ArgNum = 2;
3954     HasRC = true;
3955     break;
3956   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3957   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3958   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3959   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3960   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3961   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3962   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3963   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3964   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3965   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3966   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3967   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3968   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3969   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3970   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3971     ArgNum = 3;
3972     HasRC = true;
3973     break;
3974   case X86::BI__builtin_ia32_addss_round_mask:
3975   case X86::BI__builtin_ia32_addsd_round_mask:
3976   case X86::BI__builtin_ia32_divss_round_mask:
3977   case X86::BI__builtin_ia32_divsd_round_mask:
3978   case X86::BI__builtin_ia32_mulss_round_mask:
3979   case X86::BI__builtin_ia32_mulsd_round_mask:
3980   case X86::BI__builtin_ia32_subss_round_mask:
3981   case X86::BI__builtin_ia32_subsd_round_mask:
3982   case X86::BI__builtin_ia32_scalefpd512_mask:
3983   case X86::BI__builtin_ia32_scalefps512_mask:
3984   case X86::BI__builtin_ia32_scalefsd_round_mask:
3985   case X86::BI__builtin_ia32_scalefss_round_mask:
3986   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3987   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3988   case X86::BI__builtin_ia32_sqrtss_round_mask:
3989   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3990   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3991   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3992   case X86::BI__builtin_ia32_vfmaddss3_mask:
3993   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3994   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3995   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3996   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3997   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3998   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3999   case X86::BI__builtin_ia32_vfmaddps512_mask:
4000   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4001   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4002   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4003   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4004   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4005   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4006   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4007   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4008   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4009   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4010   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4011     ArgNum = 4;
4012     HasRC = true;
4013     break;
4014   }
4015 
4016   llvm::APSInt Result;
4017 
4018   // We can't check the value of a dependent argument.
4019   Expr *Arg = TheCall->getArg(ArgNum);
4020   if (Arg->isTypeDependent() || Arg->isValueDependent())
4021     return false;
4022 
4023   // Check constant-ness first.
4024   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4025     return true;
4026 
4027   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4028   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4029   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4030   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4031   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4032       Result == 8/*ROUND_NO_EXC*/ ||
4033       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4034       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4035     return false;
4036 
4037   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4038          << Arg->getSourceRange();
4039 }
4040 
4041 // Check if the gather/scatter scale is legal.
CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,CallExpr * TheCall)4042 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4043                                              CallExpr *TheCall) {
4044   unsigned ArgNum = 0;
4045   switch (BuiltinID) {
4046   default:
4047     return false;
4048   case X86::BI__builtin_ia32_gatherpfdpd:
4049   case X86::BI__builtin_ia32_gatherpfdps:
4050   case X86::BI__builtin_ia32_gatherpfqpd:
4051   case X86::BI__builtin_ia32_gatherpfqps:
4052   case X86::BI__builtin_ia32_scatterpfdpd:
4053   case X86::BI__builtin_ia32_scatterpfdps:
4054   case X86::BI__builtin_ia32_scatterpfqpd:
4055   case X86::BI__builtin_ia32_scatterpfqps:
4056     ArgNum = 3;
4057     break;
4058   case X86::BI__builtin_ia32_gatherd_pd:
4059   case X86::BI__builtin_ia32_gatherd_pd256:
4060   case X86::BI__builtin_ia32_gatherq_pd:
4061   case X86::BI__builtin_ia32_gatherq_pd256:
4062   case X86::BI__builtin_ia32_gatherd_ps:
4063   case X86::BI__builtin_ia32_gatherd_ps256:
4064   case X86::BI__builtin_ia32_gatherq_ps:
4065   case X86::BI__builtin_ia32_gatherq_ps256:
4066   case X86::BI__builtin_ia32_gatherd_q:
4067   case X86::BI__builtin_ia32_gatherd_q256:
4068   case X86::BI__builtin_ia32_gatherq_q:
4069   case X86::BI__builtin_ia32_gatherq_q256:
4070   case X86::BI__builtin_ia32_gatherd_d:
4071   case X86::BI__builtin_ia32_gatherd_d256:
4072   case X86::BI__builtin_ia32_gatherq_d:
4073   case X86::BI__builtin_ia32_gatherq_d256:
4074   case X86::BI__builtin_ia32_gather3div2df:
4075   case X86::BI__builtin_ia32_gather3div2di:
4076   case X86::BI__builtin_ia32_gather3div4df:
4077   case X86::BI__builtin_ia32_gather3div4di:
4078   case X86::BI__builtin_ia32_gather3div4sf:
4079   case X86::BI__builtin_ia32_gather3div4si:
4080   case X86::BI__builtin_ia32_gather3div8sf:
4081   case X86::BI__builtin_ia32_gather3div8si:
4082   case X86::BI__builtin_ia32_gather3siv2df:
4083   case X86::BI__builtin_ia32_gather3siv2di:
4084   case X86::BI__builtin_ia32_gather3siv4df:
4085   case X86::BI__builtin_ia32_gather3siv4di:
4086   case X86::BI__builtin_ia32_gather3siv4sf:
4087   case X86::BI__builtin_ia32_gather3siv4si:
4088   case X86::BI__builtin_ia32_gather3siv8sf:
4089   case X86::BI__builtin_ia32_gather3siv8si:
4090   case X86::BI__builtin_ia32_gathersiv8df:
4091   case X86::BI__builtin_ia32_gathersiv16sf:
4092   case X86::BI__builtin_ia32_gatherdiv8df:
4093   case X86::BI__builtin_ia32_gatherdiv16sf:
4094   case X86::BI__builtin_ia32_gathersiv8di:
4095   case X86::BI__builtin_ia32_gathersiv16si:
4096   case X86::BI__builtin_ia32_gatherdiv8di:
4097   case X86::BI__builtin_ia32_gatherdiv16si:
4098   case X86::BI__builtin_ia32_scatterdiv2df:
4099   case X86::BI__builtin_ia32_scatterdiv2di:
4100   case X86::BI__builtin_ia32_scatterdiv4df:
4101   case X86::BI__builtin_ia32_scatterdiv4di:
4102   case X86::BI__builtin_ia32_scatterdiv4sf:
4103   case X86::BI__builtin_ia32_scatterdiv4si:
4104   case X86::BI__builtin_ia32_scatterdiv8sf:
4105   case X86::BI__builtin_ia32_scatterdiv8si:
4106   case X86::BI__builtin_ia32_scattersiv2df:
4107   case X86::BI__builtin_ia32_scattersiv2di:
4108   case X86::BI__builtin_ia32_scattersiv4df:
4109   case X86::BI__builtin_ia32_scattersiv4di:
4110   case X86::BI__builtin_ia32_scattersiv4sf:
4111   case X86::BI__builtin_ia32_scattersiv4si:
4112   case X86::BI__builtin_ia32_scattersiv8sf:
4113   case X86::BI__builtin_ia32_scattersiv8si:
4114   case X86::BI__builtin_ia32_scattersiv8df:
4115   case X86::BI__builtin_ia32_scattersiv16sf:
4116   case X86::BI__builtin_ia32_scatterdiv8df:
4117   case X86::BI__builtin_ia32_scatterdiv16sf:
4118   case X86::BI__builtin_ia32_scattersiv8di:
4119   case X86::BI__builtin_ia32_scattersiv16si:
4120   case X86::BI__builtin_ia32_scatterdiv8di:
4121   case X86::BI__builtin_ia32_scatterdiv16si:
4122     ArgNum = 4;
4123     break;
4124   }
4125 
4126   llvm::APSInt Result;
4127 
4128   // We can't check the value of a dependent argument.
4129   Expr *Arg = TheCall->getArg(ArgNum);
4130   if (Arg->isTypeDependent() || Arg->isValueDependent())
4131     return false;
4132 
4133   // Check constant-ness first.
4134   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4135     return true;
4136 
4137   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4138     return false;
4139 
4140   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4141          << Arg->getSourceRange();
4142 }
4143 
4144 enum { TileRegLow = 0, TileRegHigh = 7 };
4145 
CheckX86BuiltinTileArgumentsRange(CallExpr * TheCall,ArrayRef<int> ArgNums)4146 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4147                                              ArrayRef<int> ArgNums) {
4148   for (int ArgNum : ArgNums) {
4149     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4150       return true;
4151   }
4152   return false;
4153 }
4154 
CheckX86BuiltinTileDuplicate(CallExpr * TheCall,ArrayRef<int> ArgNums)4155 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4156                                         ArrayRef<int> ArgNums) {
4157   // Because the max number of tile register is TileRegHigh + 1, so here we use
4158   // each bit to represent the usage of them in bitset.
4159   std::bitset<TileRegHigh + 1> ArgValues;
4160   for (int ArgNum : ArgNums) {
4161     Expr *Arg = TheCall->getArg(ArgNum);
4162     if (Arg->isTypeDependent() || Arg->isValueDependent())
4163       continue;
4164 
4165     llvm::APSInt Result;
4166     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4167       return true;
4168     int ArgExtValue = Result.getExtValue();
4169     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4170            "Incorrect tile register num.");
4171     if (ArgValues.test(ArgExtValue))
4172       return Diag(TheCall->getBeginLoc(),
4173                   diag::err_x86_builtin_tile_arg_duplicate)
4174              << TheCall->getArg(ArgNum)->getSourceRange();
4175     ArgValues.set(ArgExtValue);
4176   }
4177   return false;
4178 }
4179 
CheckX86BuiltinTileRangeAndDuplicate(CallExpr * TheCall,ArrayRef<int> ArgNums)4180 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4181                                                 ArrayRef<int> ArgNums) {
4182   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4183          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4184 }
4185 
CheckX86BuiltinTileArguments(unsigned BuiltinID,CallExpr * TheCall)4186 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4187   switch (BuiltinID) {
4188   default:
4189     return false;
4190   case X86::BI__builtin_ia32_tileloadd64:
4191   case X86::BI__builtin_ia32_tileloaddt164:
4192   case X86::BI__builtin_ia32_tilestored64:
4193   case X86::BI__builtin_ia32_tilezero:
4194     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4195   case X86::BI__builtin_ia32_tdpbssd:
4196   case X86::BI__builtin_ia32_tdpbsud:
4197   case X86::BI__builtin_ia32_tdpbusd:
4198   case X86::BI__builtin_ia32_tdpbuud:
4199   case X86::BI__builtin_ia32_tdpbf16ps:
4200     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4201   }
4202 }
isX86_32Builtin(unsigned BuiltinID)4203 static bool isX86_32Builtin(unsigned BuiltinID) {
4204   // These builtins only work on x86-32 targets.
4205   switch (BuiltinID) {
4206   case X86::BI__builtin_ia32_readeflags_u32:
4207   case X86::BI__builtin_ia32_writeeflags_u32:
4208     return true;
4209   }
4210 
4211   return false;
4212 }
4213 
CheckX86BuiltinFunctionCall(const TargetInfo & TI,unsigned BuiltinID,CallExpr * TheCall)4214 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4215                                        CallExpr *TheCall) {
4216   if (BuiltinID == X86::BI__builtin_cpu_supports)
4217     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4218 
4219   if (BuiltinID == X86::BI__builtin_cpu_is)
4220     return SemaBuiltinCpuIs(*this, TI, TheCall);
4221 
4222   // Check for 32-bit only builtins on a 64-bit target.
4223   const llvm::Triple &TT = TI.getTriple();
4224   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4225     return Diag(TheCall->getCallee()->getBeginLoc(),
4226                 diag::err_32_bit_builtin_64_bit_tgt);
4227 
4228   // If the intrinsic has rounding or SAE make sure its valid.
4229   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4230     return true;
4231 
4232   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4233   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4234     return true;
4235 
4236   // If the intrinsic has a tile arguments, make sure they are valid.
4237   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4238     return true;
4239 
4240   // For intrinsics which take an immediate value as part of the instruction,
4241   // range check them here.
4242   int i = 0, l = 0, u = 0;
4243   switch (BuiltinID) {
4244   default:
4245     return false;
4246   case X86::BI__builtin_ia32_vec_ext_v2si:
4247   case X86::BI__builtin_ia32_vec_ext_v2di:
4248   case X86::BI__builtin_ia32_vextractf128_pd256:
4249   case X86::BI__builtin_ia32_vextractf128_ps256:
4250   case X86::BI__builtin_ia32_vextractf128_si256:
4251   case X86::BI__builtin_ia32_extract128i256:
4252   case X86::BI__builtin_ia32_extractf64x4_mask:
4253   case X86::BI__builtin_ia32_extracti64x4_mask:
4254   case X86::BI__builtin_ia32_extractf32x8_mask:
4255   case X86::BI__builtin_ia32_extracti32x8_mask:
4256   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4257   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4258   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4259   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4260     i = 1; l = 0; u = 1;
4261     break;
4262   case X86::BI__builtin_ia32_vec_set_v2di:
4263   case X86::BI__builtin_ia32_vinsertf128_pd256:
4264   case X86::BI__builtin_ia32_vinsertf128_ps256:
4265   case X86::BI__builtin_ia32_vinsertf128_si256:
4266   case X86::BI__builtin_ia32_insert128i256:
4267   case X86::BI__builtin_ia32_insertf32x8:
4268   case X86::BI__builtin_ia32_inserti32x8:
4269   case X86::BI__builtin_ia32_insertf64x4:
4270   case X86::BI__builtin_ia32_inserti64x4:
4271   case X86::BI__builtin_ia32_insertf64x2_256:
4272   case X86::BI__builtin_ia32_inserti64x2_256:
4273   case X86::BI__builtin_ia32_insertf32x4_256:
4274   case X86::BI__builtin_ia32_inserti32x4_256:
4275     i = 2; l = 0; u = 1;
4276     break;
4277   case X86::BI__builtin_ia32_vpermilpd:
4278   case X86::BI__builtin_ia32_vec_ext_v4hi:
4279   case X86::BI__builtin_ia32_vec_ext_v4si:
4280   case X86::BI__builtin_ia32_vec_ext_v4sf:
4281   case X86::BI__builtin_ia32_vec_ext_v4di:
4282   case X86::BI__builtin_ia32_extractf32x4_mask:
4283   case X86::BI__builtin_ia32_extracti32x4_mask:
4284   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4285   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4286     i = 1; l = 0; u = 3;
4287     break;
4288   case X86::BI_mm_prefetch:
4289   case X86::BI__builtin_ia32_vec_ext_v8hi:
4290   case X86::BI__builtin_ia32_vec_ext_v8si:
4291     i = 1; l = 0; u = 7;
4292     break;
4293   case X86::BI__builtin_ia32_sha1rnds4:
4294   case X86::BI__builtin_ia32_blendpd:
4295   case X86::BI__builtin_ia32_shufpd:
4296   case X86::BI__builtin_ia32_vec_set_v4hi:
4297   case X86::BI__builtin_ia32_vec_set_v4si:
4298   case X86::BI__builtin_ia32_vec_set_v4di:
4299   case X86::BI__builtin_ia32_shuf_f32x4_256:
4300   case X86::BI__builtin_ia32_shuf_f64x2_256:
4301   case X86::BI__builtin_ia32_shuf_i32x4_256:
4302   case X86::BI__builtin_ia32_shuf_i64x2_256:
4303   case X86::BI__builtin_ia32_insertf64x2_512:
4304   case X86::BI__builtin_ia32_inserti64x2_512:
4305   case X86::BI__builtin_ia32_insertf32x4:
4306   case X86::BI__builtin_ia32_inserti32x4:
4307     i = 2; l = 0; u = 3;
4308     break;
4309   case X86::BI__builtin_ia32_vpermil2pd:
4310   case X86::BI__builtin_ia32_vpermil2pd256:
4311   case X86::BI__builtin_ia32_vpermil2ps:
4312   case X86::BI__builtin_ia32_vpermil2ps256:
4313     i = 3; l = 0; u = 3;
4314     break;
4315   case X86::BI__builtin_ia32_cmpb128_mask:
4316   case X86::BI__builtin_ia32_cmpw128_mask:
4317   case X86::BI__builtin_ia32_cmpd128_mask:
4318   case X86::BI__builtin_ia32_cmpq128_mask:
4319   case X86::BI__builtin_ia32_cmpb256_mask:
4320   case X86::BI__builtin_ia32_cmpw256_mask:
4321   case X86::BI__builtin_ia32_cmpd256_mask:
4322   case X86::BI__builtin_ia32_cmpq256_mask:
4323   case X86::BI__builtin_ia32_cmpb512_mask:
4324   case X86::BI__builtin_ia32_cmpw512_mask:
4325   case X86::BI__builtin_ia32_cmpd512_mask:
4326   case X86::BI__builtin_ia32_cmpq512_mask:
4327   case X86::BI__builtin_ia32_ucmpb128_mask:
4328   case X86::BI__builtin_ia32_ucmpw128_mask:
4329   case X86::BI__builtin_ia32_ucmpd128_mask:
4330   case X86::BI__builtin_ia32_ucmpq128_mask:
4331   case X86::BI__builtin_ia32_ucmpb256_mask:
4332   case X86::BI__builtin_ia32_ucmpw256_mask:
4333   case X86::BI__builtin_ia32_ucmpd256_mask:
4334   case X86::BI__builtin_ia32_ucmpq256_mask:
4335   case X86::BI__builtin_ia32_ucmpb512_mask:
4336   case X86::BI__builtin_ia32_ucmpw512_mask:
4337   case X86::BI__builtin_ia32_ucmpd512_mask:
4338   case X86::BI__builtin_ia32_ucmpq512_mask:
4339   case X86::BI__builtin_ia32_vpcomub:
4340   case X86::BI__builtin_ia32_vpcomuw:
4341   case X86::BI__builtin_ia32_vpcomud:
4342   case X86::BI__builtin_ia32_vpcomuq:
4343   case X86::BI__builtin_ia32_vpcomb:
4344   case X86::BI__builtin_ia32_vpcomw:
4345   case X86::BI__builtin_ia32_vpcomd:
4346   case X86::BI__builtin_ia32_vpcomq:
4347   case X86::BI__builtin_ia32_vec_set_v8hi:
4348   case X86::BI__builtin_ia32_vec_set_v8si:
4349     i = 2; l = 0; u = 7;
4350     break;
4351   case X86::BI__builtin_ia32_vpermilpd256:
4352   case X86::BI__builtin_ia32_roundps:
4353   case X86::BI__builtin_ia32_roundpd:
4354   case X86::BI__builtin_ia32_roundps256:
4355   case X86::BI__builtin_ia32_roundpd256:
4356   case X86::BI__builtin_ia32_getmantpd128_mask:
4357   case X86::BI__builtin_ia32_getmantpd256_mask:
4358   case X86::BI__builtin_ia32_getmantps128_mask:
4359   case X86::BI__builtin_ia32_getmantps256_mask:
4360   case X86::BI__builtin_ia32_getmantpd512_mask:
4361   case X86::BI__builtin_ia32_getmantps512_mask:
4362   case X86::BI__builtin_ia32_vec_ext_v16qi:
4363   case X86::BI__builtin_ia32_vec_ext_v16hi:
4364     i = 1; l = 0; u = 15;
4365     break;
4366   case X86::BI__builtin_ia32_pblendd128:
4367   case X86::BI__builtin_ia32_blendps:
4368   case X86::BI__builtin_ia32_blendpd256:
4369   case X86::BI__builtin_ia32_shufpd256:
4370   case X86::BI__builtin_ia32_roundss:
4371   case X86::BI__builtin_ia32_roundsd:
4372   case X86::BI__builtin_ia32_rangepd128_mask:
4373   case X86::BI__builtin_ia32_rangepd256_mask:
4374   case X86::BI__builtin_ia32_rangepd512_mask:
4375   case X86::BI__builtin_ia32_rangeps128_mask:
4376   case X86::BI__builtin_ia32_rangeps256_mask:
4377   case X86::BI__builtin_ia32_rangeps512_mask:
4378   case X86::BI__builtin_ia32_getmantsd_round_mask:
4379   case X86::BI__builtin_ia32_getmantss_round_mask:
4380   case X86::BI__builtin_ia32_vec_set_v16qi:
4381   case X86::BI__builtin_ia32_vec_set_v16hi:
4382     i = 2; l = 0; u = 15;
4383     break;
4384   case X86::BI__builtin_ia32_vec_ext_v32qi:
4385     i = 1; l = 0; u = 31;
4386     break;
4387   case X86::BI__builtin_ia32_cmpps:
4388   case X86::BI__builtin_ia32_cmpss:
4389   case X86::BI__builtin_ia32_cmppd:
4390   case X86::BI__builtin_ia32_cmpsd:
4391   case X86::BI__builtin_ia32_cmpps256:
4392   case X86::BI__builtin_ia32_cmppd256:
4393   case X86::BI__builtin_ia32_cmpps128_mask:
4394   case X86::BI__builtin_ia32_cmppd128_mask:
4395   case X86::BI__builtin_ia32_cmpps256_mask:
4396   case X86::BI__builtin_ia32_cmppd256_mask:
4397   case X86::BI__builtin_ia32_cmpps512_mask:
4398   case X86::BI__builtin_ia32_cmppd512_mask:
4399   case X86::BI__builtin_ia32_cmpsd_mask:
4400   case X86::BI__builtin_ia32_cmpss_mask:
4401   case X86::BI__builtin_ia32_vec_set_v32qi:
4402     i = 2; l = 0; u = 31;
4403     break;
4404   case X86::BI__builtin_ia32_permdf256:
4405   case X86::BI__builtin_ia32_permdi256:
4406   case X86::BI__builtin_ia32_permdf512:
4407   case X86::BI__builtin_ia32_permdi512:
4408   case X86::BI__builtin_ia32_vpermilps:
4409   case X86::BI__builtin_ia32_vpermilps256:
4410   case X86::BI__builtin_ia32_vpermilpd512:
4411   case X86::BI__builtin_ia32_vpermilps512:
4412   case X86::BI__builtin_ia32_pshufd:
4413   case X86::BI__builtin_ia32_pshufd256:
4414   case X86::BI__builtin_ia32_pshufd512:
4415   case X86::BI__builtin_ia32_pshufhw:
4416   case X86::BI__builtin_ia32_pshufhw256:
4417   case X86::BI__builtin_ia32_pshufhw512:
4418   case X86::BI__builtin_ia32_pshuflw:
4419   case X86::BI__builtin_ia32_pshuflw256:
4420   case X86::BI__builtin_ia32_pshuflw512:
4421   case X86::BI__builtin_ia32_vcvtps2ph:
4422   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4423   case X86::BI__builtin_ia32_vcvtps2ph256:
4424   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4425   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4426   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4427   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4428   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4429   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4430   case X86::BI__builtin_ia32_rndscaleps_mask:
4431   case X86::BI__builtin_ia32_rndscalepd_mask:
4432   case X86::BI__builtin_ia32_reducepd128_mask:
4433   case X86::BI__builtin_ia32_reducepd256_mask:
4434   case X86::BI__builtin_ia32_reducepd512_mask:
4435   case X86::BI__builtin_ia32_reduceps128_mask:
4436   case X86::BI__builtin_ia32_reduceps256_mask:
4437   case X86::BI__builtin_ia32_reduceps512_mask:
4438   case X86::BI__builtin_ia32_prold512:
4439   case X86::BI__builtin_ia32_prolq512:
4440   case X86::BI__builtin_ia32_prold128:
4441   case X86::BI__builtin_ia32_prold256:
4442   case X86::BI__builtin_ia32_prolq128:
4443   case X86::BI__builtin_ia32_prolq256:
4444   case X86::BI__builtin_ia32_prord512:
4445   case X86::BI__builtin_ia32_prorq512:
4446   case X86::BI__builtin_ia32_prord128:
4447   case X86::BI__builtin_ia32_prord256:
4448   case X86::BI__builtin_ia32_prorq128:
4449   case X86::BI__builtin_ia32_prorq256:
4450   case X86::BI__builtin_ia32_fpclasspd128_mask:
4451   case X86::BI__builtin_ia32_fpclasspd256_mask:
4452   case X86::BI__builtin_ia32_fpclassps128_mask:
4453   case X86::BI__builtin_ia32_fpclassps256_mask:
4454   case X86::BI__builtin_ia32_fpclassps512_mask:
4455   case X86::BI__builtin_ia32_fpclasspd512_mask:
4456   case X86::BI__builtin_ia32_fpclasssd_mask:
4457   case X86::BI__builtin_ia32_fpclassss_mask:
4458   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4459   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4460   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4461   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4462   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4463   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4464   case X86::BI__builtin_ia32_kshiftliqi:
4465   case X86::BI__builtin_ia32_kshiftlihi:
4466   case X86::BI__builtin_ia32_kshiftlisi:
4467   case X86::BI__builtin_ia32_kshiftlidi:
4468   case X86::BI__builtin_ia32_kshiftriqi:
4469   case X86::BI__builtin_ia32_kshiftrihi:
4470   case X86::BI__builtin_ia32_kshiftrisi:
4471   case X86::BI__builtin_ia32_kshiftridi:
4472     i = 1; l = 0; u = 255;
4473     break;
4474   case X86::BI__builtin_ia32_vperm2f128_pd256:
4475   case X86::BI__builtin_ia32_vperm2f128_ps256:
4476   case X86::BI__builtin_ia32_vperm2f128_si256:
4477   case X86::BI__builtin_ia32_permti256:
4478   case X86::BI__builtin_ia32_pblendw128:
4479   case X86::BI__builtin_ia32_pblendw256:
4480   case X86::BI__builtin_ia32_blendps256:
4481   case X86::BI__builtin_ia32_pblendd256:
4482   case X86::BI__builtin_ia32_palignr128:
4483   case X86::BI__builtin_ia32_palignr256:
4484   case X86::BI__builtin_ia32_palignr512:
4485   case X86::BI__builtin_ia32_alignq512:
4486   case X86::BI__builtin_ia32_alignd512:
4487   case X86::BI__builtin_ia32_alignd128:
4488   case X86::BI__builtin_ia32_alignd256:
4489   case X86::BI__builtin_ia32_alignq128:
4490   case X86::BI__builtin_ia32_alignq256:
4491   case X86::BI__builtin_ia32_vcomisd:
4492   case X86::BI__builtin_ia32_vcomiss:
4493   case X86::BI__builtin_ia32_shuf_f32x4:
4494   case X86::BI__builtin_ia32_shuf_f64x2:
4495   case X86::BI__builtin_ia32_shuf_i32x4:
4496   case X86::BI__builtin_ia32_shuf_i64x2:
4497   case X86::BI__builtin_ia32_shufpd512:
4498   case X86::BI__builtin_ia32_shufps:
4499   case X86::BI__builtin_ia32_shufps256:
4500   case X86::BI__builtin_ia32_shufps512:
4501   case X86::BI__builtin_ia32_dbpsadbw128:
4502   case X86::BI__builtin_ia32_dbpsadbw256:
4503   case X86::BI__builtin_ia32_dbpsadbw512:
4504   case X86::BI__builtin_ia32_vpshldd128:
4505   case X86::BI__builtin_ia32_vpshldd256:
4506   case X86::BI__builtin_ia32_vpshldd512:
4507   case X86::BI__builtin_ia32_vpshldq128:
4508   case X86::BI__builtin_ia32_vpshldq256:
4509   case X86::BI__builtin_ia32_vpshldq512:
4510   case X86::BI__builtin_ia32_vpshldw128:
4511   case X86::BI__builtin_ia32_vpshldw256:
4512   case X86::BI__builtin_ia32_vpshldw512:
4513   case X86::BI__builtin_ia32_vpshrdd128:
4514   case X86::BI__builtin_ia32_vpshrdd256:
4515   case X86::BI__builtin_ia32_vpshrdd512:
4516   case X86::BI__builtin_ia32_vpshrdq128:
4517   case X86::BI__builtin_ia32_vpshrdq256:
4518   case X86::BI__builtin_ia32_vpshrdq512:
4519   case X86::BI__builtin_ia32_vpshrdw128:
4520   case X86::BI__builtin_ia32_vpshrdw256:
4521   case X86::BI__builtin_ia32_vpshrdw512:
4522     i = 2; l = 0; u = 255;
4523     break;
4524   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4525   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4526   case X86::BI__builtin_ia32_fixupimmps512_mask:
4527   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4528   case X86::BI__builtin_ia32_fixupimmsd_mask:
4529   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4530   case X86::BI__builtin_ia32_fixupimmss_mask:
4531   case X86::BI__builtin_ia32_fixupimmss_maskz:
4532   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4533   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4534   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4535   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4536   case X86::BI__builtin_ia32_fixupimmps128_mask:
4537   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4538   case X86::BI__builtin_ia32_fixupimmps256_mask:
4539   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4540   case X86::BI__builtin_ia32_pternlogd512_mask:
4541   case X86::BI__builtin_ia32_pternlogd512_maskz:
4542   case X86::BI__builtin_ia32_pternlogq512_mask:
4543   case X86::BI__builtin_ia32_pternlogq512_maskz:
4544   case X86::BI__builtin_ia32_pternlogd128_mask:
4545   case X86::BI__builtin_ia32_pternlogd128_maskz:
4546   case X86::BI__builtin_ia32_pternlogd256_mask:
4547   case X86::BI__builtin_ia32_pternlogd256_maskz:
4548   case X86::BI__builtin_ia32_pternlogq128_mask:
4549   case X86::BI__builtin_ia32_pternlogq128_maskz:
4550   case X86::BI__builtin_ia32_pternlogq256_mask:
4551   case X86::BI__builtin_ia32_pternlogq256_maskz:
4552     i = 3; l = 0; u = 255;
4553     break;
4554   case X86::BI__builtin_ia32_gatherpfdpd:
4555   case X86::BI__builtin_ia32_gatherpfdps:
4556   case X86::BI__builtin_ia32_gatherpfqpd:
4557   case X86::BI__builtin_ia32_gatherpfqps:
4558   case X86::BI__builtin_ia32_scatterpfdpd:
4559   case X86::BI__builtin_ia32_scatterpfdps:
4560   case X86::BI__builtin_ia32_scatterpfqpd:
4561   case X86::BI__builtin_ia32_scatterpfqps:
4562     i = 4; l = 2; u = 3;
4563     break;
4564   case X86::BI__builtin_ia32_reducesd_mask:
4565   case X86::BI__builtin_ia32_reducess_mask:
4566   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4567   case X86::BI__builtin_ia32_rndscaless_round_mask:
4568     i = 4; l = 0; u = 255;
4569     break;
4570   }
4571 
4572   // Note that we don't force a hard error on the range check here, allowing
4573   // template-generated or macro-generated dead code to potentially have out-of-
4574   // range values. These need to code generate, but don't need to necessarily
4575   // make any sense. We use a warning that defaults to an error.
4576   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4577 }
4578 
4579 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4580 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4581 /// Returns true when the format fits the function and the FormatStringInfo has
4582 /// been populated.
getFormatStringInfo(const FormatAttr * Format,bool IsCXXMember,FormatStringInfo * FSI)4583 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4584                                FormatStringInfo *FSI) {
4585   FSI->HasVAListArg = Format->getFirstArg() == 0;
4586   FSI->FormatIdx = Format->getFormatIdx() - 1;
4587   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4588 
4589   // The way the format attribute works in GCC, the implicit this argument
4590   // of member functions is counted. However, it doesn't appear in our own
4591   // lists, so decrement format_idx in that case.
4592   if (IsCXXMember) {
4593     if(FSI->FormatIdx == 0)
4594       return false;
4595     --FSI->FormatIdx;
4596     if (FSI->FirstDataArg != 0)
4597       --FSI->FirstDataArg;
4598   }
4599   return true;
4600 }
4601 
4602 /// Checks if a the given expression evaluates to null.
4603 ///
4604 /// Returns true if the value evaluates to null.
CheckNonNullExpr(Sema & S,const Expr * Expr)4605 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4606   // If the expression has non-null type, it doesn't evaluate to null.
4607   if (auto nullability
4608         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4609     if (*nullability == NullabilityKind::NonNull)
4610       return false;
4611   }
4612 
4613   // As a special case, transparent unions initialized with zero are
4614   // considered null for the purposes of the nonnull attribute.
4615   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4616     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4617       if (const CompoundLiteralExpr *CLE =
4618           dyn_cast<CompoundLiteralExpr>(Expr))
4619         if (const InitListExpr *ILE =
4620             dyn_cast<InitListExpr>(CLE->getInitializer()))
4621           Expr = ILE->getInit(0);
4622   }
4623 
4624   bool Result;
4625   return (!Expr->isValueDependent() &&
4626           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4627           !Result);
4628 }
4629 
CheckNonNullArgument(Sema & S,const Expr * ArgExpr,SourceLocation CallSiteLoc)4630 static void CheckNonNullArgument(Sema &S,
4631                                  const Expr *ArgExpr,
4632                                  SourceLocation CallSiteLoc) {
4633   if (CheckNonNullExpr(S, ArgExpr))
4634     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4635                           S.PDiag(diag::warn_null_arg)
4636                               << ArgExpr->getSourceRange());
4637 }
4638 
GetFormatNSStringIdx(const FormatAttr * Format,unsigned & Idx)4639 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4640   FormatStringInfo FSI;
4641   if ((GetFormatStringType(Format) == FST_NSString) &&
4642       getFormatStringInfo(Format, false, &FSI)) {
4643     Idx = FSI.FormatIdx;
4644     return true;
4645   }
4646   return false;
4647 }
4648 
4649 /// Diagnose use of %s directive in an NSString which is being passed
4650 /// as formatting string to formatting method.
4651 static void
DiagnoseCStringFormatDirectiveInCFAPI(Sema & S,const NamedDecl * FDecl,Expr ** Args,unsigned NumArgs)4652 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4653                                         const NamedDecl *FDecl,
4654                                         Expr **Args,
4655                                         unsigned NumArgs) {
4656   unsigned Idx = 0;
4657   bool Format = false;
4658   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4659   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4660     Idx = 2;
4661     Format = true;
4662   }
4663   else
4664     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4665       if (S.GetFormatNSStringIdx(I, Idx)) {
4666         Format = true;
4667         break;
4668       }
4669     }
4670   if (!Format || NumArgs <= Idx)
4671     return;
4672   const Expr *FormatExpr = Args[Idx];
4673   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4674     FormatExpr = CSCE->getSubExpr();
4675   const StringLiteral *FormatString;
4676   if (const ObjCStringLiteral *OSL =
4677       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4678     FormatString = OSL->getString();
4679   else
4680     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4681   if (!FormatString)
4682     return;
4683   if (S.FormatStringHasSArg(FormatString)) {
4684     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4685       << "%s" << 1 << 1;
4686     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4687       << FDecl->getDeclName();
4688   }
4689 }
4690 
4691 /// Determine whether the given type has a non-null nullability annotation.
isNonNullType(ASTContext & ctx,QualType type)4692 static bool isNonNullType(ASTContext &ctx, QualType type) {
4693   if (auto nullability = type->getNullability(ctx))
4694     return *nullability == NullabilityKind::NonNull;
4695 
4696   return false;
4697 }
4698 
CheckNonNullArguments(Sema & S,const NamedDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<const Expr * > Args,SourceLocation CallSiteLoc)4699 static void CheckNonNullArguments(Sema &S,
4700                                   const NamedDecl *FDecl,
4701                                   const FunctionProtoType *Proto,
4702                                   ArrayRef<const Expr *> Args,
4703                                   SourceLocation CallSiteLoc) {
4704   assert((FDecl || Proto) && "Need a function declaration or prototype");
4705 
4706   // Already checked by by constant evaluator.
4707   if (S.isConstantEvaluated())
4708     return;
4709   // Check the attributes attached to the method/function itself.
4710   llvm::SmallBitVector NonNullArgs;
4711   if (FDecl) {
4712     // Handle the nonnull attribute on the function/method declaration itself.
4713     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4714       if (!NonNull->args_size()) {
4715         // Easy case: all pointer arguments are nonnull.
4716         for (const auto *Arg : Args)
4717           if (S.isValidPointerAttrType(Arg->getType()))
4718             CheckNonNullArgument(S, Arg, CallSiteLoc);
4719         return;
4720       }
4721 
4722       for (const ParamIdx &Idx : NonNull->args()) {
4723         unsigned IdxAST = Idx.getASTIndex();
4724         if (IdxAST >= Args.size())
4725           continue;
4726         if (NonNullArgs.empty())
4727           NonNullArgs.resize(Args.size());
4728         NonNullArgs.set(IdxAST);
4729       }
4730     }
4731   }
4732 
4733   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4734     // Handle the nonnull attribute on the parameters of the
4735     // function/method.
4736     ArrayRef<ParmVarDecl*> parms;
4737     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4738       parms = FD->parameters();
4739     else
4740       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4741 
4742     unsigned ParamIndex = 0;
4743     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4744          I != E; ++I, ++ParamIndex) {
4745       const ParmVarDecl *PVD = *I;
4746       if (PVD->hasAttr<NonNullAttr>() ||
4747           isNonNullType(S.Context, PVD->getType())) {
4748         if (NonNullArgs.empty())
4749           NonNullArgs.resize(Args.size());
4750 
4751         NonNullArgs.set(ParamIndex);
4752       }
4753     }
4754   } else {
4755     // If we have a non-function, non-method declaration but no
4756     // function prototype, try to dig out the function prototype.
4757     if (!Proto) {
4758       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4759         QualType type = VD->getType().getNonReferenceType();
4760         if (auto pointerType = type->getAs<PointerType>())
4761           type = pointerType->getPointeeType();
4762         else if (auto blockType = type->getAs<BlockPointerType>())
4763           type = blockType->getPointeeType();
4764         // FIXME: data member pointers?
4765 
4766         // Dig out the function prototype, if there is one.
4767         Proto = type->getAs<FunctionProtoType>();
4768       }
4769     }
4770 
4771     // Fill in non-null argument information from the nullability
4772     // information on the parameter types (if we have them).
4773     if (Proto) {
4774       unsigned Index = 0;
4775       for (auto paramType : Proto->getParamTypes()) {
4776         if (isNonNullType(S.Context, paramType)) {
4777           if (NonNullArgs.empty())
4778             NonNullArgs.resize(Args.size());
4779 
4780           NonNullArgs.set(Index);
4781         }
4782 
4783         ++Index;
4784       }
4785     }
4786   }
4787 
4788   // Check for non-null arguments.
4789   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4790        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4791     if (NonNullArgs[ArgIndex])
4792       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4793   }
4794 }
4795 
4796 /// Warn if a pointer or reference argument passed to a function points to an
4797 /// object that is less aligned than the parameter. This can happen when
4798 /// creating a typedef with a lower alignment than the original type and then
4799 /// calling functions defined in terms of the original type.
CheckArgAlignment(SourceLocation Loc,NamedDecl * FDecl,StringRef ParamName,QualType ArgTy,QualType ParamTy)4800 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4801                              StringRef ParamName, QualType ArgTy,
4802                              QualType ParamTy) {
4803 
4804   // If a function accepts a pointer or reference type
4805   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4806     return;
4807 
4808   // If the parameter is a pointer type, get the pointee type for the
4809   // argument too. If the parameter is a reference type, don't try to get
4810   // the pointee type for the argument.
4811   if (ParamTy->isPointerType())
4812     ArgTy = ArgTy->getPointeeType();
4813 
4814   // Remove reference or pointer
4815   ParamTy = ParamTy->getPointeeType();
4816 
4817   // Find expected alignment, and the actual alignment of the passed object.
4818   // getTypeAlignInChars requires complete types
4819   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4820       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4821       ArgTy->isUndeducedType())
4822     return;
4823 
4824   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4825   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4826 
4827   // If the argument is less aligned than the parameter, there is a
4828   // potential alignment issue.
4829   if (ArgAlign < ParamAlign)
4830     Diag(Loc, diag::warn_param_mismatched_alignment)
4831         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4832         << ParamName << FDecl;
4833 }
4834 
4835 /// Handles the checks for format strings, non-POD arguments to vararg
4836 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4837 /// attributes.
checkCall(NamedDecl * FDecl,const FunctionProtoType * Proto,const Expr * ThisArg,ArrayRef<const Expr * > Args,bool IsMemberFunction,SourceLocation Loc,SourceRange Range,VariadicCallType CallType)4838 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4839                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4840                      bool IsMemberFunction, SourceLocation Loc,
4841                      SourceRange Range, VariadicCallType CallType) {
4842   // FIXME: We should check as much as we can in the template definition.
4843   if (CurContext->isDependentContext())
4844     return;
4845 
4846   // Printf and scanf checking.
4847   llvm::SmallBitVector CheckedVarArgs;
4848   if (FDecl) {
4849     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4850       // Only create vector if there are format attributes.
4851       CheckedVarArgs.resize(Args.size());
4852 
4853       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4854                            CheckedVarArgs);
4855     }
4856   }
4857 
4858   // Refuse POD arguments that weren't caught by the format string
4859   // checks above.
4860   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4861   if (CallType != VariadicDoesNotApply &&
4862       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4863     unsigned NumParams = Proto ? Proto->getNumParams()
4864                        : FDecl && isa<FunctionDecl>(FDecl)
4865                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4866                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4867                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4868                        : 0;
4869 
4870     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4871       // Args[ArgIdx] can be null in malformed code.
4872       if (const Expr *Arg = Args[ArgIdx]) {
4873         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4874           checkVariadicArgument(Arg, CallType);
4875       }
4876     }
4877   }
4878 
4879   if (FDecl || Proto) {
4880     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4881 
4882     // Type safety checking.
4883     if (FDecl) {
4884       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4885         CheckArgumentWithTypeTag(I, Args, Loc);
4886     }
4887   }
4888 
4889   // Check that passed arguments match the alignment of original arguments.
4890   // Try to get the missing prototype from the declaration.
4891   if (!Proto && FDecl) {
4892     const auto *FT = FDecl->getFunctionType();
4893     if (isa_and_nonnull<FunctionProtoType>(FT))
4894       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4895   }
4896   if (Proto) {
4897     // For variadic functions, we may have more args than parameters.
4898     // For some K&R functions, we may have less args than parameters.
4899     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4900     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4901       // Args[ArgIdx] can be null in malformed code.
4902       if (const Expr *Arg = Args[ArgIdx]) {
4903         if (Arg->containsErrors())
4904           continue;
4905 
4906         QualType ParamTy = Proto->getParamType(ArgIdx);
4907         QualType ArgTy = Arg->getType();
4908         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4909                           ArgTy, ParamTy);
4910       }
4911     }
4912   }
4913 
4914   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4915     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4916     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4917     if (!Arg->isValueDependent()) {
4918       Expr::EvalResult Align;
4919       if (Arg->EvaluateAsInt(Align, Context)) {
4920         const llvm::APSInt &I = Align.Val.getInt();
4921         if (!I.isPowerOf2())
4922           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4923               << Arg->getSourceRange();
4924 
4925         if (I > Sema::MaximumAlignment)
4926           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4927               << Arg->getSourceRange() << Sema::MaximumAlignment;
4928       }
4929     }
4930   }
4931 
4932   if (FD)
4933     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4934 }
4935 
4936 /// CheckConstructorCall - Check a constructor call for correctness and safety
4937 /// properties not enforced by the C type system.
CheckConstructorCall(FunctionDecl * FDecl,QualType ThisType,ArrayRef<const Expr * > Args,const FunctionProtoType * Proto,SourceLocation Loc)4938 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4939                                 ArrayRef<const Expr *> Args,
4940                                 const FunctionProtoType *Proto,
4941                                 SourceLocation Loc) {
4942   VariadicCallType CallType =
4943       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4944 
4945   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4946   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4947                     Context.getPointerType(Ctor->getThisObjectType()));
4948 
4949   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4950             Loc, SourceRange(), CallType);
4951 }
4952 
4953 /// CheckFunctionCall - Check a direct function call for various correctness
4954 /// and safety properties not strictly enforced by the C type system.
CheckFunctionCall(FunctionDecl * FDecl,CallExpr * TheCall,const FunctionProtoType * Proto)4955 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4956                              const FunctionProtoType *Proto) {
4957   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4958                               isa<CXXMethodDecl>(FDecl);
4959   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4960                           IsMemberOperatorCall;
4961   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4962                                                   TheCall->getCallee());
4963   Expr** Args = TheCall->getArgs();
4964   unsigned NumArgs = TheCall->getNumArgs();
4965 
4966   Expr *ImplicitThis = nullptr;
4967   if (IsMemberOperatorCall) {
4968     // If this is a call to a member operator, hide the first argument
4969     // from checkCall.
4970     // FIXME: Our choice of AST representation here is less than ideal.
4971     ImplicitThis = Args[0];
4972     ++Args;
4973     --NumArgs;
4974   } else if (IsMemberFunction)
4975     ImplicitThis =
4976         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4977 
4978   if (ImplicitThis) {
4979     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4980     // used.
4981     QualType ThisType = ImplicitThis->getType();
4982     if (!ThisType->isPointerType()) {
4983       assert(!ThisType->isReferenceType());
4984       ThisType = Context.getPointerType(ThisType);
4985     }
4986 
4987     QualType ThisTypeFromDecl =
4988         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4989 
4990     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4991                       ThisTypeFromDecl);
4992   }
4993 
4994   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4995             IsMemberFunction, TheCall->getRParenLoc(),
4996             TheCall->getCallee()->getSourceRange(), CallType);
4997 
4998   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4999   // None of the checks below are needed for functions that don't have
5000   // simple names (e.g., C++ conversion functions).
5001   if (!FnInfo)
5002     return false;
5003 
5004   CheckTCBEnforcement(TheCall, FDecl);
5005 
5006   CheckAbsoluteValueFunction(TheCall, FDecl);
5007   CheckMaxUnsignedZero(TheCall, FDecl);
5008 
5009   if (getLangOpts().ObjC)
5010     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5011 
5012   unsigned CMId = FDecl->getMemoryFunctionKind();
5013 
5014   // Handle memory setting and copying functions.
5015   switch (CMId) {
5016   case 0:
5017     return false;
5018   case Builtin::BIstrlcpy: // fallthrough
5019   case Builtin::BIstrlcat:
5020     CheckStrlcpycatArguments(TheCall, FnInfo);
5021     break;
5022   case Builtin::BIstrncat:
5023     CheckStrncatArguments(TheCall, FnInfo);
5024     break;
5025   case Builtin::BIfree:
5026     CheckFreeArguments(TheCall);
5027     break;
5028   default:
5029     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5030   }
5031 
5032   return false;
5033 }
5034 
CheckObjCMethodCall(ObjCMethodDecl * Method,SourceLocation lbrac,ArrayRef<const Expr * > Args)5035 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5036                                ArrayRef<const Expr *> Args) {
5037   VariadicCallType CallType =
5038       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5039 
5040   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5041             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5042             CallType);
5043 
5044   return false;
5045 }
5046 
CheckPointerCall(NamedDecl * NDecl,CallExpr * TheCall,const FunctionProtoType * Proto)5047 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5048                             const FunctionProtoType *Proto) {
5049   QualType Ty;
5050   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5051     Ty = V->getType().getNonReferenceType();
5052   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5053     Ty = F->getType().getNonReferenceType();
5054   else
5055     return false;
5056 
5057   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5058       !Ty->isFunctionProtoType())
5059     return false;
5060 
5061   VariadicCallType CallType;
5062   if (!Proto || !Proto->isVariadic()) {
5063     CallType = VariadicDoesNotApply;
5064   } else if (Ty->isBlockPointerType()) {
5065     CallType = VariadicBlock;
5066   } else { // Ty->isFunctionPointerType()
5067     CallType = VariadicFunction;
5068   }
5069 
5070   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5071             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5072             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5073             TheCall->getCallee()->getSourceRange(), CallType);
5074 
5075   return false;
5076 }
5077 
5078 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5079 /// such as function pointers returned from functions.
CheckOtherCall(CallExpr * TheCall,const FunctionProtoType * Proto)5080 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5081   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5082                                                   TheCall->getCallee());
5083   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5084             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5085             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5086             TheCall->getCallee()->getSourceRange(), CallType);
5087 
5088   return false;
5089 }
5090 
isValidOrderingForOp(int64_t Ordering,AtomicExpr::AtomicOp Op)5091 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5092   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5093     return false;
5094 
5095   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5096   switch (Op) {
5097   case AtomicExpr::AO__c11_atomic_init:
5098   case AtomicExpr::AO__opencl_atomic_init:
5099     llvm_unreachable("There is no ordering argument for an init");
5100 
5101   case AtomicExpr::AO__c11_atomic_load:
5102   case AtomicExpr::AO__opencl_atomic_load:
5103   case AtomicExpr::AO__atomic_load_n:
5104   case AtomicExpr::AO__atomic_load:
5105     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5106            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5107 
5108   case AtomicExpr::AO__c11_atomic_store:
5109   case AtomicExpr::AO__opencl_atomic_store:
5110   case AtomicExpr::AO__atomic_store:
5111   case AtomicExpr::AO__atomic_store_n:
5112     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5113            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5114            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5115 
5116   default:
5117     return true;
5118   }
5119 }
5120 
SemaAtomicOpsOverloaded(ExprResult TheCallResult,AtomicExpr::AtomicOp Op)5121 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5122                                          AtomicExpr::AtomicOp Op) {
5123   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5124   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5125   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5126   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5127                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5128                          Op);
5129 }
5130 
BuildAtomicExpr(SourceRange CallRange,SourceRange ExprRange,SourceLocation RParenLoc,MultiExprArg Args,AtomicExpr::AtomicOp Op,AtomicArgumentOrder ArgOrder)5131 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5132                                  SourceLocation RParenLoc, MultiExprArg Args,
5133                                  AtomicExpr::AtomicOp Op,
5134                                  AtomicArgumentOrder ArgOrder) {
5135   // All the non-OpenCL operations take one of the following forms.
5136   // The OpenCL operations take the __c11 forms with one extra argument for
5137   // synchronization scope.
5138   enum {
5139     // C    __c11_atomic_init(A *, C)
5140     Init,
5141 
5142     // C    __c11_atomic_load(A *, int)
5143     Load,
5144 
5145     // void __atomic_load(A *, CP, int)
5146     LoadCopy,
5147 
5148     // void __atomic_store(A *, CP, int)
5149     Copy,
5150 
5151     // C    __c11_atomic_add(A *, M, int)
5152     Arithmetic,
5153 
5154     // C    __atomic_exchange_n(A *, CP, int)
5155     Xchg,
5156 
5157     // void __atomic_exchange(A *, C *, CP, int)
5158     GNUXchg,
5159 
5160     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5161     C11CmpXchg,
5162 
5163     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5164     GNUCmpXchg
5165   } Form = Init;
5166 
5167   const unsigned NumForm = GNUCmpXchg + 1;
5168   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5169   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5170   // where:
5171   //   C is an appropriate type,
5172   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5173   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5174   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5175   //   the int parameters are for orderings.
5176 
5177   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5178       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5179       "need to update code for modified forms");
5180   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5181                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5182                         AtomicExpr::AO__atomic_load,
5183                 "need to update code for modified C11 atomics");
5184   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5185                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5186   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5187                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5188                IsOpenCL;
5189   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5190              Op == AtomicExpr::AO__atomic_store_n ||
5191              Op == AtomicExpr::AO__atomic_exchange_n ||
5192              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5193   bool IsAddSub = false;
5194 
5195   switch (Op) {
5196   case AtomicExpr::AO__c11_atomic_init:
5197   case AtomicExpr::AO__opencl_atomic_init:
5198     Form = Init;
5199     break;
5200 
5201   case AtomicExpr::AO__c11_atomic_load:
5202   case AtomicExpr::AO__opencl_atomic_load:
5203   case AtomicExpr::AO__atomic_load_n:
5204     Form = Load;
5205     break;
5206 
5207   case AtomicExpr::AO__atomic_load:
5208     Form = LoadCopy;
5209     break;
5210 
5211   case AtomicExpr::AO__c11_atomic_store:
5212   case AtomicExpr::AO__opencl_atomic_store:
5213   case AtomicExpr::AO__atomic_store:
5214   case AtomicExpr::AO__atomic_store_n:
5215     Form = Copy;
5216     break;
5217 
5218   case AtomicExpr::AO__c11_atomic_fetch_add:
5219   case AtomicExpr::AO__c11_atomic_fetch_sub:
5220   case AtomicExpr::AO__opencl_atomic_fetch_add:
5221   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5222   case AtomicExpr::AO__atomic_fetch_add:
5223   case AtomicExpr::AO__atomic_fetch_sub:
5224   case AtomicExpr::AO__atomic_add_fetch:
5225   case AtomicExpr::AO__atomic_sub_fetch:
5226     IsAddSub = true;
5227     Form = Arithmetic;
5228     break;
5229   case AtomicExpr::AO__c11_atomic_fetch_and:
5230   case AtomicExpr::AO__c11_atomic_fetch_or:
5231   case AtomicExpr::AO__c11_atomic_fetch_xor:
5232   case AtomicExpr::AO__opencl_atomic_fetch_and:
5233   case AtomicExpr::AO__opencl_atomic_fetch_or:
5234   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5235   case AtomicExpr::AO__atomic_fetch_and:
5236   case AtomicExpr::AO__atomic_fetch_or:
5237   case AtomicExpr::AO__atomic_fetch_xor:
5238   case AtomicExpr::AO__atomic_fetch_nand:
5239   case AtomicExpr::AO__atomic_and_fetch:
5240   case AtomicExpr::AO__atomic_or_fetch:
5241   case AtomicExpr::AO__atomic_xor_fetch:
5242   case AtomicExpr::AO__atomic_nand_fetch:
5243     Form = Arithmetic;
5244     break;
5245   case AtomicExpr::AO__c11_atomic_fetch_min:
5246   case AtomicExpr::AO__c11_atomic_fetch_max:
5247   case AtomicExpr::AO__opencl_atomic_fetch_min:
5248   case AtomicExpr::AO__opencl_atomic_fetch_max:
5249   case AtomicExpr::AO__atomic_min_fetch:
5250   case AtomicExpr::AO__atomic_max_fetch:
5251   case AtomicExpr::AO__atomic_fetch_min:
5252   case AtomicExpr::AO__atomic_fetch_max:
5253     Form = Arithmetic;
5254     break;
5255 
5256   case AtomicExpr::AO__c11_atomic_exchange:
5257   case AtomicExpr::AO__opencl_atomic_exchange:
5258   case AtomicExpr::AO__atomic_exchange_n:
5259     Form = Xchg;
5260     break;
5261 
5262   case AtomicExpr::AO__atomic_exchange:
5263     Form = GNUXchg;
5264     break;
5265 
5266   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5267   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5268   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5269   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5270     Form = C11CmpXchg;
5271     break;
5272 
5273   case AtomicExpr::AO__atomic_compare_exchange:
5274   case AtomicExpr::AO__atomic_compare_exchange_n:
5275     Form = GNUCmpXchg;
5276     break;
5277   }
5278 
5279   unsigned AdjustedNumArgs = NumArgs[Form];
5280   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5281     ++AdjustedNumArgs;
5282   // Check we have the right number of arguments.
5283   if (Args.size() < AdjustedNumArgs) {
5284     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5285         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5286         << ExprRange;
5287     return ExprError();
5288   } else if (Args.size() > AdjustedNumArgs) {
5289     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5290          diag::err_typecheck_call_too_many_args)
5291         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5292         << ExprRange;
5293     return ExprError();
5294   }
5295 
5296   // Inspect the first argument of the atomic operation.
5297   Expr *Ptr = Args[0];
5298   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5299   if (ConvertedPtr.isInvalid())
5300     return ExprError();
5301 
5302   Ptr = ConvertedPtr.get();
5303   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5304   if (!pointerType) {
5305     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5306         << Ptr->getType() << Ptr->getSourceRange();
5307     return ExprError();
5308   }
5309 
5310   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5311   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5312   QualType ValType = AtomTy; // 'C'
5313   if (IsC11) {
5314     if (!AtomTy->isAtomicType()) {
5315       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5316           << Ptr->getType() << Ptr->getSourceRange();
5317       return ExprError();
5318     }
5319     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5320         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5321       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5322           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5323           << Ptr->getSourceRange();
5324       return ExprError();
5325     }
5326     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5327   } else if (Form != Load && Form != LoadCopy) {
5328     if (ValType.isConstQualified()) {
5329       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5330           << Ptr->getType() << Ptr->getSourceRange();
5331       return ExprError();
5332     }
5333   }
5334 
5335   // For an arithmetic operation, the implied arithmetic must be well-formed.
5336   if (Form == Arithmetic) {
5337     // gcc does not enforce these rules for GNU atomics, but we do so for
5338     // sanity.
5339     auto IsAllowedValueType = [&](QualType ValType) {
5340       if (ValType->isIntegerType())
5341         return true;
5342       if (ValType->isPointerType())
5343         return true;
5344       if (!ValType->isFloatingType())
5345         return false;
5346       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5347       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5348           &Context.getTargetInfo().getLongDoubleFormat() ==
5349               &llvm::APFloat::x87DoubleExtended())
5350         return false;
5351       return true;
5352     };
5353     if (IsAddSub && !IsAllowedValueType(ValType)) {
5354       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5355           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5356       return ExprError();
5357     }
5358     if (!IsAddSub && !ValType->isIntegerType()) {
5359       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5360           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5361       return ExprError();
5362     }
5363     if (IsC11 && ValType->isPointerType() &&
5364         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5365                             diag::err_incomplete_type)) {
5366       return ExprError();
5367     }
5368   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5369     // For __atomic_*_n operations, the value type must be a scalar integral or
5370     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5371     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5372         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5373     return ExprError();
5374   }
5375 
5376   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5377       !AtomTy->isScalarType()) {
5378     // For GNU atomics, require a trivially-copyable type. This is not part of
5379     // the GNU atomics specification, but we enforce it for sanity.
5380     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5381         << Ptr->getType() << Ptr->getSourceRange();
5382     return ExprError();
5383   }
5384 
5385   switch (ValType.getObjCLifetime()) {
5386   case Qualifiers::OCL_None:
5387   case Qualifiers::OCL_ExplicitNone:
5388     // okay
5389     break;
5390 
5391   case Qualifiers::OCL_Weak:
5392   case Qualifiers::OCL_Strong:
5393   case Qualifiers::OCL_Autoreleasing:
5394     // FIXME: Can this happen? By this point, ValType should be known
5395     // to be trivially copyable.
5396     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5397         << ValType << Ptr->getSourceRange();
5398     return ExprError();
5399   }
5400 
5401   // All atomic operations have an overload which takes a pointer to a volatile
5402   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5403   // into the result or the other operands. Similarly atomic_load takes a
5404   // pointer to a const 'A'.
5405   ValType.removeLocalVolatile();
5406   ValType.removeLocalConst();
5407   QualType ResultType = ValType;
5408   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5409       Form == Init)
5410     ResultType = Context.VoidTy;
5411   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5412     ResultType = Context.BoolTy;
5413 
5414   // The type of a parameter passed 'by value'. In the GNU atomics, such
5415   // arguments are actually passed as pointers.
5416   QualType ByValType = ValType; // 'CP'
5417   bool IsPassedByAddress = false;
5418   if (!IsC11 && !IsN) {
5419     ByValType = Ptr->getType();
5420     IsPassedByAddress = true;
5421   }
5422 
5423   SmallVector<Expr *, 5> APIOrderedArgs;
5424   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5425     APIOrderedArgs.push_back(Args[0]);
5426     switch (Form) {
5427     case Init:
5428     case Load:
5429       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5430       break;
5431     case LoadCopy:
5432     case Copy:
5433     case Arithmetic:
5434     case Xchg:
5435       APIOrderedArgs.push_back(Args[2]); // Val1
5436       APIOrderedArgs.push_back(Args[1]); // Order
5437       break;
5438     case GNUXchg:
5439       APIOrderedArgs.push_back(Args[2]); // Val1
5440       APIOrderedArgs.push_back(Args[3]); // Val2
5441       APIOrderedArgs.push_back(Args[1]); // Order
5442       break;
5443     case C11CmpXchg:
5444       APIOrderedArgs.push_back(Args[2]); // Val1
5445       APIOrderedArgs.push_back(Args[4]); // Val2
5446       APIOrderedArgs.push_back(Args[1]); // Order
5447       APIOrderedArgs.push_back(Args[3]); // OrderFail
5448       break;
5449     case GNUCmpXchg:
5450       APIOrderedArgs.push_back(Args[2]); // Val1
5451       APIOrderedArgs.push_back(Args[4]); // Val2
5452       APIOrderedArgs.push_back(Args[5]); // Weak
5453       APIOrderedArgs.push_back(Args[1]); // Order
5454       APIOrderedArgs.push_back(Args[3]); // OrderFail
5455       break;
5456     }
5457   } else
5458     APIOrderedArgs.append(Args.begin(), Args.end());
5459 
5460   // The first argument's non-CV pointer type is used to deduce the type of
5461   // subsequent arguments, except for:
5462   //  - weak flag (always converted to bool)
5463   //  - memory order (always converted to int)
5464   //  - scope  (always converted to int)
5465   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5466     QualType Ty;
5467     if (i < NumVals[Form] + 1) {
5468       switch (i) {
5469       case 0:
5470         // The first argument is always a pointer. It has a fixed type.
5471         // It is always dereferenced, a nullptr is undefined.
5472         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5473         // Nothing else to do: we already know all we want about this pointer.
5474         continue;
5475       case 1:
5476         // The second argument is the non-atomic operand. For arithmetic, this
5477         // is always passed by value, and for a compare_exchange it is always
5478         // passed by address. For the rest, GNU uses by-address and C11 uses
5479         // by-value.
5480         assert(Form != Load);
5481         if (Form == Arithmetic && ValType->isPointerType())
5482           Ty = Context.getPointerDiffType();
5483         else if (Form == Init || Form == Arithmetic)
5484           Ty = ValType;
5485         else if (Form == Copy || Form == Xchg) {
5486           if (IsPassedByAddress) {
5487             // The value pointer is always dereferenced, a nullptr is undefined.
5488             CheckNonNullArgument(*this, APIOrderedArgs[i],
5489                                  ExprRange.getBegin());
5490           }
5491           Ty = ByValType;
5492         } else {
5493           Expr *ValArg = APIOrderedArgs[i];
5494           // The value pointer is always dereferenced, a nullptr is undefined.
5495           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5496           LangAS AS = LangAS::Default;
5497           // Keep address space of non-atomic pointer type.
5498           if (const PointerType *PtrTy =
5499                   ValArg->getType()->getAs<PointerType>()) {
5500             AS = PtrTy->getPointeeType().getAddressSpace();
5501           }
5502           Ty = Context.getPointerType(
5503               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5504         }
5505         break;
5506       case 2:
5507         // The third argument to compare_exchange / GNU exchange is the desired
5508         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5509         if (IsPassedByAddress)
5510           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5511         Ty = ByValType;
5512         break;
5513       case 3:
5514         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5515         Ty = Context.BoolTy;
5516         break;
5517       }
5518     } else {
5519       // The order(s) and scope are always converted to int.
5520       Ty = Context.IntTy;
5521     }
5522 
5523     InitializedEntity Entity =
5524         InitializedEntity::InitializeParameter(Context, Ty, false);
5525     ExprResult Arg = APIOrderedArgs[i];
5526     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5527     if (Arg.isInvalid())
5528       return true;
5529     APIOrderedArgs[i] = Arg.get();
5530   }
5531 
5532   // Permute the arguments into a 'consistent' order.
5533   SmallVector<Expr*, 5> SubExprs;
5534   SubExprs.push_back(Ptr);
5535   switch (Form) {
5536   case Init:
5537     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5538     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5539     break;
5540   case Load:
5541     SubExprs.push_back(APIOrderedArgs[1]); // Order
5542     break;
5543   case LoadCopy:
5544   case Copy:
5545   case Arithmetic:
5546   case Xchg:
5547     SubExprs.push_back(APIOrderedArgs[2]); // Order
5548     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5549     break;
5550   case GNUXchg:
5551     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5552     SubExprs.push_back(APIOrderedArgs[3]); // Order
5553     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5554     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5555     break;
5556   case C11CmpXchg:
5557     SubExprs.push_back(APIOrderedArgs[3]); // Order
5558     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5559     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5560     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5561     break;
5562   case GNUCmpXchg:
5563     SubExprs.push_back(APIOrderedArgs[4]); // Order
5564     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5565     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5566     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5567     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5568     break;
5569   }
5570 
5571   if (SubExprs.size() >= 2 && Form != Init) {
5572     if (Optional<llvm::APSInt> Result =
5573             SubExprs[1]->getIntegerConstantExpr(Context))
5574       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5575         Diag(SubExprs[1]->getBeginLoc(),
5576              diag::warn_atomic_op_has_invalid_memory_order)
5577             << SubExprs[1]->getSourceRange();
5578   }
5579 
5580   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5581     auto *Scope = Args[Args.size() - 1];
5582     if (Optional<llvm::APSInt> Result =
5583             Scope->getIntegerConstantExpr(Context)) {
5584       if (!ScopeModel->isValid(Result->getZExtValue()))
5585         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5586             << Scope->getSourceRange();
5587     }
5588     SubExprs.push_back(Scope);
5589   }
5590 
5591   AtomicExpr *AE = new (Context)
5592       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5593 
5594   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5595        Op == AtomicExpr::AO__c11_atomic_store ||
5596        Op == AtomicExpr::AO__opencl_atomic_load ||
5597        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5598       Context.AtomicUsesUnsupportedLibcall(AE))
5599     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5600         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5601              Op == AtomicExpr::AO__opencl_atomic_load)
5602                 ? 0
5603                 : 1);
5604 
5605   if (ValType->isExtIntType()) {
5606     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5607     return ExprError();
5608   }
5609 
5610   return AE;
5611 }
5612 
5613 /// checkBuiltinArgument - Given a call to a builtin function, perform
5614 /// normal type-checking on the given argument, updating the call in
5615 /// place.  This is useful when a builtin function requires custom
5616 /// type-checking for some of its arguments but not necessarily all of
5617 /// them.
5618 ///
5619 /// Returns true on error.
checkBuiltinArgument(Sema & S,CallExpr * E,unsigned ArgIndex)5620 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5621   FunctionDecl *Fn = E->getDirectCallee();
5622   assert(Fn && "builtin call without direct callee!");
5623 
5624   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5625   InitializedEntity Entity =
5626     InitializedEntity::InitializeParameter(S.Context, Param);
5627 
5628   ExprResult Arg = E->getArg(0);
5629   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5630   if (Arg.isInvalid())
5631     return true;
5632 
5633   E->setArg(ArgIndex, Arg.get());
5634   return false;
5635 }
5636 
5637 /// We have a call to a function like __sync_fetch_and_add, which is an
5638 /// overloaded function based on the pointer type of its first argument.
5639 /// The main BuildCallExpr routines have already promoted the types of
5640 /// arguments because all of these calls are prototyped as void(...).
5641 ///
5642 /// This function goes through and does final semantic checking for these
5643 /// builtins, as well as generating any warnings.
5644 ExprResult
SemaBuiltinAtomicOverloaded(ExprResult TheCallResult)5645 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5646   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5647   Expr *Callee = TheCall->getCallee();
5648   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5649   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5650 
5651   // Ensure that we have at least one argument to do type inference from.
5652   if (TheCall->getNumArgs() < 1) {
5653     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5654         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5655     return ExprError();
5656   }
5657 
5658   // Inspect the first argument of the atomic builtin.  This should always be
5659   // a pointer type, whose element is an integral scalar or pointer type.
5660   // Because it is a pointer type, we don't have to worry about any implicit
5661   // casts here.
5662   // FIXME: We don't allow floating point scalars as input.
5663   Expr *FirstArg = TheCall->getArg(0);
5664   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5665   if (FirstArgResult.isInvalid())
5666     return ExprError();
5667   FirstArg = FirstArgResult.get();
5668   TheCall->setArg(0, FirstArg);
5669 
5670   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5671   if (!pointerType) {
5672     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5673         << FirstArg->getType() << FirstArg->getSourceRange();
5674     return ExprError();
5675   }
5676 
5677   QualType ValType = pointerType->getPointeeType();
5678   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5679       !ValType->isBlockPointerType()) {
5680     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5681         << FirstArg->getType() << FirstArg->getSourceRange();
5682     return ExprError();
5683   }
5684 
5685   if (ValType.isConstQualified()) {
5686     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5687         << FirstArg->getType() << FirstArg->getSourceRange();
5688     return ExprError();
5689   }
5690 
5691   switch (ValType.getObjCLifetime()) {
5692   case Qualifiers::OCL_None:
5693   case Qualifiers::OCL_ExplicitNone:
5694     // okay
5695     break;
5696 
5697   case Qualifiers::OCL_Weak:
5698   case Qualifiers::OCL_Strong:
5699   case Qualifiers::OCL_Autoreleasing:
5700     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5701         << ValType << FirstArg->getSourceRange();
5702     return ExprError();
5703   }
5704 
5705   // Strip any qualifiers off ValType.
5706   ValType = ValType.getUnqualifiedType();
5707 
5708   // The majority of builtins return a value, but a few have special return
5709   // types, so allow them to override appropriately below.
5710   QualType ResultType = ValType;
5711 
5712   // We need to figure out which concrete builtin this maps onto.  For example,
5713   // __sync_fetch_and_add with a 2 byte object turns into
5714   // __sync_fetch_and_add_2.
5715 #define BUILTIN_ROW(x) \
5716   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5717     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5718 
5719   static const unsigned BuiltinIndices[][5] = {
5720     BUILTIN_ROW(__sync_fetch_and_add),
5721     BUILTIN_ROW(__sync_fetch_and_sub),
5722     BUILTIN_ROW(__sync_fetch_and_or),
5723     BUILTIN_ROW(__sync_fetch_and_and),
5724     BUILTIN_ROW(__sync_fetch_and_xor),
5725     BUILTIN_ROW(__sync_fetch_and_nand),
5726 
5727     BUILTIN_ROW(__sync_add_and_fetch),
5728     BUILTIN_ROW(__sync_sub_and_fetch),
5729     BUILTIN_ROW(__sync_and_and_fetch),
5730     BUILTIN_ROW(__sync_or_and_fetch),
5731     BUILTIN_ROW(__sync_xor_and_fetch),
5732     BUILTIN_ROW(__sync_nand_and_fetch),
5733 
5734     BUILTIN_ROW(__sync_val_compare_and_swap),
5735     BUILTIN_ROW(__sync_bool_compare_and_swap),
5736     BUILTIN_ROW(__sync_lock_test_and_set),
5737     BUILTIN_ROW(__sync_lock_release),
5738     BUILTIN_ROW(__sync_swap)
5739   };
5740 #undef BUILTIN_ROW
5741 
5742   // Determine the index of the size.
5743   unsigned SizeIndex;
5744   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5745   case 1: SizeIndex = 0; break;
5746   case 2: SizeIndex = 1; break;
5747   case 4: SizeIndex = 2; break;
5748   case 8: SizeIndex = 3; break;
5749   case 16: SizeIndex = 4; break;
5750   default:
5751     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5752         << FirstArg->getType() << FirstArg->getSourceRange();
5753     return ExprError();
5754   }
5755 
5756   // Each of these builtins has one pointer argument, followed by some number of
5757   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5758   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5759   // as the number of fixed args.
5760   unsigned BuiltinID = FDecl->getBuiltinID();
5761   unsigned BuiltinIndex, NumFixed = 1;
5762   bool WarnAboutSemanticsChange = false;
5763   switch (BuiltinID) {
5764   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5765   case Builtin::BI__sync_fetch_and_add:
5766   case Builtin::BI__sync_fetch_and_add_1:
5767   case Builtin::BI__sync_fetch_and_add_2:
5768   case Builtin::BI__sync_fetch_and_add_4:
5769   case Builtin::BI__sync_fetch_and_add_8:
5770   case Builtin::BI__sync_fetch_and_add_16:
5771     BuiltinIndex = 0;
5772     break;
5773 
5774   case Builtin::BI__sync_fetch_and_sub:
5775   case Builtin::BI__sync_fetch_and_sub_1:
5776   case Builtin::BI__sync_fetch_and_sub_2:
5777   case Builtin::BI__sync_fetch_and_sub_4:
5778   case Builtin::BI__sync_fetch_and_sub_8:
5779   case Builtin::BI__sync_fetch_and_sub_16:
5780     BuiltinIndex = 1;
5781     break;
5782 
5783   case Builtin::BI__sync_fetch_and_or:
5784   case Builtin::BI__sync_fetch_and_or_1:
5785   case Builtin::BI__sync_fetch_and_or_2:
5786   case Builtin::BI__sync_fetch_and_or_4:
5787   case Builtin::BI__sync_fetch_and_or_8:
5788   case Builtin::BI__sync_fetch_and_or_16:
5789     BuiltinIndex = 2;
5790     break;
5791 
5792   case Builtin::BI__sync_fetch_and_and:
5793   case Builtin::BI__sync_fetch_and_and_1:
5794   case Builtin::BI__sync_fetch_and_and_2:
5795   case Builtin::BI__sync_fetch_and_and_4:
5796   case Builtin::BI__sync_fetch_and_and_8:
5797   case Builtin::BI__sync_fetch_and_and_16:
5798     BuiltinIndex = 3;
5799     break;
5800 
5801   case Builtin::BI__sync_fetch_and_xor:
5802   case Builtin::BI__sync_fetch_and_xor_1:
5803   case Builtin::BI__sync_fetch_and_xor_2:
5804   case Builtin::BI__sync_fetch_and_xor_4:
5805   case Builtin::BI__sync_fetch_and_xor_8:
5806   case Builtin::BI__sync_fetch_and_xor_16:
5807     BuiltinIndex = 4;
5808     break;
5809 
5810   case Builtin::BI__sync_fetch_and_nand:
5811   case Builtin::BI__sync_fetch_and_nand_1:
5812   case Builtin::BI__sync_fetch_and_nand_2:
5813   case Builtin::BI__sync_fetch_and_nand_4:
5814   case Builtin::BI__sync_fetch_and_nand_8:
5815   case Builtin::BI__sync_fetch_and_nand_16:
5816     BuiltinIndex = 5;
5817     WarnAboutSemanticsChange = true;
5818     break;
5819 
5820   case Builtin::BI__sync_add_and_fetch:
5821   case Builtin::BI__sync_add_and_fetch_1:
5822   case Builtin::BI__sync_add_and_fetch_2:
5823   case Builtin::BI__sync_add_and_fetch_4:
5824   case Builtin::BI__sync_add_and_fetch_8:
5825   case Builtin::BI__sync_add_and_fetch_16:
5826     BuiltinIndex = 6;
5827     break;
5828 
5829   case Builtin::BI__sync_sub_and_fetch:
5830   case Builtin::BI__sync_sub_and_fetch_1:
5831   case Builtin::BI__sync_sub_and_fetch_2:
5832   case Builtin::BI__sync_sub_and_fetch_4:
5833   case Builtin::BI__sync_sub_and_fetch_8:
5834   case Builtin::BI__sync_sub_and_fetch_16:
5835     BuiltinIndex = 7;
5836     break;
5837 
5838   case Builtin::BI__sync_and_and_fetch:
5839   case Builtin::BI__sync_and_and_fetch_1:
5840   case Builtin::BI__sync_and_and_fetch_2:
5841   case Builtin::BI__sync_and_and_fetch_4:
5842   case Builtin::BI__sync_and_and_fetch_8:
5843   case Builtin::BI__sync_and_and_fetch_16:
5844     BuiltinIndex = 8;
5845     break;
5846 
5847   case Builtin::BI__sync_or_and_fetch:
5848   case Builtin::BI__sync_or_and_fetch_1:
5849   case Builtin::BI__sync_or_and_fetch_2:
5850   case Builtin::BI__sync_or_and_fetch_4:
5851   case Builtin::BI__sync_or_and_fetch_8:
5852   case Builtin::BI__sync_or_and_fetch_16:
5853     BuiltinIndex = 9;
5854     break;
5855 
5856   case Builtin::BI__sync_xor_and_fetch:
5857   case Builtin::BI__sync_xor_and_fetch_1:
5858   case Builtin::BI__sync_xor_and_fetch_2:
5859   case Builtin::BI__sync_xor_and_fetch_4:
5860   case Builtin::BI__sync_xor_and_fetch_8:
5861   case Builtin::BI__sync_xor_and_fetch_16:
5862     BuiltinIndex = 10;
5863     break;
5864 
5865   case Builtin::BI__sync_nand_and_fetch:
5866   case Builtin::BI__sync_nand_and_fetch_1:
5867   case Builtin::BI__sync_nand_and_fetch_2:
5868   case Builtin::BI__sync_nand_and_fetch_4:
5869   case Builtin::BI__sync_nand_and_fetch_8:
5870   case Builtin::BI__sync_nand_and_fetch_16:
5871     BuiltinIndex = 11;
5872     WarnAboutSemanticsChange = true;
5873     break;
5874 
5875   case Builtin::BI__sync_val_compare_and_swap:
5876   case Builtin::BI__sync_val_compare_and_swap_1:
5877   case Builtin::BI__sync_val_compare_and_swap_2:
5878   case Builtin::BI__sync_val_compare_and_swap_4:
5879   case Builtin::BI__sync_val_compare_and_swap_8:
5880   case Builtin::BI__sync_val_compare_and_swap_16:
5881     BuiltinIndex = 12;
5882     NumFixed = 2;
5883     break;
5884 
5885   case Builtin::BI__sync_bool_compare_and_swap:
5886   case Builtin::BI__sync_bool_compare_and_swap_1:
5887   case Builtin::BI__sync_bool_compare_and_swap_2:
5888   case Builtin::BI__sync_bool_compare_and_swap_4:
5889   case Builtin::BI__sync_bool_compare_and_swap_8:
5890   case Builtin::BI__sync_bool_compare_and_swap_16:
5891     BuiltinIndex = 13;
5892     NumFixed = 2;
5893     ResultType = Context.BoolTy;
5894     break;
5895 
5896   case Builtin::BI__sync_lock_test_and_set:
5897   case Builtin::BI__sync_lock_test_and_set_1:
5898   case Builtin::BI__sync_lock_test_and_set_2:
5899   case Builtin::BI__sync_lock_test_and_set_4:
5900   case Builtin::BI__sync_lock_test_and_set_8:
5901   case Builtin::BI__sync_lock_test_and_set_16:
5902     BuiltinIndex = 14;
5903     break;
5904 
5905   case Builtin::BI__sync_lock_release:
5906   case Builtin::BI__sync_lock_release_1:
5907   case Builtin::BI__sync_lock_release_2:
5908   case Builtin::BI__sync_lock_release_4:
5909   case Builtin::BI__sync_lock_release_8:
5910   case Builtin::BI__sync_lock_release_16:
5911     BuiltinIndex = 15;
5912     NumFixed = 0;
5913     ResultType = Context.VoidTy;
5914     break;
5915 
5916   case Builtin::BI__sync_swap:
5917   case Builtin::BI__sync_swap_1:
5918   case Builtin::BI__sync_swap_2:
5919   case Builtin::BI__sync_swap_4:
5920   case Builtin::BI__sync_swap_8:
5921   case Builtin::BI__sync_swap_16:
5922     BuiltinIndex = 16;
5923     break;
5924   }
5925 
5926   // Now that we know how many fixed arguments we expect, first check that we
5927   // have at least that many.
5928   if (TheCall->getNumArgs() < 1+NumFixed) {
5929     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5930         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5931         << Callee->getSourceRange();
5932     return ExprError();
5933   }
5934 
5935   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5936       << Callee->getSourceRange();
5937 
5938   if (WarnAboutSemanticsChange) {
5939     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5940         << Callee->getSourceRange();
5941   }
5942 
5943   // Get the decl for the concrete builtin from this, we can tell what the
5944   // concrete integer type we should convert to is.
5945   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5946   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5947   FunctionDecl *NewBuiltinDecl;
5948   if (NewBuiltinID == BuiltinID)
5949     NewBuiltinDecl = FDecl;
5950   else {
5951     // Perform builtin lookup to avoid redeclaring it.
5952     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5953     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5954     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5955     assert(Res.getFoundDecl());
5956     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5957     if (!NewBuiltinDecl)
5958       return ExprError();
5959   }
5960 
5961   // The first argument --- the pointer --- has a fixed type; we
5962   // deduce the types of the rest of the arguments accordingly.  Walk
5963   // the remaining arguments, converting them to the deduced value type.
5964   for (unsigned i = 0; i != NumFixed; ++i) {
5965     ExprResult Arg = TheCall->getArg(i+1);
5966 
5967     // GCC does an implicit conversion to the pointer or integer ValType.  This
5968     // can fail in some cases (1i -> int**), check for this error case now.
5969     // Initialize the argument.
5970     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5971                                                    ValType, /*consume*/ false);
5972     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5973     if (Arg.isInvalid())
5974       return ExprError();
5975 
5976     // Okay, we have something that *can* be converted to the right type.  Check
5977     // to see if there is a potentially weird extension going on here.  This can
5978     // happen when you do an atomic operation on something like an char* and
5979     // pass in 42.  The 42 gets converted to char.  This is even more strange
5980     // for things like 45.123 -> char, etc.
5981     // FIXME: Do this check.
5982     TheCall->setArg(i+1, Arg.get());
5983   }
5984 
5985   // Create a new DeclRefExpr to refer to the new decl.
5986   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5987       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5988       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5989       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5990 
5991   // Set the callee in the CallExpr.
5992   // FIXME: This loses syntactic information.
5993   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5994   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5995                                               CK_BuiltinFnToFnPtr);
5996   TheCall->setCallee(PromotedCall.get());
5997 
5998   // Change the result type of the call to match the original value type. This
5999   // is arbitrary, but the codegen for these builtins ins design to handle it
6000   // gracefully.
6001   TheCall->setType(ResultType);
6002 
6003   // Prohibit use of _ExtInt with atomic builtins.
6004   // The arguments would have already been converted to the first argument's
6005   // type, so only need to check the first argument.
6006   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6007   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6008     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6009     return ExprError();
6010   }
6011 
6012   return TheCallResult;
6013 }
6014 
6015 /// SemaBuiltinNontemporalOverloaded - We have a call to
6016 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6017 /// overloaded function based on the pointer type of its last argument.
6018 ///
6019 /// This function goes through and does final semantic checking for these
6020 /// builtins.
SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult)6021 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6022   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6023   DeclRefExpr *DRE =
6024       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6025   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6026   unsigned BuiltinID = FDecl->getBuiltinID();
6027   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6028           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6029          "Unexpected nontemporal load/store builtin!");
6030   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6031   unsigned numArgs = isStore ? 2 : 1;
6032 
6033   // Ensure that we have the proper number of arguments.
6034   if (checkArgCount(*this, TheCall, numArgs))
6035     return ExprError();
6036 
6037   // Inspect the last argument of the nontemporal builtin.  This should always
6038   // be a pointer type, from which we imply the type of the memory access.
6039   // Because it is a pointer type, we don't have to worry about any implicit
6040   // casts here.
6041   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6042   ExprResult PointerArgResult =
6043       DefaultFunctionArrayLvalueConversion(PointerArg);
6044 
6045   if (PointerArgResult.isInvalid())
6046     return ExprError();
6047   PointerArg = PointerArgResult.get();
6048   TheCall->setArg(numArgs - 1, PointerArg);
6049 
6050   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6051   if (!pointerType) {
6052     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6053         << PointerArg->getType() << PointerArg->getSourceRange();
6054     return ExprError();
6055   }
6056 
6057   QualType ValType = pointerType->getPointeeType();
6058 
6059   // Strip any qualifiers off ValType.
6060   ValType = ValType.getUnqualifiedType();
6061   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6062       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6063       !ValType->isVectorType()) {
6064     Diag(DRE->getBeginLoc(),
6065          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6066         << PointerArg->getType() << PointerArg->getSourceRange();
6067     return ExprError();
6068   }
6069 
6070   if (!isStore) {
6071     TheCall->setType(ValType);
6072     return TheCallResult;
6073   }
6074 
6075   ExprResult ValArg = TheCall->getArg(0);
6076   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6077       Context, ValType, /*consume*/ false);
6078   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6079   if (ValArg.isInvalid())
6080     return ExprError();
6081 
6082   TheCall->setArg(0, ValArg.get());
6083   TheCall->setType(Context.VoidTy);
6084   return TheCallResult;
6085 }
6086 
6087 /// CheckObjCString - Checks that the argument to the builtin
6088 /// CFString constructor is correct
6089 /// Note: It might also make sense to do the UTF-16 conversion here (would
6090 /// simplify the backend).
CheckObjCString(Expr * Arg)6091 bool Sema::CheckObjCString(Expr *Arg) {
6092   Arg = Arg->IgnoreParenCasts();
6093   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6094 
6095   if (!Literal || !Literal->isAscii()) {
6096     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6097         << Arg->getSourceRange();
6098     return true;
6099   }
6100 
6101   if (Literal->containsNonAsciiOrNull()) {
6102     StringRef String = Literal->getString();
6103     unsigned NumBytes = String.size();
6104     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6105     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6106     llvm::UTF16 *ToPtr = &ToBuf[0];
6107 
6108     llvm::ConversionResult Result =
6109         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6110                                  ToPtr + NumBytes, llvm::strictConversion);
6111     // Check for conversion failure.
6112     if (Result != llvm::conversionOK)
6113       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6114           << Arg->getSourceRange();
6115   }
6116   return false;
6117 }
6118 
6119 /// CheckObjCString - Checks that the format string argument to the os_log()
6120 /// and os_trace() functions is correct, and converts it to const char *.
CheckOSLogFormatStringArg(Expr * Arg)6121 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6122   Arg = Arg->IgnoreParenCasts();
6123   auto *Literal = dyn_cast<StringLiteral>(Arg);
6124   if (!Literal) {
6125     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6126       Literal = ObjcLiteral->getString();
6127     }
6128   }
6129 
6130   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6131     return ExprError(
6132         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6133         << Arg->getSourceRange());
6134   }
6135 
6136   ExprResult Result(Literal);
6137   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6138   InitializedEntity Entity =
6139       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6140   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6141   return Result;
6142 }
6143 
6144 /// Check that the user is calling the appropriate va_start builtin for the
6145 /// target and calling convention.
checkVAStartABI(Sema & S,unsigned BuiltinID,Expr * Fn)6146 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6147   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6148   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6149   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6150                     TT.getArch() == llvm::Triple::aarch64_32);
6151   bool IsWindows = TT.isOSWindows();
6152   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6153   if (IsX64 || IsAArch64) {
6154     CallingConv CC = CC_C;
6155     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6156       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6157     if (IsMSVAStart) {
6158       // Don't allow this in System V ABI functions.
6159       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6160         return S.Diag(Fn->getBeginLoc(),
6161                       diag::err_ms_va_start_used_in_sysv_function);
6162     } else {
6163       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6164       // On x64 Windows, don't allow this in System V ABI functions.
6165       // (Yes, that means there's no corresponding way to support variadic
6166       // System V ABI functions on Windows.)
6167       if ((IsWindows && CC == CC_X86_64SysV) ||
6168           (!IsWindows && CC == CC_Win64))
6169         return S.Diag(Fn->getBeginLoc(),
6170                       diag::err_va_start_used_in_wrong_abi_function)
6171                << !IsWindows;
6172     }
6173     return false;
6174   }
6175 
6176   if (IsMSVAStart)
6177     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6178   return false;
6179 }
6180 
checkVAStartIsInVariadicFunction(Sema & S,Expr * Fn,ParmVarDecl ** LastParam=nullptr)6181 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6182                                              ParmVarDecl **LastParam = nullptr) {
6183   // Determine whether the current function, block, or obj-c method is variadic
6184   // and get its parameter list.
6185   bool IsVariadic = false;
6186   ArrayRef<ParmVarDecl *> Params;
6187   DeclContext *Caller = S.CurContext;
6188   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6189     IsVariadic = Block->isVariadic();
6190     Params = Block->parameters();
6191   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6192     IsVariadic = FD->isVariadic();
6193     Params = FD->parameters();
6194   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6195     IsVariadic = MD->isVariadic();
6196     // FIXME: This isn't correct for methods (results in bogus warning).
6197     Params = MD->parameters();
6198   } else if (isa<CapturedDecl>(Caller)) {
6199     // We don't support va_start in a CapturedDecl.
6200     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6201     return true;
6202   } else {
6203     // This must be some other declcontext that parses exprs.
6204     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6205     return true;
6206   }
6207 
6208   if (!IsVariadic) {
6209     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6210     return true;
6211   }
6212 
6213   if (LastParam)
6214     *LastParam = Params.empty() ? nullptr : Params.back();
6215 
6216   return false;
6217 }
6218 
6219 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6220 /// for validity.  Emit an error and return true on failure; return false
6221 /// on success.
SemaBuiltinVAStart(unsigned BuiltinID,CallExpr * TheCall)6222 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6223   Expr *Fn = TheCall->getCallee();
6224 
6225   if (checkVAStartABI(*this, BuiltinID, Fn))
6226     return true;
6227 
6228   if (checkArgCount(*this, TheCall, 2))
6229     return true;
6230 
6231   // Type-check the first argument normally.
6232   if (checkBuiltinArgument(*this, TheCall, 0))
6233     return true;
6234 
6235   // Check that the current function is variadic, and get its last parameter.
6236   ParmVarDecl *LastParam;
6237   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6238     return true;
6239 
6240   // Verify that the second argument to the builtin is the last argument of the
6241   // current function or method.
6242   bool SecondArgIsLastNamedArgument = false;
6243   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6244 
6245   // These are valid if SecondArgIsLastNamedArgument is false after the next
6246   // block.
6247   QualType Type;
6248   SourceLocation ParamLoc;
6249   bool IsCRegister = false;
6250 
6251   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6252     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6253       SecondArgIsLastNamedArgument = PV == LastParam;
6254 
6255       Type = PV->getType();
6256       ParamLoc = PV->getLocation();
6257       IsCRegister =
6258           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6259     }
6260   }
6261 
6262   if (!SecondArgIsLastNamedArgument)
6263     Diag(TheCall->getArg(1)->getBeginLoc(),
6264          diag::warn_second_arg_of_va_start_not_last_named_param);
6265   else if (IsCRegister || Type->isReferenceType() ||
6266            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6267              // Promotable integers are UB, but enumerations need a bit of
6268              // extra checking to see what their promotable type actually is.
6269              if (!Type->isPromotableIntegerType())
6270                return false;
6271              if (!Type->isEnumeralType())
6272                return true;
6273              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6274              return !(ED &&
6275                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6276            }()) {
6277     unsigned Reason = 0;
6278     if (Type->isReferenceType())  Reason = 1;
6279     else if (IsCRegister)         Reason = 2;
6280     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6281     Diag(ParamLoc, diag::note_parameter_type) << Type;
6282   }
6283 
6284   TheCall->setType(Context.VoidTy);
6285   return false;
6286 }
6287 
SemaBuiltinVAStartARMMicrosoft(CallExpr * Call)6288 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6289   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6290   //                 const char *named_addr);
6291 
6292   Expr *Func = Call->getCallee();
6293 
6294   if (Call->getNumArgs() < 3)
6295     return Diag(Call->getEndLoc(),
6296                 diag::err_typecheck_call_too_few_args_at_least)
6297            << 0 /*function call*/ << 3 << Call->getNumArgs();
6298 
6299   // Type-check the first argument normally.
6300   if (checkBuiltinArgument(*this, Call, 0))
6301     return true;
6302 
6303   // Check that the current function is variadic.
6304   if (checkVAStartIsInVariadicFunction(*this, Func))
6305     return true;
6306 
6307   // __va_start on Windows does not validate the parameter qualifiers
6308 
6309   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6310   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6311 
6312   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6313   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6314 
6315   const QualType &ConstCharPtrTy =
6316       Context.getPointerType(Context.CharTy.withConst());
6317   if (!Arg1Ty->isPointerType() ||
6318       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6319     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6320         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6321         << 0                                      /* qualifier difference */
6322         << 3                                      /* parameter mismatch */
6323         << 2 << Arg1->getType() << ConstCharPtrTy;
6324 
6325   const QualType SizeTy = Context.getSizeType();
6326   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6327     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6328         << Arg2->getType() << SizeTy << 1 /* different class */
6329         << 0                              /* qualifier difference */
6330         << 3                              /* parameter mismatch */
6331         << 3 << Arg2->getType() << SizeTy;
6332 
6333   return false;
6334 }
6335 
6336 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6337 /// friends.  This is declared to take (...), so we have to check everything.
SemaBuiltinUnorderedCompare(CallExpr * TheCall)6338 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6339   if (checkArgCount(*this, TheCall, 2))
6340     return true;
6341 
6342   ExprResult OrigArg0 = TheCall->getArg(0);
6343   ExprResult OrigArg1 = TheCall->getArg(1);
6344 
6345   // Do standard promotions between the two arguments, returning their common
6346   // type.
6347   QualType Res = UsualArithmeticConversions(
6348       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6349   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6350     return true;
6351 
6352   // Make sure any conversions are pushed back into the call; this is
6353   // type safe since unordered compare builtins are declared as "_Bool
6354   // foo(...)".
6355   TheCall->setArg(0, OrigArg0.get());
6356   TheCall->setArg(1, OrigArg1.get());
6357 
6358   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6359     return false;
6360 
6361   // If the common type isn't a real floating type, then the arguments were
6362   // invalid for this operation.
6363   if (Res.isNull() || !Res->isRealFloatingType())
6364     return Diag(OrigArg0.get()->getBeginLoc(),
6365                 diag::err_typecheck_call_invalid_ordered_compare)
6366            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6367            << SourceRange(OrigArg0.get()->getBeginLoc(),
6368                           OrigArg1.get()->getEndLoc());
6369 
6370   return false;
6371 }
6372 
6373 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6374 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6375 /// to check everything. We expect the last argument to be a floating point
6376 /// value.
SemaBuiltinFPClassification(CallExpr * TheCall,unsigned NumArgs)6377 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6378   if (checkArgCount(*this, TheCall, NumArgs))
6379     return true;
6380 
6381   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6382   // on all preceding parameters just being int.  Try all of those.
6383   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6384     Expr *Arg = TheCall->getArg(i);
6385 
6386     if (Arg->isTypeDependent())
6387       return false;
6388 
6389     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6390 
6391     if (Res.isInvalid())
6392       return true;
6393     TheCall->setArg(i, Res.get());
6394   }
6395 
6396   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6397 
6398   if (OrigArg->isTypeDependent())
6399     return false;
6400 
6401   // Usual Unary Conversions will convert half to float, which we want for
6402   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6403   // type how it is, but do normal L->Rvalue conversions.
6404   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6405     OrigArg = UsualUnaryConversions(OrigArg).get();
6406   else
6407     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6408   TheCall->setArg(NumArgs - 1, OrigArg);
6409 
6410   // This operation requires a non-_Complex floating-point number.
6411   if (!OrigArg->getType()->isRealFloatingType())
6412     return Diag(OrigArg->getBeginLoc(),
6413                 diag::err_typecheck_call_invalid_unary_fp)
6414            << OrigArg->getType() << OrigArg->getSourceRange();
6415 
6416   return false;
6417 }
6418 
6419 /// Perform semantic analysis for a call to __builtin_complex.
SemaBuiltinComplex(CallExpr * TheCall)6420 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6421   if (checkArgCount(*this, TheCall, 2))
6422     return true;
6423 
6424   bool Dependent = false;
6425   for (unsigned I = 0; I != 2; ++I) {
6426     Expr *Arg = TheCall->getArg(I);
6427     QualType T = Arg->getType();
6428     if (T->isDependentType()) {
6429       Dependent = true;
6430       continue;
6431     }
6432 
6433     // Despite supporting _Complex int, GCC requires a real floating point type
6434     // for the operands of __builtin_complex.
6435     if (!T->isRealFloatingType()) {
6436       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6437              << Arg->getType() << Arg->getSourceRange();
6438     }
6439 
6440     ExprResult Converted = DefaultLvalueConversion(Arg);
6441     if (Converted.isInvalid())
6442       return true;
6443     TheCall->setArg(I, Converted.get());
6444   }
6445 
6446   if (Dependent) {
6447     TheCall->setType(Context.DependentTy);
6448     return false;
6449   }
6450 
6451   Expr *Real = TheCall->getArg(0);
6452   Expr *Imag = TheCall->getArg(1);
6453   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6454     return Diag(Real->getBeginLoc(),
6455                 diag::err_typecheck_call_different_arg_types)
6456            << Real->getType() << Imag->getType()
6457            << Real->getSourceRange() << Imag->getSourceRange();
6458   }
6459 
6460   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6461   // don't allow this builtin to form those types either.
6462   // FIXME: Should we allow these types?
6463   if (Real->getType()->isFloat16Type())
6464     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6465            << "_Float16";
6466   if (Real->getType()->isHalfType())
6467     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6468            << "half";
6469 
6470   TheCall->setType(Context.getComplexType(Real->getType()));
6471   return false;
6472 }
6473 
6474 // Customized Sema Checking for VSX builtins that have the following signature:
6475 // vector [...] builtinName(vector [...], vector [...], const int);
6476 // Which takes the same type of vectors (any legal vector type) for the first
6477 // two arguments and takes compile time constant for the third argument.
6478 // Example builtins are :
6479 // vector double vec_xxpermdi(vector double, vector double, int);
6480 // vector short vec_xxsldwi(vector short, vector short, int);
SemaBuiltinVSX(CallExpr * TheCall)6481 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6482   unsigned ExpectedNumArgs = 3;
6483   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6484     return true;
6485 
6486   // Check the third argument is a compile time constant
6487   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6488     return Diag(TheCall->getBeginLoc(),
6489                 diag::err_vsx_builtin_nonconstant_argument)
6490            << 3 /* argument index */ << TheCall->getDirectCallee()
6491            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6492                           TheCall->getArg(2)->getEndLoc());
6493 
6494   QualType Arg1Ty = TheCall->getArg(0)->getType();
6495   QualType Arg2Ty = TheCall->getArg(1)->getType();
6496 
6497   // Check the type of argument 1 and argument 2 are vectors.
6498   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6499   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6500       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6501     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6502            << TheCall->getDirectCallee()
6503            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6504                           TheCall->getArg(1)->getEndLoc());
6505   }
6506 
6507   // Check the first two arguments are the same type.
6508   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6509     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6510            << TheCall->getDirectCallee()
6511            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6512                           TheCall->getArg(1)->getEndLoc());
6513   }
6514 
6515   // When default clang type checking is turned off and the customized type
6516   // checking is used, the returning type of the function must be explicitly
6517   // set. Otherwise it is _Bool by default.
6518   TheCall->setType(Arg1Ty);
6519 
6520   return false;
6521 }
6522 
6523 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6524 // This is declared to take (...), so we have to check everything.
SemaBuiltinShuffleVector(CallExpr * TheCall)6525 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6526   if (TheCall->getNumArgs() < 2)
6527     return ExprError(Diag(TheCall->getEndLoc(),
6528                           diag::err_typecheck_call_too_few_args_at_least)
6529                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6530                      << TheCall->getSourceRange());
6531 
6532   // Determine which of the following types of shufflevector we're checking:
6533   // 1) unary, vector mask: (lhs, mask)
6534   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6535   QualType resType = TheCall->getArg(0)->getType();
6536   unsigned numElements = 0;
6537 
6538   if (!TheCall->getArg(0)->isTypeDependent() &&
6539       !TheCall->getArg(1)->isTypeDependent()) {
6540     QualType LHSType = TheCall->getArg(0)->getType();
6541     QualType RHSType = TheCall->getArg(1)->getType();
6542 
6543     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6544       return ExprError(
6545           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6546           << TheCall->getDirectCallee()
6547           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6548                          TheCall->getArg(1)->getEndLoc()));
6549 
6550     numElements = LHSType->castAs<VectorType>()->getNumElements();
6551     unsigned numResElements = TheCall->getNumArgs() - 2;
6552 
6553     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6554     // with mask.  If so, verify that RHS is an integer vector type with the
6555     // same number of elts as lhs.
6556     if (TheCall->getNumArgs() == 2) {
6557       if (!RHSType->hasIntegerRepresentation() ||
6558           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6559         return ExprError(Diag(TheCall->getBeginLoc(),
6560                               diag::err_vec_builtin_incompatible_vector)
6561                          << TheCall->getDirectCallee()
6562                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6563                                         TheCall->getArg(1)->getEndLoc()));
6564     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6565       return ExprError(Diag(TheCall->getBeginLoc(),
6566                             diag::err_vec_builtin_incompatible_vector)
6567                        << TheCall->getDirectCallee()
6568                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6569                                       TheCall->getArg(1)->getEndLoc()));
6570     } else if (numElements != numResElements) {
6571       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6572       resType = Context.getVectorType(eltType, numResElements,
6573                                       VectorType::GenericVector);
6574     }
6575   }
6576 
6577   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6578     if (TheCall->getArg(i)->isTypeDependent() ||
6579         TheCall->getArg(i)->isValueDependent())
6580       continue;
6581 
6582     Optional<llvm::APSInt> Result;
6583     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6584       return ExprError(Diag(TheCall->getBeginLoc(),
6585                             diag::err_shufflevector_nonconstant_argument)
6586                        << TheCall->getArg(i)->getSourceRange());
6587 
6588     // Allow -1 which will be translated to undef in the IR.
6589     if (Result->isSigned() && Result->isAllOnesValue())
6590       continue;
6591 
6592     if (Result->getActiveBits() > 64 ||
6593         Result->getZExtValue() >= numElements * 2)
6594       return ExprError(Diag(TheCall->getBeginLoc(),
6595                             diag::err_shufflevector_argument_too_large)
6596                        << TheCall->getArg(i)->getSourceRange());
6597   }
6598 
6599   SmallVector<Expr*, 32> exprs;
6600 
6601   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6602     exprs.push_back(TheCall->getArg(i));
6603     TheCall->setArg(i, nullptr);
6604   }
6605 
6606   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6607                                          TheCall->getCallee()->getBeginLoc(),
6608                                          TheCall->getRParenLoc());
6609 }
6610 
6611 /// SemaConvertVectorExpr - Handle __builtin_convertvector
SemaConvertVectorExpr(Expr * E,TypeSourceInfo * TInfo,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6612 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6613                                        SourceLocation BuiltinLoc,
6614                                        SourceLocation RParenLoc) {
6615   ExprValueKind VK = VK_PRValue;
6616   ExprObjectKind OK = OK_Ordinary;
6617   QualType DstTy = TInfo->getType();
6618   QualType SrcTy = E->getType();
6619 
6620   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6621     return ExprError(Diag(BuiltinLoc,
6622                           diag::err_convertvector_non_vector)
6623                      << E->getSourceRange());
6624   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6625     return ExprError(Diag(BuiltinLoc,
6626                           diag::err_convertvector_non_vector_type));
6627 
6628   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6629     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6630     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6631     if (SrcElts != DstElts)
6632       return ExprError(Diag(BuiltinLoc,
6633                             diag::err_convertvector_incompatible_vector)
6634                        << E->getSourceRange());
6635   }
6636 
6637   return new (Context)
6638       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6639 }
6640 
6641 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6642 // This is declared to take (const void*, ...) and can take two
6643 // optional constant int args.
SemaBuiltinPrefetch(CallExpr * TheCall)6644 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6645   unsigned NumArgs = TheCall->getNumArgs();
6646 
6647   if (NumArgs > 3)
6648     return Diag(TheCall->getEndLoc(),
6649                 diag::err_typecheck_call_too_many_args_at_most)
6650            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6651 
6652   // Argument 0 is checked for us and the remaining arguments must be
6653   // constant integers.
6654   for (unsigned i = 1; i != NumArgs; ++i)
6655     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6656       return true;
6657 
6658   return false;
6659 }
6660 
6661 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
SemaBuiltinArithmeticFence(CallExpr * TheCall)6662 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6663   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6664     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6665            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6666   if (checkArgCount(*this, TheCall, 1))
6667     return true;
6668   Expr *Arg = TheCall->getArg(0);
6669   if (Arg->isInstantiationDependent())
6670     return false;
6671 
6672   QualType ArgTy = Arg->getType();
6673   if (!ArgTy->hasFloatingRepresentation())
6674     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6675            << ArgTy;
6676   if (Arg->isLValue()) {
6677     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6678     TheCall->setArg(0, FirstArg.get());
6679   }
6680   TheCall->setType(TheCall->getArg(0)->getType());
6681   return false;
6682 }
6683 
6684 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6685 // __assume does not evaluate its arguments, and should warn if its argument
6686 // has side effects.
SemaBuiltinAssume(CallExpr * TheCall)6687 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6688   Expr *Arg = TheCall->getArg(0);
6689   if (Arg->isInstantiationDependent()) return false;
6690 
6691   if (Arg->HasSideEffects(Context))
6692     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6693         << Arg->getSourceRange()
6694         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6695 
6696   return false;
6697 }
6698 
6699 /// Handle __builtin_alloca_with_align. This is declared
6700 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6701 /// than 8.
SemaBuiltinAllocaWithAlign(CallExpr * TheCall)6702 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6703   // The alignment must be a constant integer.
6704   Expr *Arg = TheCall->getArg(1);
6705 
6706   // We can't check the value of a dependent argument.
6707   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6708     if (const auto *UE =
6709             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6710       if (UE->getKind() == UETT_AlignOf ||
6711           UE->getKind() == UETT_PreferredAlignOf)
6712         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6713             << Arg->getSourceRange();
6714 
6715     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6716 
6717     if (!Result.isPowerOf2())
6718       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6719              << Arg->getSourceRange();
6720 
6721     if (Result < Context.getCharWidth())
6722       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6723              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6724 
6725     if (Result > std::numeric_limits<int32_t>::max())
6726       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6727              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6728   }
6729 
6730   return false;
6731 }
6732 
6733 /// Handle __builtin_assume_aligned. This is declared
6734 /// as (const void*, size_t, ...) and can take one optional constant int arg.
SemaBuiltinAssumeAligned(CallExpr * TheCall)6735 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6736   unsigned NumArgs = TheCall->getNumArgs();
6737 
6738   if (NumArgs > 3)
6739     return Diag(TheCall->getEndLoc(),
6740                 diag::err_typecheck_call_too_many_args_at_most)
6741            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6742 
6743   // The alignment must be a constant integer.
6744   Expr *Arg = TheCall->getArg(1);
6745 
6746   // We can't check the value of a dependent argument.
6747   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6748     llvm::APSInt Result;
6749     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6750       return true;
6751 
6752     if (!Result.isPowerOf2())
6753       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6754              << Arg->getSourceRange();
6755 
6756     if (Result > Sema::MaximumAlignment)
6757       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6758           << Arg->getSourceRange() << Sema::MaximumAlignment;
6759   }
6760 
6761   if (NumArgs > 2) {
6762     ExprResult Arg(TheCall->getArg(2));
6763     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6764       Context.getSizeType(), false);
6765     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6766     if (Arg.isInvalid()) return true;
6767     TheCall->setArg(2, Arg.get());
6768   }
6769 
6770   return false;
6771 }
6772 
SemaBuiltinOSLogFormat(CallExpr * TheCall)6773 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6774   unsigned BuiltinID =
6775       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6776   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6777 
6778   unsigned NumArgs = TheCall->getNumArgs();
6779   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6780   if (NumArgs < NumRequiredArgs) {
6781     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6782            << 0 /* function call */ << NumRequiredArgs << NumArgs
6783            << TheCall->getSourceRange();
6784   }
6785   if (NumArgs >= NumRequiredArgs + 0x100) {
6786     return Diag(TheCall->getEndLoc(),
6787                 diag::err_typecheck_call_too_many_args_at_most)
6788            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6789            << TheCall->getSourceRange();
6790   }
6791   unsigned i = 0;
6792 
6793   // For formatting call, check buffer arg.
6794   if (!IsSizeCall) {
6795     ExprResult Arg(TheCall->getArg(i));
6796     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6797         Context, Context.VoidPtrTy, false);
6798     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6799     if (Arg.isInvalid())
6800       return true;
6801     TheCall->setArg(i, Arg.get());
6802     i++;
6803   }
6804 
6805   // Check string literal arg.
6806   unsigned FormatIdx = i;
6807   {
6808     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6809     if (Arg.isInvalid())
6810       return true;
6811     TheCall->setArg(i, Arg.get());
6812     i++;
6813   }
6814 
6815   // Make sure variadic args are scalar.
6816   unsigned FirstDataArg = i;
6817   while (i < NumArgs) {
6818     ExprResult Arg = DefaultVariadicArgumentPromotion(
6819         TheCall->getArg(i), VariadicFunction, nullptr);
6820     if (Arg.isInvalid())
6821       return true;
6822     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6823     if (ArgSize.getQuantity() >= 0x100) {
6824       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6825              << i << (int)ArgSize.getQuantity() << 0xff
6826              << TheCall->getSourceRange();
6827     }
6828     TheCall->setArg(i, Arg.get());
6829     i++;
6830   }
6831 
6832   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6833   // call to avoid duplicate diagnostics.
6834   if (!IsSizeCall) {
6835     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6836     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6837     bool Success = CheckFormatArguments(
6838         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6839         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6840         CheckedVarArgs);
6841     if (!Success)
6842       return true;
6843   }
6844 
6845   if (IsSizeCall) {
6846     TheCall->setType(Context.getSizeType());
6847   } else {
6848     TheCall->setType(Context.VoidPtrTy);
6849   }
6850   return false;
6851 }
6852 
6853 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6854 /// TheCall is a constant expression.
SemaBuiltinConstantArg(CallExpr * TheCall,int ArgNum,llvm::APSInt & Result)6855 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6856                                   llvm::APSInt &Result) {
6857   Expr *Arg = TheCall->getArg(ArgNum);
6858   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6859   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6860 
6861   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6862 
6863   Optional<llvm::APSInt> R;
6864   if (!(R = Arg->getIntegerConstantExpr(Context)))
6865     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6866            << FDecl->getDeclName() << Arg->getSourceRange();
6867   Result = *R;
6868   return false;
6869 }
6870 
6871 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6872 /// TheCall is a constant expression in the range [Low, High].
SemaBuiltinConstantArgRange(CallExpr * TheCall,int ArgNum,int Low,int High,bool RangeIsError)6873 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6874                                        int Low, int High, bool RangeIsError) {
6875   if (isConstantEvaluated())
6876     return false;
6877   llvm::APSInt Result;
6878 
6879   // We can't check the value of a dependent argument.
6880   Expr *Arg = TheCall->getArg(ArgNum);
6881   if (Arg->isTypeDependent() || Arg->isValueDependent())
6882     return false;
6883 
6884   // Check constant-ness first.
6885   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6886     return true;
6887 
6888   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6889     if (RangeIsError)
6890       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6891              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6892     else
6893       // Defer the warning until we know if the code will be emitted so that
6894       // dead code can ignore this.
6895       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6896                           PDiag(diag::warn_argument_invalid_range)
6897                               << toString(Result, 10) << Low << High
6898                               << Arg->getSourceRange());
6899   }
6900 
6901   return false;
6902 }
6903 
6904 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6905 /// TheCall is a constant expression is a multiple of Num..
SemaBuiltinConstantArgMultiple(CallExpr * TheCall,int ArgNum,unsigned Num)6906 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6907                                           unsigned Num) {
6908   llvm::APSInt Result;
6909 
6910   // We can't check the value of a dependent argument.
6911   Expr *Arg = TheCall->getArg(ArgNum);
6912   if (Arg->isTypeDependent() || Arg->isValueDependent())
6913     return false;
6914 
6915   // Check constant-ness first.
6916   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6917     return true;
6918 
6919   if (Result.getSExtValue() % Num != 0)
6920     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6921            << Num << Arg->getSourceRange();
6922 
6923   return false;
6924 }
6925 
6926 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6927 /// constant expression representing a power of 2.
SemaBuiltinConstantArgPower2(CallExpr * TheCall,int ArgNum)6928 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6929   llvm::APSInt Result;
6930 
6931   // We can't check the value of a dependent argument.
6932   Expr *Arg = TheCall->getArg(ArgNum);
6933   if (Arg->isTypeDependent() || Arg->isValueDependent())
6934     return false;
6935 
6936   // Check constant-ness first.
6937   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6938     return true;
6939 
6940   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6941   // and only if x is a power of 2.
6942   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6943     return false;
6944 
6945   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6946          << Arg->getSourceRange();
6947 }
6948 
IsShiftedByte(llvm::APSInt Value)6949 static bool IsShiftedByte(llvm::APSInt Value) {
6950   if (Value.isNegative())
6951     return false;
6952 
6953   // Check if it's a shifted byte, by shifting it down
6954   while (true) {
6955     // If the value fits in the bottom byte, the check passes.
6956     if (Value < 0x100)
6957       return true;
6958 
6959     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6960     // fails.
6961     if ((Value & 0xFF) != 0)
6962       return false;
6963 
6964     // If the bottom 8 bits are all 0, but something above that is nonzero,
6965     // then shifting the value right by 8 bits won't affect whether it's a
6966     // shifted byte or not. So do that, and go round again.
6967     Value >>= 8;
6968   }
6969 }
6970 
6971 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6972 /// a constant expression representing an arbitrary byte value shifted left by
6973 /// a multiple of 8 bits.
SemaBuiltinConstantArgShiftedByte(CallExpr * TheCall,int ArgNum,unsigned ArgBits)6974 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6975                                              unsigned ArgBits) {
6976   llvm::APSInt Result;
6977 
6978   // We can't check the value of a dependent argument.
6979   Expr *Arg = TheCall->getArg(ArgNum);
6980   if (Arg->isTypeDependent() || Arg->isValueDependent())
6981     return false;
6982 
6983   // Check constant-ness first.
6984   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6985     return true;
6986 
6987   // Truncate to the given size.
6988   Result = Result.getLoBits(ArgBits);
6989   Result.setIsUnsigned(true);
6990 
6991   if (IsShiftedByte(Result))
6992     return false;
6993 
6994   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6995          << Arg->getSourceRange();
6996 }
6997 
6998 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6999 /// TheCall is a constant expression representing either a shifted byte value,
7000 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7001 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7002 /// Arm MVE intrinsics.
SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr * TheCall,int ArgNum,unsigned ArgBits)7003 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7004                                                    int ArgNum,
7005                                                    unsigned ArgBits) {
7006   llvm::APSInt Result;
7007 
7008   // We can't check the value of a dependent argument.
7009   Expr *Arg = TheCall->getArg(ArgNum);
7010   if (Arg->isTypeDependent() || Arg->isValueDependent())
7011     return false;
7012 
7013   // Check constant-ness first.
7014   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7015     return true;
7016 
7017   // Truncate to the given size.
7018   Result = Result.getLoBits(ArgBits);
7019   Result.setIsUnsigned(true);
7020 
7021   // Check to see if it's in either of the required forms.
7022   if (IsShiftedByte(Result) ||
7023       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7024     return false;
7025 
7026   return Diag(TheCall->getBeginLoc(),
7027               diag::err_argument_not_shifted_byte_or_xxff)
7028          << Arg->getSourceRange();
7029 }
7030 
7031 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID,CallExpr * TheCall)7032 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7033   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7034     if (checkArgCount(*this, TheCall, 2))
7035       return true;
7036     Expr *Arg0 = TheCall->getArg(0);
7037     Expr *Arg1 = TheCall->getArg(1);
7038 
7039     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7040     if (FirstArg.isInvalid())
7041       return true;
7042     QualType FirstArgType = FirstArg.get()->getType();
7043     if (!FirstArgType->isAnyPointerType())
7044       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7045                << "first" << FirstArgType << Arg0->getSourceRange();
7046     TheCall->setArg(0, FirstArg.get());
7047 
7048     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7049     if (SecArg.isInvalid())
7050       return true;
7051     QualType SecArgType = SecArg.get()->getType();
7052     if (!SecArgType->isIntegerType())
7053       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7054                << "second" << SecArgType << Arg1->getSourceRange();
7055 
7056     // Derive the return type from the pointer argument.
7057     TheCall->setType(FirstArgType);
7058     return false;
7059   }
7060 
7061   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7062     if (checkArgCount(*this, TheCall, 2))
7063       return true;
7064 
7065     Expr *Arg0 = TheCall->getArg(0);
7066     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7067     if (FirstArg.isInvalid())
7068       return true;
7069     QualType FirstArgType = FirstArg.get()->getType();
7070     if (!FirstArgType->isAnyPointerType())
7071       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7072                << "first" << FirstArgType << Arg0->getSourceRange();
7073     TheCall->setArg(0, FirstArg.get());
7074 
7075     // Derive the return type from the pointer argument.
7076     TheCall->setType(FirstArgType);
7077 
7078     // Second arg must be an constant in range [0,15]
7079     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7080   }
7081 
7082   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7083     if (checkArgCount(*this, TheCall, 2))
7084       return true;
7085     Expr *Arg0 = TheCall->getArg(0);
7086     Expr *Arg1 = TheCall->getArg(1);
7087 
7088     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7089     if (FirstArg.isInvalid())
7090       return true;
7091     QualType FirstArgType = FirstArg.get()->getType();
7092     if (!FirstArgType->isAnyPointerType())
7093       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7094                << "first" << FirstArgType << Arg0->getSourceRange();
7095 
7096     QualType SecArgType = Arg1->getType();
7097     if (!SecArgType->isIntegerType())
7098       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7099                << "second" << SecArgType << Arg1->getSourceRange();
7100     TheCall->setType(Context.IntTy);
7101     return false;
7102   }
7103 
7104   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7105       BuiltinID == AArch64::BI__builtin_arm_stg) {
7106     if (checkArgCount(*this, TheCall, 1))
7107       return true;
7108     Expr *Arg0 = TheCall->getArg(0);
7109     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7110     if (FirstArg.isInvalid())
7111       return true;
7112 
7113     QualType FirstArgType = FirstArg.get()->getType();
7114     if (!FirstArgType->isAnyPointerType())
7115       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7116                << "first" << FirstArgType << Arg0->getSourceRange();
7117     TheCall->setArg(0, FirstArg.get());
7118 
7119     // Derive the return type from the pointer argument.
7120     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7121       TheCall->setType(FirstArgType);
7122     return false;
7123   }
7124 
7125   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7126     Expr *ArgA = TheCall->getArg(0);
7127     Expr *ArgB = TheCall->getArg(1);
7128 
7129     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7130     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7131 
7132     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7133       return true;
7134 
7135     QualType ArgTypeA = ArgExprA.get()->getType();
7136     QualType ArgTypeB = ArgExprB.get()->getType();
7137 
7138     auto isNull = [&] (Expr *E) -> bool {
7139       return E->isNullPointerConstant(
7140                         Context, Expr::NPC_ValueDependentIsNotNull); };
7141 
7142     // argument should be either a pointer or null
7143     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7144       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7145         << "first" << ArgTypeA << ArgA->getSourceRange();
7146 
7147     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7148       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7149         << "second" << ArgTypeB << ArgB->getSourceRange();
7150 
7151     // Ensure Pointee types are compatible
7152     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7153         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7154       QualType pointeeA = ArgTypeA->getPointeeType();
7155       QualType pointeeB = ArgTypeB->getPointeeType();
7156       if (!Context.typesAreCompatible(
7157              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7158              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7159         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7160           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7161           << ArgB->getSourceRange();
7162       }
7163     }
7164 
7165     // at least one argument should be pointer type
7166     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7167       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7168         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7169 
7170     if (isNull(ArgA)) // adopt type of the other pointer
7171       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7172 
7173     if (isNull(ArgB))
7174       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7175 
7176     TheCall->setArg(0, ArgExprA.get());
7177     TheCall->setArg(1, ArgExprB.get());
7178     TheCall->setType(Context.LongLongTy);
7179     return false;
7180   }
7181   assert(false && "Unhandled ARM MTE intrinsic");
7182   return true;
7183 }
7184 
7185 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7186 /// TheCall is an ARM/AArch64 special register string literal.
SemaBuiltinARMSpecialReg(unsigned BuiltinID,CallExpr * TheCall,int ArgNum,unsigned ExpectedFieldNum,bool AllowName)7187 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7188                                     int ArgNum, unsigned ExpectedFieldNum,
7189                                     bool AllowName) {
7190   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7191                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7192                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7193                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7194                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7195                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7196   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7197                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7198                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7199                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7200                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7201                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7202   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7203 
7204   // We can't check the value of a dependent argument.
7205   Expr *Arg = TheCall->getArg(ArgNum);
7206   if (Arg->isTypeDependent() || Arg->isValueDependent())
7207     return false;
7208 
7209   // Check if the argument is a string literal.
7210   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7211     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7212            << Arg->getSourceRange();
7213 
7214   // Check the type of special register given.
7215   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7216   SmallVector<StringRef, 6> Fields;
7217   Reg.split(Fields, ":");
7218 
7219   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7220     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7221            << Arg->getSourceRange();
7222 
7223   // If the string is the name of a register then we cannot check that it is
7224   // valid here but if the string is of one the forms described in ACLE then we
7225   // can check that the supplied fields are integers and within the valid
7226   // ranges.
7227   if (Fields.size() > 1) {
7228     bool FiveFields = Fields.size() == 5;
7229 
7230     bool ValidString = true;
7231     if (IsARMBuiltin) {
7232       ValidString &= Fields[0].startswith_insensitive("cp") ||
7233                      Fields[0].startswith_insensitive("p");
7234       if (ValidString)
7235         Fields[0] = Fields[0].drop_front(
7236             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7237 
7238       ValidString &= Fields[2].startswith_insensitive("c");
7239       if (ValidString)
7240         Fields[2] = Fields[2].drop_front(1);
7241 
7242       if (FiveFields) {
7243         ValidString &= Fields[3].startswith_insensitive("c");
7244         if (ValidString)
7245           Fields[3] = Fields[3].drop_front(1);
7246       }
7247     }
7248 
7249     SmallVector<int, 5> Ranges;
7250     if (FiveFields)
7251       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7252     else
7253       Ranges.append({15, 7, 15});
7254 
7255     for (unsigned i=0; i<Fields.size(); ++i) {
7256       int IntField;
7257       ValidString &= !Fields[i].getAsInteger(10, IntField);
7258       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7259     }
7260 
7261     if (!ValidString)
7262       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7263              << Arg->getSourceRange();
7264   } else if (IsAArch64Builtin && Fields.size() == 1) {
7265     // If the register name is one of those that appear in the condition below
7266     // and the special register builtin being used is one of the write builtins,
7267     // then we require that the argument provided for writing to the register
7268     // is an integer constant expression. This is because it will be lowered to
7269     // an MSR (immediate) instruction, so we need to know the immediate at
7270     // compile time.
7271     if (TheCall->getNumArgs() != 2)
7272       return false;
7273 
7274     std::string RegLower = Reg.lower();
7275     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7276         RegLower != "pan" && RegLower != "uao")
7277       return false;
7278 
7279     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7280   }
7281 
7282   return false;
7283 }
7284 
7285 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7286 /// Emit an error and return true on failure; return false on success.
7287 /// TypeStr is a string containing the type descriptor of the value returned by
7288 /// the builtin and the descriptors of the expected type of the arguments.
SemaBuiltinPPCMMACall(CallExpr * TheCall,const char * TypeStr)7289 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7290 
7291   assert((TypeStr[0] != '\0') &&
7292          "Invalid types in PPC MMA builtin declaration");
7293 
7294   unsigned Mask = 0;
7295   unsigned ArgNum = 0;
7296 
7297   // The first type in TypeStr is the type of the value returned by the
7298   // builtin. So we first read that type and change the type of TheCall.
7299   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7300   TheCall->setType(type);
7301 
7302   while (*TypeStr != '\0') {
7303     Mask = 0;
7304     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7305     if (ArgNum >= TheCall->getNumArgs()) {
7306       ArgNum++;
7307       break;
7308     }
7309 
7310     Expr *Arg = TheCall->getArg(ArgNum);
7311     QualType ArgType = Arg->getType();
7312 
7313     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7314         (!ExpectedType->isVoidPointerType() &&
7315            ArgType.getCanonicalType() != ExpectedType))
7316       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7317              << ArgType << ExpectedType << 1 << 0 << 0;
7318 
7319     // If the value of the Mask is not 0, we have a constraint in the size of
7320     // the integer argument so here we ensure the argument is a constant that
7321     // is in the valid range.
7322     if (Mask != 0 &&
7323         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7324       return true;
7325 
7326     ArgNum++;
7327   }
7328 
7329   // In case we exited early from the previous loop, there are other types to
7330   // read from TypeStr. So we need to read them all to ensure we have the right
7331   // number of arguments in TheCall and if it is not the case, to display a
7332   // better error message.
7333   while (*TypeStr != '\0') {
7334     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7335     ArgNum++;
7336   }
7337   if (checkArgCount(*this, TheCall, ArgNum))
7338     return true;
7339 
7340   return false;
7341 }
7342 
7343 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7344 /// This checks that the target supports __builtin_longjmp and
7345 /// that val is a constant 1.
SemaBuiltinLongjmp(CallExpr * TheCall)7346 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7347   if (!Context.getTargetInfo().hasSjLjLowering())
7348     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7349            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7350 
7351   Expr *Arg = TheCall->getArg(1);
7352   llvm::APSInt Result;
7353 
7354   // TODO: This is less than ideal. Overload this to take a value.
7355   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7356     return true;
7357 
7358   if (Result != 1)
7359     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7360            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7361 
7362   return false;
7363 }
7364 
7365 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7366 /// This checks that the target supports __builtin_setjmp.
SemaBuiltinSetjmp(CallExpr * TheCall)7367 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7368   if (!Context.getTargetInfo().hasSjLjLowering())
7369     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7370            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7371   return false;
7372 }
7373 
7374 namespace {
7375 
7376 class UncoveredArgHandler {
7377   enum { Unknown = -1, AllCovered = -2 };
7378 
7379   signed FirstUncoveredArg = Unknown;
7380   SmallVector<const Expr *, 4> DiagnosticExprs;
7381 
7382 public:
7383   UncoveredArgHandler() = default;
7384 
hasUncoveredArg() const7385   bool hasUncoveredArg() const {
7386     return (FirstUncoveredArg >= 0);
7387   }
7388 
getUncoveredArg() const7389   unsigned getUncoveredArg() const {
7390     assert(hasUncoveredArg() && "no uncovered argument");
7391     return FirstUncoveredArg;
7392   }
7393 
setAllCovered()7394   void setAllCovered() {
7395     // A string has been found with all arguments covered, so clear out
7396     // the diagnostics.
7397     DiagnosticExprs.clear();
7398     FirstUncoveredArg = AllCovered;
7399   }
7400 
Update(signed NewFirstUncoveredArg,const Expr * StrExpr)7401   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7402     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7403 
7404     // Don't update if a previous string covers all arguments.
7405     if (FirstUncoveredArg == AllCovered)
7406       return;
7407 
7408     // UncoveredArgHandler tracks the highest uncovered argument index
7409     // and with it all the strings that match this index.
7410     if (NewFirstUncoveredArg == FirstUncoveredArg)
7411       DiagnosticExprs.push_back(StrExpr);
7412     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7413       DiagnosticExprs.clear();
7414       DiagnosticExprs.push_back(StrExpr);
7415       FirstUncoveredArg = NewFirstUncoveredArg;
7416     }
7417   }
7418 
7419   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7420 };
7421 
7422 enum StringLiteralCheckType {
7423   SLCT_NotALiteral,
7424   SLCT_UncheckedLiteral,
7425   SLCT_CheckedLiteral
7426 };
7427 
7428 } // namespace
7429 
sumOffsets(llvm::APSInt & Offset,llvm::APSInt Addend,BinaryOperatorKind BinOpKind,bool AddendIsRight)7430 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7431                                      BinaryOperatorKind BinOpKind,
7432                                      bool AddendIsRight) {
7433   unsigned BitWidth = Offset.getBitWidth();
7434   unsigned AddendBitWidth = Addend.getBitWidth();
7435   // There might be negative interim results.
7436   if (Addend.isUnsigned()) {
7437     Addend = Addend.zext(++AddendBitWidth);
7438     Addend.setIsSigned(true);
7439   }
7440   // Adjust the bit width of the APSInts.
7441   if (AddendBitWidth > BitWidth) {
7442     Offset = Offset.sext(AddendBitWidth);
7443     BitWidth = AddendBitWidth;
7444   } else if (BitWidth > AddendBitWidth) {
7445     Addend = Addend.sext(BitWidth);
7446   }
7447 
7448   bool Ov = false;
7449   llvm::APSInt ResOffset = Offset;
7450   if (BinOpKind == BO_Add)
7451     ResOffset = Offset.sadd_ov(Addend, Ov);
7452   else {
7453     assert(AddendIsRight && BinOpKind == BO_Sub &&
7454            "operator must be add or sub with addend on the right");
7455     ResOffset = Offset.ssub_ov(Addend, Ov);
7456   }
7457 
7458   // We add an offset to a pointer here so we should support an offset as big as
7459   // possible.
7460   if (Ov) {
7461     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7462            "index (intermediate) result too big");
7463     Offset = Offset.sext(2 * BitWidth);
7464     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7465     return;
7466   }
7467 
7468   Offset = ResOffset;
7469 }
7470 
7471 namespace {
7472 
7473 // This is a wrapper class around StringLiteral to support offsetted string
7474 // literals as format strings. It takes the offset into account when returning
7475 // the string and its length or the source locations to display notes correctly.
7476 class FormatStringLiteral {
7477   const StringLiteral *FExpr;
7478   int64_t Offset;
7479 
7480  public:
FormatStringLiteral(const StringLiteral * fexpr,int64_t Offset=0)7481   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7482       : FExpr(fexpr), Offset(Offset) {}
7483 
getString() const7484   StringRef getString() const {
7485     return FExpr->getString().drop_front(Offset);
7486   }
7487 
getByteLength() const7488   unsigned getByteLength() const {
7489     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7490   }
7491 
getLength() const7492   unsigned getLength() const { return FExpr->getLength() - Offset; }
getCharByteWidth() const7493   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7494 
getKind() const7495   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7496 
getType() const7497   QualType getType() const { return FExpr->getType(); }
7498 
isAscii() const7499   bool isAscii() const { return FExpr->isAscii(); }
isWide() const7500   bool isWide() const { return FExpr->isWide(); }
isUTF8() const7501   bool isUTF8() const { return FExpr->isUTF8(); }
isUTF16() const7502   bool isUTF16() const { return FExpr->isUTF16(); }
isUTF32() const7503   bool isUTF32() const { return FExpr->isUTF32(); }
isPascal() const7504   bool isPascal() const { return FExpr->isPascal(); }
7505 
getLocationOfByte(unsigned ByteNo,const SourceManager & SM,const LangOptions & Features,const TargetInfo & Target,unsigned * StartToken=nullptr,unsigned * StartTokenByteOffset=nullptr) const7506   SourceLocation getLocationOfByte(
7507       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7508       const TargetInfo &Target, unsigned *StartToken = nullptr,
7509       unsigned *StartTokenByteOffset = nullptr) const {
7510     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7511                                     StartToken, StartTokenByteOffset);
7512   }
7513 
getBeginLoc() const7514   SourceLocation getBeginLoc() const LLVM_READONLY {
7515     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7516   }
7517 
getEndLoc() const7518   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7519 };
7520 
7521 }  // namespace
7522 
7523 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7524                               const Expr *OrigFormatExpr,
7525                               ArrayRef<const Expr *> Args,
7526                               bool HasVAListArg, unsigned format_idx,
7527                               unsigned firstDataArg,
7528                               Sema::FormatStringType Type,
7529                               bool inFunctionCall,
7530                               Sema::VariadicCallType CallType,
7531                               llvm::SmallBitVector &CheckedVarArgs,
7532                               UncoveredArgHandler &UncoveredArg,
7533                               bool IgnoreStringsWithoutSpecifiers);
7534 
7535 // Determine if an expression is a string literal or constant string.
7536 // If this function returns false on the arguments to a function expecting a
7537 // format string, we will usually need to emit a warning.
7538 // True string literals are then checked by CheckFormatString.
7539 static StringLiteralCheckType
checkFormatStringExpr(Sema & S,const Expr * E,ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,Sema::FormatStringType Type,Sema::VariadicCallType CallType,bool InFunctionCall,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg,llvm::APSInt Offset,bool IgnoreStringsWithoutSpecifiers=false)7540 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7541                       bool HasVAListArg, unsigned format_idx,
7542                       unsigned firstDataArg, Sema::FormatStringType Type,
7543                       Sema::VariadicCallType CallType, bool InFunctionCall,
7544                       llvm::SmallBitVector &CheckedVarArgs,
7545                       UncoveredArgHandler &UncoveredArg,
7546                       llvm::APSInt Offset,
7547                       bool IgnoreStringsWithoutSpecifiers = false) {
7548   if (S.isConstantEvaluated())
7549     return SLCT_NotALiteral;
7550  tryAgain:
7551   assert(Offset.isSigned() && "invalid offset");
7552 
7553   if (E->isTypeDependent() || E->isValueDependent())
7554     return SLCT_NotALiteral;
7555 
7556   E = E->IgnoreParenCasts();
7557 
7558   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7559     // Technically -Wformat-nonliteral does not warn about this case.
7560     // The behavior of printf and friends in this case is implementation
7561     // dependent.  Ideally if the format string cannot be null then
7562     // it should have a 'nonnull' attribute in the function prototype.
7563     return SLCT_UncheckedLiteral;
7564 
7565   switch (E->getStmtClass()) {
7566   case Stmt::BinaryConditionalOperatorClass:
7567   case Stmt::ConditionalOperatorClass: {
7568     // The expression is a literal if both sub-expressions were, and it was
7569     // completely checked only if both sub-expressions were checked.
7570     const AbstractConditionalOperator *C =
7571         cast<AbstractConditionalOperator>(E);
7572 
7573     // Determine whether it is necessary to check both sub-expressions, for
7574     // example, because the condition expression is a constant that can be
7575     // evaluated at compile time.
7576     bool CheckLeft = true, CheckRight = true;
7577 
7578     bool Cond;
7579     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7580                                                  S.isConstantEvaluated())) {
7581       if (Cond)
7582         CheckRight = false;
7583       else
7584         CheckLeft = false;
7585     }
7586 
7587     // We need to maintain the offsets for the right and the left hand side
7588     // separately to check if every possible indexed expression is a valid
7589     // string literal. They might have different offsets for different string
7590     // literals in the end.
7591     StringLiteralCheckType Left;
7592     if (!CheckLeft)
7593       Left = SLCT_UncheckedLiteral;
7594     else {
7595       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7596                                    HasVAListArg, format_idx, firstDataArg,
7597                                    Type, CallType, InFunctionCall,
7598                                    CheckedVarArgs, UncoveredArg, Offset,
7599                                    IgnoreStringsWithoutSpecifiers);
7600       if (Left == SLCT_NotALiteral || !CheckRight) {
7601         return Left;
7602       }
7603     }
7604 
7605     StringLiteralCheckType Right = checkFormatStringExpr(
7606         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7607         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7608         IgnoreStringsWithoutSpecifiers);
7609 
7610     return (CheckLeft && Left < Right) ? Left : Right;
7611   }
7612 
7613   case Stmt::ImplicitCastExprClass:
7614     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7615     goto tryAgain;
7616 
7617   case Stmt::OpaqueValueExprClass:
7618     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7619       E = src;
7620       goto tryAgain;
7621     }
7622     return SLCT_NotALiteral;
7623 
7624   case Stmt::PredefinedExprClass:
7625     // While __func__, etc., are technically not string literals, they
7626     // cannot contain format specifiers and thus are not a security
7627     // liability.
7628     return SLCT_UncheckedLiteral;
7629 
7630   case Stmt::DeclRefExprClass: {
7631     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7632 
7633     // As an exception, do not flag errors for variables binding to
7634     // const string literals.
7635     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7636       bool isConstant = false;
7637       QualType T = DR->getType();
7638 
7639       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7640         isConstant = AT->getElementType().isConstant(S.Context);
7641       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7642         isConstant = T.isConstant(S.Context) &&
7643                      PT->getPointeeType().isConstant(S.Context);
7644       } else if (T->isObjCObjectPointerType()) {
7645         // In ObjC, there is usually no "const ObjectPointer" type,
7646         // so don't check if the pointee type is constant.
7647         isConstant = T.isConstant(S.Context);
7648       }
7649 
7650       if (isConstant) {
7651         if (const Expr *Init = VD->getAnyInitializer()) {
7652           // Look through initializers like const char c[] = { "foo" }
7653           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7654             if (InitList->isStringLiteralInit())
7655               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7656           }
7657           return checkFormatStringExpr(S, Init, Args,
7658                                        HasVAListArg, format_idx,
7659                                        firstDataArg, Type, CallType,
7660                                        /*InFunctionCall*/ false, CheckedVarArgs,
7661                                        UncoveredArg, Offset);
7662         }
7663       }
7664 
7665       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7666       // special check to see if the format string is a function parameter
7667       // of the function calling the printf function.  If the function
7668       // has an attribute indicating it is a printf-like function, then we
7669       // should suppress warnings concerning non-literals being used in a call
7670       // to a vprintf function.  For example:
7671       //
7672       // void
7673       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7674       //      va_list ap;
7675       //      va_start(ap, fmt);
7676       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7677       //      ...
7678       // }
7679       if (HasVAListArg) {
7680         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7681           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7682             int PVIndex = PV->getFunctionScopeIndex() + 1;
7683             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7684               // adjust for implicit parameter
7685               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7686                 if (MD->isInstance())
7687                   ++PVIndex;
7688               // We also check if the formats are compatible.
7689               // We can't pass a 'scanf' string to a 'printf' function.
7690               if (PVIndex == PVFormat->getFormatIdx() &&
7691                   Type == S.GetFormatStringType(PVFormat))
7692                 return SLCT_UncheckedLiteral;
7693             }
7694           }
7695         }
7696       }
7697     }
7698 
7699     return SLCT_NotALiteral;
7700   }
7701 
7702   case Stmt::CallExprClass:
7703   case Stmt::CXXMemberCallExprClass: {
7704     const CallExpr *CE = cast<CallExpr>(E);
7705     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7706       bool IsFirst = true;
7707       StringLiteralCheckType CommonResult;
7708       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7709         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7710         StringLiteralCheckType Result = checkFormatStringExpr(
7711             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7712             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7713             IgnoreStringsWithoutSpecifiers);
7714         if (IsFirst) {
7715           CommonResult = Result;
7716           IsFirst = false;
7717         }
7718       }
7719       if (!IsFirst)
7720         return CommonResult;
7721 
7722       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7723         unsigned BuiltinID = FD->getBuiltinID();
7724         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7725             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7726           const Expr *Arg = CE->getArg(0);
7727           return checkFormatStringExpr(S, Arg, Args,
7728                                        HasVAListArg, format_idx,
7729                                        firstDataArg, Type, CallType,
7730                                        InFunctionCall, CheckedVarArgs,
7731                                        UncoveredArg, Offset,
7732                                        IgnoreStringsWithoutSpecifiers);
7733         }
7734       }
7735     }
7736 
7737     return SLCT_NotALiteral;
7738   }
7739   case Stmt::ObjCMessageExprClass: {
7740     const auto *ME = cast<ObjCMessageExpr>(E);
7741     if (const auto *MD = ME->getMethodDecl()) {
7742       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7743         // As a special case heuristic, if we're using the method -[NSBundle
7744         // localizedStringForKey:value:table:], ignore any key strings that lack
7745         // format specifiers. The idea is that if the key doesn't have any
7746         // format specifiers then its probably just a key to map to the
7747         // localized strings. If it does have format specifiers though, then its
7748         // likely that the text of the key is the format string in the
7749         // programmer's language, and should be checked.
7750         const ObjCInterfaceDecl *IFace;
7751         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7752             IFace->getIdentifier()->isStr("NSBundle") &&
7753             MD->getSelector().isKeywordSelector(
7754                 {"localizedStringForKey", "value", "table"})) {
7755           IgnoreStringsWithoutSpecifiers = true;
7756         }
7757 
7758         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7759         return checkFormatStringExpr(
7760             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7761             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7762             IgnoreStringsWithoutSpecifiers);
7763       }
7764     }
7765 
7766     return SLCT_NotALiteral;
7767   }
7768   case Stmt::ObjCStringLiteralClass:
7769   case Stmt::StringLiteralClass: {
7770     const StringLiteral *StrE = nullptr;
7771 
7772     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7773       StrE = ObjCFExpr->getString();
7774     else
7775       StrE = cast<StringLiteral>(E);
7776 
7777     if (StrE) {
7778       if (Offset.isNegative() || Offset > StrE->getLength()) {
7779         // TODO: It would be better to have an explicit warning for out of
7780         // bounds literals.
7781         return SLCT_NotALiteral;
7782       }
7783       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7784       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7785                         firstDataArg, Type, InFunctionCall, CallType,
7786                         CheckedVarArgs, UncoveredArg,
7787                         IgnoreStringsWithoutSpecifiers);
7788       return SLCT_CheckedLiteral;
7789     }
7790 
7791     return SLCT_NotALiteral;
7792   }
7793   case Stmt::BinaryOperatorClass: {
7794     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7795 
7796     // A string literal + an int offset is still a string literal.
7797     if (BinOp->isAdditiveOp()) {
7798       Expr::EvalResult LResult, RResult;
7799 
7800       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7801           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7802       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7803           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7804 
7805       if (LIsInt != RIsInt) {
7806         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7807 
7808         if (LIsInt) {
7809           if (BinOpKind == BO_Add) {
7810             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7811             E = BinOp->getRHS();
7812             goto tryAgain;
7813           }
7814         } else {
7815           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7816           E = BinOp->getLHS();
7817           goto tryAgain;
7818         }
7819       }
7820     }
7821 
7822     return SLCT_NotALiteral;
7823   }
7824   case Stmt::UnaryOperatorClass: {
7825     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7826     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7827     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7828       Expr::EvalResult IndexResult;
7829       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7830                                        Expr::SE_NoSideEffects,
7831                                        S.isConstantEvaluated())) {
7832         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7833                    /*RHS is int*/ true);
7834         E = ASE->getBase();
7835         goto tryAgain;
7836       }
7837     }
7838 
7839     return SLCT_NotALiteral;
7840   }
7841 
7842   default:
7843     return SLCT_NotALiteral;
7844   }
7845 }
7846 
GetFormatStringType(const FormatAttr * Format)7847 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7848   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7849       .Case("scanf", FST_Scanf)
7850       .Cases("printf", "printf0", FST_Printf)
7851       .Cases("NSString", "CFString", FST_NSString)
7852       .Case("strftime", FST_Strftime)
7853       .Case("strfmon", FST_Strfmon)
7854       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7855       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7856       .Case("os_trace", FST_OSLog)
7857       .Case("os_log", FST_OSLog)
7858       .Default(FST_Unknown);
7859 }
7860 
7861 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7862 /// functions) for correct use of format strings.
7863 /// Returns true if a format string has been fully checked.
CheckFormatArguments(const FormatAttr * Format,ArrayRef<const Expr * > Args,bool IsCXXMember,VariadicCallType CallType,SourceLocation Loc,SourceRange Range,llvm::SmallBitVector & CheckedVarArgs)7864 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7865                                 ArrayRef<const Expr *> Args,
7866                                 bool IsCXXMember,
7867                                 VariadicCallType CallType,
7868                                 SourceLocation Loc, SourceRange Range,
7869                                 llvm::SmallBitVector &CheckedVarArgs) {
7870   FormatStringInfo FSI;
7871   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7872     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7873                                 FSI.FirstDataArg, GetFormatStringType(Format),
7874                                 CallType, Loc, Range, CheckedVarArgs);
7875   return false;
7876 }
7877 
CheckFormatArguments(ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,FormatStringType Type,VariadicCallType CallType,SourceLocation Loc,SourceRange Range,llvm::SmallBitVector & CheckedVarArgs)7878 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7879                                 bool HasVAListArg, unsigned format_idx,
7880                                 unsigned firstDataArg, FormatStringType Type,
7881                                 VariadicCallType CallType,
7882                                 SourceLocation Loc, SourceRange Range,
7883                                 llvm::SmallBitVector &CheckedVarArgs) {
7884   // CHECK: printf/scanf-like function is called with no format string.
7885   if (format_idx >= Args.size()) {
7886     Diag(Loc, diag::warn_missing_format_string) << Range;
7887     return false;
7888   }
7889 
7890   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7891 
7892   // CHECK: format string is not a string literal.
7893   //
7894   // Dynamically generated format strings are difficult to
7895   // automatically vet at compile time.  Requiring that format strings
7896   // are string literals: (1) permits the checking of format strings by
7897   // the compiler and thereby (2) can practically remove the source of
7898   // many format string exploits.
7899 
7900   // Format string can be either ObjC string (e.g. @"%d") or
7901   // C string (e.g. "%d")
7902   // ObjC string uses the same format specifiers as C string, so we can use
7903   // the same format string checking logic for both ObjC and C strings.
7904   UncoveredArgHandler UncoveredArg;
7905   StringLiteralCheckType CT =
7906       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7907                             format_idx, firstDataArg, Type, CallType,
7908                             /*IsFunctionCall*/ true, CheckedVarArgs,
7909                             UncoveredArg,
7910                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7911 
7912   // Generate a diagnostic where an uncovered argument is detected.
7913   if (UncoveredArg.hasUncoveredArg()) {
7914     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7915     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7916     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7917   }
7918 
7919   if (CT != SLCT_NotALiteral)
7920     // Literal format string found, check done!
7921     return CT == SLCT_CheckedLiteral;
7922 
7923   // Strftime is particular as it always uses a single 'time' argument,
7924   // so it is safe to pass a non-literal string.
7925   if (Type == FST_Strftime)
7926     return false;
7927 
7928   // Do not emit diag when the string param is a macro expansion and the
7929   // format is either NSString or CFString. This is a hack to prevent
7930   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7931   // which are usually used in place of NS and CF string literals.
7932   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7933   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7934     return false;
7935 
7936   // If there are no arguments specified, warn with -Wformat-security, otherwise
7937   // warn only with -Wformat-nonliteral.
7938   if (Args.size() == firstDataArg) {
7939     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7940       << OrigFormatExpr->getSourceRange();
7941     switch (Type) {
7942     default:
7943       break;
7944     case FST_Kprintf:
7945     case FST_FreeBSDKPrintf:
7946     case FST_Printf:
7947       Diag(FormatLoc, diag::note_format_security_fixit)
7948         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7949       break;
7950     case FST_NSString:
7951       Diag(FormatLoc, diag::note_format_security_fixit)
7952         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7953       break;
7954     }
7955   } else {
7956     Diag(FormatLoc, diag::warn_format_nonliteral)
7957       << OrigFormatExpr->getSourceRange();
7958   }
7959   return false;
7960 }
7961 
7962 namespace {
7963 
7964 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7965 protected:
7966   Sema &S;
7967   const FormatStringLiteral *FExpr;
7968   const Expr *OrigFormatExpr;
7969   const Sema::FormatStringType FSType;
7970   const unsigned FirstDataArg;
7971   const unsigned NumDataArgs;
7972   const char *Beg; // Start of format string.
7973   const bool HasVAListArg;
7974   ArrayRef<const Expr *> Args;
7975   unsigned FormatIdx;
7976   llvm::SmallBitVector CoveredArgs;
7977   bool usesPositionalArgs = false;
7978   bool atFirstArg = true;
7979   bool inFunctionCall;
7980   Sema::VariadicCallType CallType;
7981   llvm::SmallBitVector &CheckedVarArgs;
7982   UncoveredArgHandler &UncoveredArg;
7983 
7984 public:
CheckFormatHandler(Sema & s,const FormatStringLiteral * fexpr,const Expr * origFormatExpr,const Sema::FormatStringType type,unsigned firstDataArg,unsigned numDataArgs,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType callType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg)7985   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7986                      const Expr *origFormatExpr,
7987                      const Sema::FormatStringType type, unsigned firstDataArg,
7988                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7989                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7990                      bool inFunctionCall, Sema::VariadicCallType callType,
7991                      llvm::SmallBitVector &CheckedVarArgs,
7992                      UncoveredArgHandler &UncoveredArg)
7993       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7994         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7995         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7996         inFunctionCall(inFunctionCall), CallType(callType),
7997         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7998     CoveredArgs.resize(numDataArgs);
7999     CoveredArgs.reset();
8000   }
8001 
8002   void DoneProcessing();
8003 
8004   void HandleIncompleteSpecifier(const char *startSpecifier,
8005                                  unsigned specifierLen) override;
8006 
8007   void HandleInvalidLengthModifier(
8008                            const analyze_format_string::FormatSpecifier &FS,
8009                            const analyze_format_string::ConversionSpecifier &CS,
8010                            const char *startSpecifier, unsigned specifierLen,
8011                            unsigned DiagID);
8012 
8013   void HandleNonStandardLengthModifier(
8014                     const analyze_format_string::FormatSpecifier &FS,
8015                     const char *startSpecifier, unsigned specifierLen);
8016 
8017   void HandleNonStandardConversionSpecifier(
8018                     const analyze_format_string::ConversionSpecifier &CS,
8019                     const char *startSpecifier, unsigned specifierLen);
8020 
8021   void HandlePosition(const char *startPos, unsigned posLen) override;
8022 
8023   void HandleInvalidPosition(const char *startSpecifier,
8024                              unsigned specifierLen,
8025                              analyze_format_string::PositionContext p) override;
8026 
8027   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8028 
8029   void HandleNullChar(const char *nullCharacter) override;
8030 
8031   template <typename Range>
8032   static void
8033   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8034                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8035                        bool IsStringLocation, Range StringRange,
8036                        ArrayRef<FixItHint> Fixit = None);
8037 
8038 protected:
8039   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8040                                         const char *startSpec,
8041                                         unsigned specifierLen,
8042                                         const char *csStart, unsigned csLen);
8043 
8044   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8045                                          const char *startSpec,
8046                                          unsigned specifierLen);
8047 
8048   SourceRange getFormatStringRange();
8049   CharSourceRange getSpecifierRange(const char *startSpecifier,
8050                                     unsigned specifierLen);
8051   SourceLocation getLocationOfByte(const char *x);
8052 
8053   const Expr *getDataArg(unsigned i) const;
8054 
8055   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8056                     const analyze_format_string::ConversionSpecifier &CS,
8057                     const char *startSpecifier, unsigned specifierLen,
8058                     unsigned argIndex);
8059 
8060   template <typename Range>
8061   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8062                             bool IsStringLocation, Range StringRange,
8063                             ArrayRef<FixItHint> Fixit = None);
8064 };
8065 
8066 } // namespace
8067 
getFormatStringRange()8068 SourceRange CheckFormatHandler::getFormatStringRange() {
8069   return OrigFormatExpr->getSourceRange();
8070 }
8071 
8072 CharSourceRange CheckFormatHandler::
getSpecifierRange(const char * startSpecifier,unsigned specifierLen)8073 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8074   SourceLocation Start = getLocationOfByte(startSpecifier);
8075   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8076 
8077   // Advance the end SourceLocation by one due to half-open ranges.
8078   End = End.getLocWithOffset(1);
8079 
8080   return CharSourceRange::getCharRange(Start, End);
8081 }
8082 
getLocationOfByte(const char * x)8083 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8084   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8085                                   S.getLangOpts(), S.Context.getTargetInfo());
8086 }
8087 
HandleIncompleteSpecifier(const char * startSpecifier,unsigned specifierLen)8088 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8089                                                    unsigned specifierLen){
8090   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8091                        getLocationOfByte(startSpecifier),
8092                        /*IsStringLocation*/true,
8093                        getSpecifierRange(startSpecifier, specifierLen));
8094 }
8095 
HandleInvalidLengthModifier(const analyze_format_string::FormatSpecifier & FS,const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen,unsigned DiagID)8096 void CheckFormatHandler::HandleInvalidLengthModifier(
8097     const analyze_format_string::FormatSpecifier &FS,
8098     const analyze_format_string::ConversionSpecifier &CS,
8099     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8100   using namespace analyze_format_string;
8101 
8102   const LengthModifier &LM = FS.getLengthModifier();
8103   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8104 
8105   // See if we know how to fix this length modifier.
8106   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8107   if (FixedLM) {
8108     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8109                          getLocationOfByte(LM.getStart()),
8110                          /*IsStringLocation*/true,
8111                          getSpecifierRange(startSpecifier, specifierLen));
8112 
8113     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8114       << FixedLM->toString()
8115       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8116 
8117   } else {
8118     FixItHint Hint;
8119     if (DiagID == diag::warn_format_nonsensical_length)
8120       Hint = FixItHint::CreateRemoval(LMRange);
8121 
8122     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8123                          getLocationOfByte(LM.getStart()),
8124                          /*IsStringLocation*/true,
8125                          getSpecifierRange(startSpecifier, specifierLen),
8126                          Hint);
8127   }
8128 }
8129 
HandleNonStandardLengthModifier(const analyze_format_string::FormatSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8130 void CheckFormatHandler::HandleNonStandardLengthModifier(
8131     const analyze_format_string::FormatSpecifier &FS,
8132     const char *startSpecifier, unsigned specifierLen) {
8133   using namespace analyze_format_string;
8134 
8135   const LengthModifier &LM = FS.getLengthModifier();
8136   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8137 
8138   // See if we know how to fix this length modifier.
8139   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8140   if (FixedLM) {
8141     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8142                            << LM.toString() << 0,
8143                          getLocationOfByte(LM.getStart()),
8144                          /*IsStringLocation*/true,
8145                          getSpecifierRange(startSpecifier, specifierLen));
8146 
8147     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8148       << FixedLM->toString()
8149       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8150 
8151   } else {
8152     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8153                            << LM.toString() << 0,
8154                          getLocationOfByte(LM.getStart()),
8155                          /*IsStringLocation*/true,
8156                          getSpecifierRange(startSpecifier, specifierLen));
8157   }
8158 }
8159 
HandleNonStandardConversionSpecifier(const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen)8160 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8161     const analyze_format_string::ConversionSpecifier &CS,
8162     const char *startSpecifier, unsigned specifierLen) {
8163   using namespace analyze_format_string;
8164 
8165   // See if we know how to fix this conversion specifier.
8166   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8167   if (FixedCS) {
8168     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8169                           << CS.toString() << /*conversion specifier*/1,
8170                          getLocationOfByte(CS.getStart()),
8171                          /*IsStringLocation*/true,
8172                          getSpecifierRange(startSpecifier, specifierLen));
8173 
8174     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8175     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8176       << FixedCS->toString()
8177       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8178   } else {
8179     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8180                           << CS.toString() << /*conversion specifier*/1,
8181                          getLocationOfByte(CS.getStart()),
8182                          /*IsStringLocation*/true,
8183                          getSpecifierRange(startSpecifier, specifierLen));
8184   }
8185 }
8186 
HandlePosition(const char * startPos,unsigned posLen)8187 void CheckFormatHandler::HandlePosition(const char *startPos,
8188                                         unsigned posLen) {
8189   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8190                                getLocationOfByte(startPos),
8191                                /*IsStringLocation*/true,
8192                                getSpecifierRange(startPos, posLen));
8193 }
8194 
8195 void
HandleInvalidPosition(const char * startPos,unsigned posLen,analyze_format_string::PositionContext p)8196 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8197                                      analyze_format_string::PositionContext p) {
8198   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8199                          << (unsigned) p,
8200                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8201                        getSpecifierRange(startPos, posLen));
8202 }
8203 
HandleZeroPosition(const char * startPos,unsigned posLen)8204 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8205                                             unsigned posLen) {
8206   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8207                                getLocationOfByte(startPos),
8208                                /*IsStringLocation*/true,
8209                                getSpecifierRange(startPos, posLen));
8210 }
8211 
HandleNullChar(const char * nullCharacter)8212 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8213   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8214     // The presence of a null character is likely an error.
8215     EmitFormatDiagnostic(
8216       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8217       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8218       getFormatStringRange());
8219   }
8220 }
8221 
8222 // Note that this may return NULL if there was an error parsing or building
8223 // one of the argument expressions.
getDataArg(unsigned i) const8224 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8225   return Args[FirstDataArg + i];
8226 }
8227 
DoneProcessing()8228 void CheckFormatHandler::DoneProcessing() {
8229   // Does the number of data arguments exceed the number of
8230   // format conversions in the format string?
8231   if (!HasVAListArg) {
8232       // Find any arguments that weren't covered.
8233     CoveredArgs.flip();
8234     signed notCoveredArg = CoveredArgs.find_first();
8235     if (notCoveredArg >= 0) {
8236       assert((unsigned)notCoveredArg < NumDataArgs);
8237       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8238     } else {
8239       UncoveredArg.setAllCovered();
8240     }
8241   }
8242 }
8243 
Diagnose(Sema & S,bool IsFunctionCall,const Expr * ArgExpr)8244 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8245                                    const Expr *ArgExpr) {
8246   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8247          "Invalid state");
8248 
8249   if (!ArgExpr)
8250     return;
8251 
8252   SourceLocation Loc = ArgExpr->getBeginLoc();
8253 
8254   if (S.getSourceManager().isInSystemMacro(Loc))
8255     return;
8256 
8257   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8258   for (auto E : DiagnosticExprs)
8259     PDiag << E->getSourceRange();
8260 
8261   CheckFormatHandler::EmitFormatDiagnostic(
8262                                   S, IsFunctionCall, DiagnosticExprs[0],
8263                                   PDiag, Loc, /*IsStringLocation*/false,
8264                                   DiagnosticExprs[0]->getSourceRange());
8265 }
8266 
8267 bool
HandleInvalidConversionSpecifier(unsigned argIndex,SourceLocation Loc,const char * startSpec,unsigned specifierLen,const char * csStart,unsigned csLen)8268 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8269                                                      SourceLocation Loc,
8270                                                      const char *startSpec,
8271                                                      unsigned specifierLen,
8272                                                      const char *csStart,
8273                                                      unsigned csLen) {
8274   bool keepGoing = true;
8275   if (argIndex < NumDataArgs) {
8276     // Consider the argument coverered, even though the specifier doesn't
8277     // make sense.
8278     CoveredArgs.set(argIndex);
8279   }
8280   else {
8281     // If argIndex exceeds the number of data arguments we
8282     // don't issue a warning because that is just a cascade of warnings (and
8283     // they may have intended '%%' anyway). We don't want to continue processing
8284     // the format string after this point, however, as we will like just get
8285     // gibberish when trying to match arguments.
8286     keepGoing = false;
8287   }
8288 
8289   StringRef Specifier(csStart, csLen);
8290 
8291   // If the specifier in non-printable, it could be the first byte of a UTF-8
8292   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8293   // hex value.
8294   std::string CodePointStr;
8295   if (!llvm::sys::locale::isPrint(*csStart)) {
8296     llvm::UTF32 CodePoint;
8297     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8298     const llvm::UTF8 *E =
8299         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8300     llvm::ConversionResult Result =
8301         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8302 
8303     if (Result != llvm::conversionOK) {
8304       unsigned char FirstChar = *csStart;
8305       CodePoint = (llvm::UTF32)FirstChar;
8306     }
8307 
8308     llvm::raw_string_ostream OS(CodePointStr);
8309     if (CodePoint < 256)
8310       OS << "\\x" << llvm::format("%02x", CodePoint);
8311     else if (CodePoint <= 0xFFFF)
8312       OS << "\\u" << llvm::format("%04x", CodePoint);
8313     else
8314       OS << "\\U" << llvm::format("%08x", CodePoint);
8315     OS.flush();
8316     Specifier = CodePointStr;
8317   }
8318 
8319   EmitFormatDiagnostic(
8320       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8321       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8322 
8323   return keepGoing;
8324 }
8325 
8326 void
HandlePositionalNonpositionalArgs(SourceLocation Loc,const char * startSpec,unsigned specifierLen)8327 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8328                                                       const char *startSpec,
8329                                                       unsigned specifierLen) {
8330   EmitFormatDiagnostic(
8331     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8332     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8333 }
8334 
8335 bool
CheckNumArgs(const analyze_format_string::FormatSpecifier & FS,const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen,unsigned argIndex)8336 CheckFormatHandler::CheckNumArgs(
8337   const analyze_format_string::FormatSpecifier &FS,
8338   const analyze_format_string::ConversionSpecifier &CS,
8339   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8340 
8341   if (argIndex >= NumDataArgs) {
8342     PartialDiagnostic PDiag = FS.usesPositionalArg()
8343       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8344            << (argIndex+1) << NumDataArgs)
8345       : S.PDiag(diag::warn_printf_insufficient_data_args);
8346     EmitFormatDiagnostic(
8347       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8348       getSpecifierRange(startSpecifier, specifierLen));
8349 
8350     // Since more arguments than conversion tokens are given, by extension
8351     // all arguments are covered, so mark this as so.
8352     UncoveredArg.setAllCovered();
8353     return false;
8354   }
8355   return true;
8356 }
8357 
8358 template<typename Range>
EmitFormatDiagnostic(PartialDiagnostic PDiag,SourceLocation Loc,bool IsStringLocation,Range StringRange,ArrayRef<FixItHint> FixIt)8359 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8360                                               SourceLocation Loc,
8361                                               bool IsStringLocation,
8362                                               Range StringRange,
8363                                               ArrayRef<FixItHint> FixIt) {
8364   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8365                        Loc, IsStringLocation, StringRange, FixIt);
8366 }
8367 
8368 /// If the format string is not within the function call, emit a note
8369 /// so that the function call and string are in diagnostic messages.
8370 ///
8371 /// \param InFunctionCall if true, the format string is within the function
8372 /// call and only one diagnostic message will be produced.  Otherwise, an
8373 /// extra note will be emitted pointing to location of the format string.
8374 ///
8375 /// \param ArgumentExpr the expression that is passed as the format string
8376 /// argument in the function call.  Used for getting locations when two
8377 /// diagnostics are emitted.
8378 ///
8379 /// \param PDiag the callee should already have provided any strings for the
8380 /// diagnostic message.  This function only adds locations and fixits
8381 /// to diagnostics.
8382 ///
8383 /// \param Loc primary location for diagnostic.  If two diagnostics are
8384 /// required, one will be at Loc and a new SourceLocation will be created for
8385 /// the other one.
8386 ///
8387 /// \param IsStringLocation if true, Loc points to the format string should be
8388 /// used for the note.  Otherwise, Loc points to the argument list and will
8389 /// be used with PDiag.
8390 ///
8391 /// \param StringRange some or all of the string to highlight.  This is
8392 /// templated so it can accept either a CharSourceRange or a SourceRange.
8393 ///
8394 /// \param FixIt optional fix it hint for the format string.
8395 template <typename Range>
EmitFormatDiagnostic(Sema & S,bool InFunctionCall,const Expr * ArgumentExpr,const PartialDiagnostic & PDiag,SourceLocation Loc,bool IsStringLocation,Range StringRange,ArrayRef<FixItHint> FixIt)8396 void CheckFormatHandler::EmitFormatDiagnostic(
8397     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8398     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8399     Range StringRange, ArrayRef<FixItHint> FixIt) {
8400   if (InFunctionCall) {
8401     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8402     D << StringRange;
8403     D << FixIt;
8404   } else {
8405     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8406       << ArgumentExpr->getSourceRange();
8407 
8408     const Sema::SemaDiagnosticBuilder &Note =
8409       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8410              diag::note_format_string_defined);
8411 
8412     Note << StringRange;
8413     Note << FixIt;
8414   }
8415 }
8416 
8417 //===--- CHECK: Printf format string checking ------------------------------===//
8418 
8419 namespace {
8420 
8421 class CheckPrintfHandler : public CheckFormatHandler {
8422 public:
CheckPrintfHandler(Sema & s,const FormatStringLiteral * fexpr,const Expr * origFormatExpr,const Sema::FormatStringType type,unsigned firstDataArg,unsigned numDataArgs,bool isObjC,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg)8423   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8424                      const Expr *origFormatExpr,
8425                      const Sema::FormatStringType type, unsigned firstDataArg,
8426                      unsigned numDataArgs, bool isObjC, const char *beg,
8427                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8428                      unsigned formatIdx, bool inFunctionCall,
8429                      Sema::VariadicCallType CallType,
8430                      llvm::SmallBitVector &CheckedVarArgs,
8431                      UncoveredArgHandler &UncoveredArg)
8432       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8433                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8434                            inFunctionCall, CallType, CheckedVarArgs,
8435                            UncoveredArg) {}
8436 
isObjCContext() const8437   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8438 
8439   /// Returns true if '%@' specifiers are allowed in the format string.
allowsObjCArg() const8440   bool allowsObjCArg() const {
8441     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8442            FSType == Sema::FST_OSTrace;
8443   }
8444 
8445   bool HandleInvalidPrintfConversionSpecifier(
8446                                       const analyze_printf::PrintfSpecifier &FS,
8447                                       const char *startSpecifier,
8448                                       unsigned specifierLen) override;
8449 
8450   void handleInvalidMaskType(StringRef MaskType) override;
8451 
8452   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8453                              const char *startSpecifier,
8454                              unsigned specifierLen) override;
8455   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8456                        const char *StartSpecifier,
8457                        unsigned SpecifierLen,
8458                        const Expr *E);
8459 
8460   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8461                     const char *startSpecifier, unsigned specifierLen);
8462   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8463                            const analyze_printf::OptionalAmount &Amt,
8464                            unsigned type,
8465                            const char *startSpecifier, unsigned specifierLen);
8466   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8467                   const analyze_printf::OptionalFlag &flag,
8468                   const char *startSpecifier, unsigned specifierLen);
8469   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8470                          const analyze_printf::OptionalFlag &ignoredFlag,
8471                          const analyze_printf::OptionalFlag &flag,
8472                          const char *startSpecifier, unsigned specifierLen);
8473   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8474                            const Expr *E);
8475 
8476   void HandleEmptyObjCModifierFlag(const char *startFlag,
8477                                    unsigned flagLen) override;
8478 
8479   void HandleInvalidObjCModifierFlag(const char *startFlag,
8480                                             unsigned flagLen) override;
8481 
8482   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8483                                            const char *flagsEnd,
8484                                            const char *conversionPosition)
8485                                              override;
8486 };
8487 
8488 } // namespace
8489 
HandleInvalidPrintfConversionSpecifier(const analyze_printf::PrintfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8490 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8491                                       const analyze_printf::PrintfSpecifier &FS,
8492                                       const char *startSpecifier,
8493                                       unsigned specifierLen) {
8494   const analyze_printf::PrintfConversionSpecifier &CS =
8495     FS.getConversionSpecifier();
8496 
8497   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8498                                           getLocationOfByte(CS.getStart()),
8499                                           startSpecifier, specifierLen,
8500                                           CS.getStart(), CS.getLength());
8501 }
8502 
handleInvalidMaskType(StringRef MaskType)8503 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8504   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8505 }
8506 
HandleAmount(const analyze_format_string::OptionalAmount & Amt,unsigned k,const char * startSpecifier,unsigned specifierLen)8507 bool CheckPrintfHandler::HandleAmount(
8508                                const analyze_format_string::OptionalAmount &Amt,
8509                                unsigned k, const char *startSpecifier,
8510                                unsigned specifierLen) {
8511   if (Amt.hasDataArgument()) {
8512     if (!HasVAListArg) {
8513       unsigned argIndex = Amt.getArgIndex();
8514       if (argIndex >= NumDataArgs) {
8515         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8516                                << k,
8517                              getLocationOfByte(Amt.getStart()),
8518                              /*IsStringLocation*/true,
8519                              getSpecifierRange(startSpecifier, specifierLen));
8520         // Don't do any more checking.  We will just emit
8521         // spurious errors.
8522         return false;
8523       }
8524 
8525       // Type check the data argument.  It should be an 'int'.
8526       // Although not in conformance with C99, we also allow the argument to be
8527       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8528       // doesn't emit a warning for that case.
8529       CoveredArgs.set(argIndex);
8530       const Expr *Arg = getDataArg(argIndex);
8531       if (!Arg)
8532         return false;
8533 
8534       QualType T = Arg->getType();
8535 
8536       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8537       assert(AT.isValid());
8538 
8539       if (!AT.matchesType(S.Context, T)) {
8540         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8541                                << k << AT.getRepresentativeTypeName(S.Context)
8542                                << T << Arg->getSourceRange(),
8543                              getLocationOfByte(Amt.getStart()),
8544                              /*IsStringLocation*/true,
8545                              getSpecifierRange(startSpecifier, specifierLen));
8546         // Don't do any more checking.  We will just emit
8547         // spurious errors.
8548         return false;
8549       }
8550     }
8551   }
8552   return true;
8553 }
8554 
HandleInvalidAmount(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalAmount & Amt,unsigned type,const char * startSpecifier,unsigned specifierLen)8555 void CheckPrintfHandler::HandleInvalidAmount(
8556                                       const analyze_printf::PrintfSpecifier &FS,
8557                                       const analyze_printf::OptionalAmount &Amt,
8558                                       unsigned type,
8559                                       const char *startSpecifier,
8560                                       unsigned specifierLen) {
8561   const analyze_printf::PrintfConversionSpecifier &CS =
8562     FS.getConversionSpecifier();
8563 
8564   FixItHint fixit =
8565     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8566       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8567                                  Amt.getConstantLength()))
8568       : FixItHint();
8569 
8570   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8571                          << type << CS.toString(),
8572                        getLocationOfByte(Amt.getStart()),
8573                        /*IsStringLocation*/true,
8574                        getSpecifierRange(startSpecifier, specifierLen),
8575                        fixit);
8576 }
8577 
HandleFlag(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalFlag & flag,const char * startSpecifier,unsigned specifierLen)8578 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8579                                     const analyze_printf::OptionalFlag &flag,
8580                                     const char *startSpecifier,
8581                                     unsigned specifierLen) {
8582   // Warn about pointless flag with a fixit removal.
8583   const analyze_printf::PrintfConversionSpecifier &CS =
8584     FS.getConversionSpecifier();
8585   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8586                          << flag.toString() << CS.toString(),
8587                        getLocationOfByte(flag.getPosition()),
8588                        /*IsStringLocation*/true,
8589                        getSpecifierRange(startSpecifier, specifierLen),
8590                        FixItHint::CreateRemoval(
8591                          getSpecifierRange(flag.getPosition(), 1)));
8592 }
8593 
HandleIgnoredFlag(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalFlag & ignoredFlag,const analyze_printf::OptionalFlag & flag,const char * startSpecifier,unsigned specifierLen)8594 void CheckPrintfHandler::HandleIgnoredFlag(
8595                                 const analyze_printf::PrintfSpecifier &FS,
8596                                 const analyze_printf::OptionalFlag &ignoredFlag,
8597                                 const analyze_printf::OptionalFlag &flag,
8598                                 const char *startSpecifier,
8599                                 unsigned specifierLen) {
8600   // Warn about ignored flag with a fixit removal.
8601   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8602                          << ignoredFlag.toString() << flag.toString(),
8603                        getLocationOfByte(ignoredFlag.getPosition()),
8604                        /*IsStringLocation*/true,
8605                        getSpecifierRange(startSpecifier, specifierLen),
8606                        FixItHint::CreateRemoval(
8607                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8608 }
8609 
HandleEmptyObjCModifierFlag(const char * startFlag,unsigned flagLen)8610 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8611                                                      unsigned flagLen) {
8612   // Warn about an empty flag.
8613   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8614                        getLocationOfByte(startFlag),
8615                        /*IsStringLocation*/true,
8616                        getSpecifierRange(startFlag, flagLen));
8617 }
8618 
HandleInvalidObjCModifierFlag(const char * startFlag,unsigned flagLen)8619 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8620                                                        unsigned flagLen) {
8621   // Warn about an invalid flag.
8622   auto Range = getSpecifierRange(startFlag, flagLen);
8623   StringRef flag(startFlag, flagLen);
8624   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8625                       getLocationOfByte(startFlag),
8626                       /*IsStringLocation*/true,
8627                       Range, FixItHint::CreateRemoval(Range));
8628 }
8629 
HandleObjCFlagsWithNonObjCConversion(const char * flagsStart,const char * flagsEnd,const char * conversionPosition)8630 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8631     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8632     // Warn about using '[...]' without a '@' conversion.
8633     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8634     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8635     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8636                          getLocationOfByte(conversionPosition),
8637                          /*IsStringLocation*/true,
8638                          Range, FixItHint::CreateRemoval(Range));
8639 }
8640 
8641 // Determines if the specified is a C++ class or struct containing
8642 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8643 // "c_str()").
8644 template<typename MemberKind>
8645 static llvm::SmallPtrSet<MemberKind*, 1>
CXXRecordMembersNamed(StringRef Name,Sema & S,QualType Ty)8646 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8647   const RecordType *RT = Ty->getAs<RecordType>();
8648   llvm::SmallPtrSet<MemberKind*, 1> Results;
8649 
8650   if (!RT)
8651     return Results;
8652   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8653   if (!RD || !RD->getDefinition())
8654     return Results;
8655 
8656   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8657                  Sema::LookupMemberName);
8658   R.suppressDiagnostics();
8659 
8660   // We just need to include all members of the right kind turned up by the
8661   // filter, at this point.
8662   if (S.LookupQualifiedName(R, RT->getDecl()))
8663     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8664       NamedDecl *decl = (*I)->getUnderlyingDecl();
8665       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8666         Results.insert(FK);
8667     }
8668   return Results;
8669 }
8670 
8671 /// Check if we could call '.c_str()' on an object.
8672 ///
8673 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8674 /// allow the call, or if it would be ambiguous).
hasCStrMethod(const Expr * E)8675 bool Sema::hasCStrMethod(const Expr *E) {
8676   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8677 
8678   MethodSet Results =
8679       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8680   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8681        MI != ME; ++MI)
8682     if ((*MI)->getMinRequiredArguments() == 0)
8683       return true;
8684   return false;
8685 }
8686 
8687 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8688 // better diagnostic if so. AT is assumed to be valid.
8689 // Returns true when a c_str() conversion method is found.
checkForCStrMembers(const analyze_printf::ArgType & AT,const Expr * E)8690 bool CheckPrintfHandler::checkForCStrMembers(
8691     const analyze_printf::ArgType &AT, const Expr *E) {
8692   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8693 
8694   MethodSet Results =
8695       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8696 
8697   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8698        MI != ME; ++MI) {
8699     const CXXMethodDecl *Method = *MI;
8700     if (Method->getMinRequiredArguments() == 0 &&
8701         AT.matchesType(S.Context, Method->getReturnType())) {
8702       // FIXME: Suggest parens if the expression needs them.
8703       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8704       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8705           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8706       return true;
8707     }
8708   }
8709 
8710   return false;
8711 }
8712 
8713 bool
HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)8714 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8715                                             &FS,
8716                                           const char *startSpecifier,
8717                                           unsigned specifierLen) {
8718   using namespace analyze_format_string;
8719   using namespace analyze_printf;
8720 
8721   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8722 
8723   if (FS.consumesDataArgument()) {
8724     if (atFirstArg) {
8725         atFirstArg = false;
8726         usesPositionalArgs = FS.usesPositionalArg();
8727     }
8728     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8729       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8730                                         startSpecifier, specifierLen);
8731       return false;
8732     }
8733   }
8734 
8735   // First check if the field width, precision, and conversion specifier
8736   // have matching data arguments.
8737   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8738                     startSpecifier, specifierLen)) {
8739     return false;
8740   }
8741 
8742   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8743                     startSpecifier, specifierLen)) {
8744     return false;
8745   }
8746 
8747   if (!CS.consumesDataArgument()) {
8748     // FIXME: Technically specifying a precision or field width here
8749     // makes no sense.  Worth issuing a warning at some point.
8750     return true;
8751   }
8752 
8753   // Consume the argument.
8754   unsigned argIndex = FS.getArgIndex();
8755   if (argIndex < NumDataArgs) {
8756     // The check to see if the argIndex is valid will come later.
8757     // We set the bit here because we may exit early from this
8758     // function if we encounter some other error.
8759     CoveredArgs.set(argIndex);
8760   }
8761 
8762   // FreeBSD kernel extensions.
8763   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8764       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8765     // We need at least two arguments.
8766     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8767       return false;
8768 
8769     // Claim the second argument.
8770     CoveredArgs.set(argIndex + 1);
8771 
8772     // Type check the first argument (int for %b, pointer for %D)
8773     const Expr *Ex = getDataArg(argIndex);
8774     const analyze_printf::ArgType &AT =
8775       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8776         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8777     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8778       EmitFormatDiagnostic(
8779           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8780               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8781               << false << Ex->getSourceRange(),
8782           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8783           getSpecifierRange(startSpecifier, specifierLen));
8784 
8785     // Type check the second argument (char * for both %b and %D)
8786     Ex = getDataArg(argIndex + 1);
8787     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8788     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8789       EmitFormatDiagnostic(
8790           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8791               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8792               << false << Ex->getSourceRange(),
8793           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8794           getSpecifierRange(startSpecifier, specifierLen));
8795 
8796      return true;
8797   }
8798 
8799   // Check for using an Objective-C specific conversion specifier
8800   // in a non-ObjC literal.
8801   if (!allowsObjCArg() && CS.isObjCArg()) {
8802     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8803                                                   specifierLen);
8804   }
8805 
8806   // %P can only be used with os_log.
8807   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8808     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8809                                                   specifierLen);
8810   }
8811 
8812   // %n is not allowed with os_log.
8813   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8814     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8815                          getLocationOfByte(CS.getStart()),
8816                          /*IsStringLocation*/ false,
8817                          getSpecifierRange(startSpecifier, specifierLen));
8818 
8819     return true;
8820   }
8821 
8822   // Only scalars are allowed for os_trace.
8823   if (FSType == Sema::FST_OSTrace &&
8824       (CS.getKind() == ConversionSpecifier::PArg ||
8825        CS.getKind() == ConversionSpecifier::sArg ||
8826        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8827     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8828                                                   specifierLen);
8829   }
8830 
8831   // Check for use of public/private annotation outside of os_log().
8832   if (FSType != Sema::FST_OSLog) {
8833     if (FS.isPublic().isSet()) {
8834       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8835                                << "public",
8836                            getLocationOfByte(FS.isPublic().getPosition()),
8837                            /*IsStringLocation*/ false,
8838                            getSpecifierRange(startSpecifier, specifierLen));
8839     }
8840     if (FS.isPrivate().isSet()) {
8841       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8842                                << "private",
8843                            getLocationOfByte(FS.isPrivate().getPosition()),
8844                            /*IsStringLocation*/ false,
8845                            getSpecifierRange(startSpecifier, specifierLen));
8846     }
8847   }
8848 
8849   // Check for invalid use of field width
8850   if (!FS.hasValidFieldWidth()) {
8851     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8852         startSpecifier, specifierLen);
8853   }
8854 
8855   // Check for invalid use of precision
8856   if (!FS.hasValidPrecision()) {
8857     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8858         startSpecifier, specifierLen);
8859   }
8860 
8861   // Precision is mandatory for %P specifier.
8862   if (CS.getKind() == ConversionSpecifier::PArg &&
8863       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8864     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8865                          getLocationOfByte(startSpecifier),
8866                          /*IsStringLocation*/ false,
8867                          getSpecifierRange(startSpecifier, specifierLen));
8868   }
8869 
8870   // Check each flag does not conflict with any other component.
8871   if (!FS.hasValidThousandsGroupingPrefix())
8872     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8873   if (!FS.hasValidLeadingZeros())
8874     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8875   if (!FS.hasValidPlusPrefix())
8876     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8877   if (!FS.hasValidSpacePrefix())
8878     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8879   if (!FS.hasValidAlternativeForm())
8880     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8881   if (!FS.hasValidLeftJustified())
8882     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8883 
8884   // Check that flags are not ignored by another flag
8885   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8886     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8887         startSpecifier, specifierLen);
8888   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8889     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8890             startSpecifier, specifierLen);
8891 
8892   // Check the length modifier is valid with the given conversion specifier.
8893   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8894                                  S.getLangOpts()))
8895     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8896                                 diag::warn_format_nonsensical_length);
8897   else if (!FS.hasStandardLengthModifier())
8898     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8899   else if (!FS.hasStandardLengthConversionCombination())
8900     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8901                                 diag::warn_format_non_standard_conversion_spec);
8902 
8903   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8904     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8905 
8906   // The remaining checks depend on the data arguments.
8907   if (HasVAListArg)
8908     return true;
8909 
8910   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8911     return false;
8912 
8913   const Expr *Arg = getDataArg(argIndex);
8914   if (!Arg)
8915     return true;
8916 
8917   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8918 }
8919 
requiresParensToAddCast(const Expr * E)8920 static bool requiresParensToAddCast(const Expr *E) {
8921   // FIXME: We should have a general way to reason about operator
8922   // precedence and whether parens are actually needed here.
8923   // Take care of a few common cases where they aren't.
8924   const Expr *Inside = E->IgnoreImpCasts();
8925   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8926     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8927 
8928   switch (Inside->getStmtClass()) {
8929   case Stmt::ArraySubscriptExprClass:
8930   case Stmt::CallExprClass:
8931   case Stmt::CharacterLiteralClass:
8932   case Stmt::CXXBoolLiteralExprClass:
8933   case Stmt::DeclRefExprClass:
8934   case Stmt::FloatingLiteralClass:
8935   case Stmt::IntegerLiteralClass:
8936   case Stmt::MemberExprClass:
8937   case Stmt::ObjCArrayLiteralClass:
8938   case Stmt::ObjCBoolLiteralExprClass:
8939   case Stmt::ObjCBoxedExprClass:
8940   case Stmt::ObjCDictionaryLiteralClass:
8941   case Stmt::ObjCEncodeExprClass:
8942   case Stmt::ObjCIvarRefExprClass:
8943   case Stmt::ObjCMessageExprClass:
8944   case Stmt::ObjCPropertyRefExprClass:
8945   case Stmt::ObjCStringLiteralClass:
8946   case Stmt::ObjCSubscriptRefExprClass:
8947   case Stmt::ParenExprClass:
8948   case Stmt::StringLiteralClass:
8949   case Stmt::UnaryOperatorClass:
8950     return false;
8951   default:
8952     return true;
8953   }
8954 }
8955 
8956 static std::pair<QualType, StringRef>
shouldNotPrintDirectly(const ASTContext & Context,QualType IntendedTy,const Expr * E)8957 shouldNotPrintDirectly(const ASTContext &Context,
8958                        QualType IntendedTy,
8959                        const Expr *E) {
8960   // Use a 'while' to peel off layers of typedefs.
8961   QualType TyTy = IntendedTy;
8962   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8963     StringRef Name = UserTy->getDecl()->getName();
8964     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8965       .Case("CFIndex", Context.getNSIntegerType())
8966       .Case("NSInteger", Context.getNSIntegerType())
8967       .Case("NSUInteger", Context.getNSUIntegerType())
8968       .Case("SInt32", Context.IntTy)
8969       .Case("UInt32", Context.UnsignedIntTy)
8970       .Default(QualType());
8971 
8972     if (!CastTy.isNull())
8973       return std::make_pair(CastTy, Name);
8974 
8975     TyTy = UserTy->desugar();
8976   }
8977 
8978   // Strip parens if necessary.
8979   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8980     return shouldNotPrintDirectly(Context,
8981                                   PE->getSubExpr()->getType(),
8982                                   PE->getSubExpr());
8983 
8984   // If this is a conditional expression, then its result type is constructed
8985   // via usual arithmetic conversions and thus there might be no necessary
8986   // typedef sugar there.  Recurse to operands to check for NSInteger &
8987   // Co. usage condition.
8988   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8989     QualType TrueTy, FalseTy;
8990     StringRef TrueName, FalseName;
8991 
8992     std::tie(TrueTy, TrueName) =
8993       shouldNotPrintDirectly(Context,
8994                              CO->getTrueExpr()->getType(),
8995                              CO->getTrueExpr());
8996     std::tie(FalseTy, FalseName) =
8997       shouldNotPrintDirectly(Context,
8998                              CO->getFalseExpr()->getType(),
8999                              CO->getFalseExpr());
9000 
9001     if (TrueTy == FalseTy)
9002       return std::make_pair(TrueTy, TrueName);
9003     else if (TrueTy.isNull())
9004       return std::make_pair(FalseTy, FalseName);
9005     else if (FalseTy.isNull())
9006       return std::make_pair(TrueTy, TrueName);
9007   }
9008 
9009   return std::make_pair(QualType(), StringRef());
9010 }
9011 
9012 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9013 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9014 /// type do not count.
9015 static bool
isArithmeticArgumentPromotion(Sema & S,const ImplicitCastExpr * ICE)9016 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9017   QualType From = ICE->getSubExpr()->getType();
9018   QualType To = ICE->getType();
9019   // It's an integer promotion if the destination type is the promoted
9020   // source type.
9021   if (ICE->getCastKind() == CK_IntegralCast &&
9022       From->isPromotableIntegerType() &&
9023       S.Context.getPromotedIntegerType(From) == To)
9024     return true;
9025   // Look through vector types, since we do default argument promotion for
9026   // those in OpenCL.
9027   if (const auto *VecTy = From->getAs<ExtVectorType>())
9028     From = VecTy->getElementType();
9029   if (const auto *VecTy = To->getAs<ExtVectorType>())
9030     To = VecTy->getElementType();
9031   // It's a floating promotion if the source type is a lower rank.
9032   return ICE->getCastKind() == CK_FloatingCast &&
9033          S.Context.getFloatingTypeOrder(From, To) < 0;
9034 }
9035 
9036 bool
checkFormatExpr(const analyze_printf::PrintfSpecifier & FS,const char * StartSpecifier,unsigned SpecifierLen,const Expr * E)9037 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9038                                     const char *StartSpecifier,
9039                                     unsigned SpecifierLen,
9040                                     const Expr *E) {
9041   using namespace analyze_format_string;
9042   using namespace analyze_printf;
9043 
9044   // Now type check the data expression that matches the
9045   // format specifier.
9046   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9047   if (!AT.isValid())
9048     return true;
9049 
9050   QualType ExprTy = E->getType();
9051   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9052     ExprTy = TET->getUnderlyingExpr()->getType();
9053   }
9054 
9055   // Diagnose attempts to print a boolean value as a character. Unlike other
9056   // -Wformat diagnostics, this is fine from a type perspective, but it still
9057   // doesn't make sense.
9058   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9059       E->isKnownToHaveBooleanValue()) {
9060     const CharSourceRange &CSR =
9061         getSpecifierRange(StartSpecifier, SpecifierLen);
9062     SmallString<4> FSString;
9063     llvm::raw_svector_ostream os(FSString);
9064     FS.toString(os);
9065     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9066                              << FSString,
9067                          E->getExprLoc(), false, CSR);
9068     return true;
9069   }
9070 
9071   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9072   if (Match == analyze_printf::ArgType::Match)
9073     return true;
9074 
9075   // Look through argument promotions for our error message's reported type.
9076   // This includes the integral and floating promotions, but excludes array
9077   // and function pointer decay (seeing that an argument intended to be a
9078   // string has type 'char [6]' is probably more confusing than 'char *') and
9079   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9080   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9081     if (isArithmeticArgumentPromotion(S, ICE)) {
9082       E = ICE->getSubExpr();
9083       ExprTy = E->getType();
9084 
9085       // Check if we didn't match because of an implicit cast from a 'char'
9086       // or 'short' to an 'int'.  This is done because printf is a varargs
9087       // function.
9088       if (ICE->getType() == S.Context.IntTy ||
9089           ICE->getType() == S.Context.UnsignedIntTy) {
9090         // All further checking is done on the subexpression
9091         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9092             AT.matchesType(S.Context, ExprTy);
9093         if (ImplicitMatch == analyze_printf::ArgType::Match)
9094           return true;
9095         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9096             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9097           Match = ImplicitMatch;
9098       }
9099     }
9100   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9101     // Special case for 'a', which has type 'int' in C.
9102     // Note, however, that we do /not/ want to treat multibyte constants like
9103     // 'MooV' as characters! This form is deprecated but still exists. In
9104     // addition, don't treat expressions as of type 'char' if one byte length
9105     // modifier is provided.
9106     if (ExprTy == S.Context.IntTy &&
9107         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9108       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9109         ExprTy = S.Context.CharTy;
9110   }
9111 
9112   // Look through enums to their underlying type.
9113   bool IsEnum = false;
9114   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9115     ExprTy = EnumTy->getDecl()->getIntegerType();
9116     IsEnum = true;
9117   }
9118 
9119   // %C in an Objective-C context prints a unichar, not a wchar_t.
9120   // If the argument is an integer of some kind, believe the %C and suggest
9121   // a cast instead of changing the conversion specifier.
9122   QualType IntendedTy = ExprTy;
9123   if (isObjCContext() &&
9124       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9125     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9126         !ExprTy->isCharType()) {
9127       // 'unichar' is defined as a typedef of unsigned short, but we should
9128       // prefer using the typedef if it is visible.
9129       IntendedTy = S.Context.UnsignedShortTy;
9130 
9131       // While we are here, check if the value is an IntegerLiteral that happens
9132       // to be within the valid range.
9133       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9134         const llvm::APInt &V = IL->getValue();
9135         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9136           return true;
9137       }
9138 
9139       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9140                           Sema::LookupOrdinaryName);
9141       if (S.LookupName(Result, S.getCurScope())) {
9142         NamedDecl *ND = Result.getFoundDecl();
9143         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9144           if (TD->getUnderlyingType() == IntendedTy)
9145             IntendedTy = S.Context.getTypedefType(TD);
9146       }
9147     }
9148   }
9149 
9150   // Special-case some of Darwin's platform-independence types by suggesting
9151   // casts to primitive types that are known to be large enough.
9152   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9153   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9154     QualType CastTy;
9155     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9156     if (!CastTy.isNull()) {
9157       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9158       // (long in ASTContext). Only complain to pedants.
9159       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9160           (AT.isSizeT() || AT.isPtrdiffT()) &&
9161           AT.matchesType(S.Context, CastTy))
9162         Match = ArgType::NoMatchPedantic;
9163       IntendedTy = CastTy;
9164       ShouldNotPrintDirectly = true;
9165     }
9166   }
9167 
9168   // We may be able to offer a FixItHint if it is a supported type.
9169   PrintfSpecifier fixedFS = FS;
9170   bool Success =
9171       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9172 
9173   if (Success) {
9174     // Get the fix string from the fixed format specifier
9175     SmallString<16> buf;
9176     llvm::raw_svector_ostream os(buf);
9177     fixedFS.toString(os);
9178 
9179     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9180 
9181     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9182       unsigned Diag;
9183       switch (Match) {
9184       case ArgType::Match: llvm_unreachable("expected non-matching");
9185       case ArgType::NoMatchPedantic:
9186         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9187         break;
9188       case ArgType::NoMatchTypeConfusion:
9189         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9190         break;
9191       case ArgType::NoMatch:
9192         Diag = diag::warn_format_conversion_argument_type_mismatch;
9193         break;
9194       }
9195 
9196       // In this case, the specifier is wrong and should be changed to match
9197       // the argument.
9198       EmitFormatDiagnostic(S.PDiag(Diag)
9199                                << AT.getRepresentativeTypeName(S.Context)
9200                                << IntendedTy << IsEnum << E->getSourceRange(),
9201                            E->getBeginLoc(),
9202                            /*IsStringLocation*/ false, SpecRange,
9203                            FixItHint::CreateReplacement(SpecRange, os.str()));
9204     } else {
9205       // The canonical type for formatting this value is different from the
9206       // actual type of the expression. (This occurs, for example, with Darwin's
9207       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9208       // should be printed as 'long' for 64-bit compatibility.)
9209       // Rather than emitting a normal format/argument mismatch, we want to
9210       // add a cast to the recommended type (and correct the format string
9211       // if necessary).
9212       SmallString<16> CastBuf;
9213       llvm::raw_svector_ostream CastFix(CastBuf);
9214       CastFix << "(";
9215       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9216       CastFix << ")";
9217 
9218       SmallVector<FixItHint,4> Hints;
9219       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9220         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9221 
9222       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9223         // If there's already a cast present, just replace it.
9224         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9225         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9226 
9227       } else if (!requiresParensToAddCast(E)) {
9228         // If the expression has high enough precedence,
9229         // just write the C-style cast.
9230         Hints.push_back(
9231             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9232       } else {
9233         // Otherwise, add parens around the expression as well as the cast.
9234         CastFix << "(";
9235         Hints.push_back(
9236             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9237 
9238         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9239         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9240       }
9241 
9242       if (ShouldNotPrintDirectly) {
9243         // The expression has a type that should not be printed directly.
9244         // We extract the name from the typedef because we don't want to show
9245         // the underlying type in the diagnostic.
9246         StringRef Name;
9247         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9248           Name = TypedefTy->getDecl()->getName();
9249         else
9250           Name = CastTyName;
9251         unsigned Diag = Match == ArgType::NoMatchPedantic
9252                             ? diag::warn_format_argument_needs_cast_pedantic
9253                             : diag::warn_format_argument_needs_cast;
9254         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9255                                            << E->getSourceRange(),
9256                              E->getBeginLoc(), /*IsStringLocation=*/false,
9257                              SpecRange, Hints);
9258       } else {
9259         // In this case, the expression could be printed using a different
9260         // specifier, but we've decided that the specifier is probably correct
9261         // and we should cast instead. Just use the normal warning message.
9262         EmitFormatDiagnostic(
9263             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9264                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9265                 << E->getSourceRange(),
9266             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9267       }
9268     }
9269   } else {
9270     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9271                                                    SpecifierLen);
9272     // Since the warning for passing non-POD types to variadic functions
9273     // was deferred until now, we emit a warning for non-POD
9274     // arguments here.
9275     switch (S.isValidVarArgType(ExprTy)) {
9276     case Sema::VAK_Valid:
9277     case Sema::VAK_ValidInCXX11: {
9278       unsigned Diag;
9279       switch (Match) {
9280       case ArgType::Match: llvm_unreachable("expected non-matching");
9281       case ArgType::NoMatchPedantic:
9282         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9283         break;
9284       case ArgType::NoMatchTypeConfusion:
9285         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9286         break;
9287       case ArgType::NoMatch:
9288         Diag = diag::warn_format_conversion_argument_type_mismatch;
9289         break;
9290       }
9291 
9292       EmitFormatDiagnostic(
9293           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9294                         << IsEnum << CSR << E->getSourceRange(),
9295           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9296       break;
9297     }
9298     case Sema::VAK_Undefined:
9299     case Sema::VAK_MSVCUndefined:
9300       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9301                                << S.getLangOpts().CPlusPlus11 << ExprTy
9302                                << CallType
9303                                << AT.getRepresentativeTypeName(S.Context) << CSR
9304                                << E->getSourceRange(),
9305                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9306       checkForCStrMembers(AT, E);
9307       break;
9308 
9309     case Sema::VAK_Invalid:
9310       if (ExprTy->isObjCObjectType())
9311         EmitFormatDiagnostic(
9312             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9313                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9314                 << AT.getRepresentativeTypeName(S.Context) << CSR
9315                 << E->getSourceRange(),
9316             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9317       else
9318         // FIXME: If this is an initializer list, suggest removing the braces
9319         // or inserting a cast to the target type.
9320         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9321             << isa<InitListExpr>(E) << ExprTy << CallType
9322             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9323       break;
9324     }
9325 
9326     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9327            "format string specifier index out of range");
9328     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9329   }
9330 
9331   return true;
9332 }
9333 
9334 //===--- CHECK: Scanf format string checking ------------------------------===//
9335 
9336 namespace {
9337 
9338 class CheckScanfHandler : public CheckFormatHandler {
9339 public:
CheckScanfHandler(Sema & s,const FormatStringLiteral * fexpr,const Expr * origFormatExpr,Sema::FormatStringType type,unsigned firstDataArg,unsigned numDataArgs,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg)9340   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9341                     const Expr *origFormatExpr, Sema::FormatStringType type,
9342                     unsigned firstDataArg, unsigned numDataArgs,
9343                     const char *beg, bool hasVAListArg,
9344                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9345                     bool inFunctionCall, Sema::VariadicCallType CallType,
9346                     llvm::SmallBitVector &CheckedVarArgs,
9347                     UncoveredArgHandler &UncoveredArg)
9348       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9349                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9350                            inFunctionCall, CallType, CheckedVarArgs,
9351                            UncoveredArg) {}
9352 
9353   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9354                             const char *startSpecifier,
9355                             unsigned specifierLen) override;
9356 
9357   bool HandleInvalidScanfConversionSpecifier(
9358           const analyze_scanf::ScanfSpecifier &FS,
9359           const char *startSpecifier,
9360           unsigned specifierLen) override;
9361 
9362   void HandleIncompleteScanList(const char *start, const char *end) override;
9363 };
9364 
9365 } // namespace
9366 
HandleIncompleteScanList(const char * start,const char * end)9367 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9368                                                  const char *end) {
9369   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9370                        getLocationOfByte(end), /*IsStringLocation*/true,
9371                        getSpecifierRange(start, end - start));
9372 }
9373 
HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)9374 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9375                                         const analyze_scanf::ScanfSpecifier &FS,
9376                                         const char *startSpecifier,
9377                                         unsigned specifierLen) {
9378   const analyze_scanf::ScanfConversionSpecifier &CS =
9379     FS.getConversionSpecifier();
9380 
9381   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9382                                           getLocationOfByte(CS.getStart()),
9383                                           startSpecifier, specifierLen,
9384                                           CS.getStart(), CS.getLength());
9385 }
9386 
HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)9387 bool CheckScanfHandler::HandleScanfSpecifier(
9388                                        const analyze_scanf::ScanfSpecifier &FS,
9389                                        const char *startSpecifier,
9390                                        unsigned specifierLen) {
9391   using namespace analyze_scanf;
9392   using namespace analyze_format_string;
9393 
9394   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9395 
9396   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9397   // be used to decide if we are using positional arguments consistently.
9398   if (FS.consumesDataArgument()) {
9399     if (atFirstArg) {
9400       atFirstArg = false;
9401       usesPositionalArgs = FS.usesPositionalArg();
9402     }
9403     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9404       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9405                                         startSpecifier, specifierLen);
9406       return false;
9407     }
9408   }
9409 
9410   // Check if the field with is non-zero.
9411   const OptionalAmount &Amt = FS.getFieldWidth();
9412   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9413     if (Amt.getConstantAmount() == 0) {
9414       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9415                                                    Amt.getConstantLength());
9416       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9417                            getLocationOfByte(Amt.getStart()),
9418                            /*IsStringLocation*/true, R,
9419                            FixItHint::CreateRemoval(R));
9420     }
9421   }
9422 
9423   if (!FS.consumesDataArgument()) {
9424     // FIXME: Technically specifying a precision or field width here
9425     // makes no sense.  Worth issuing a warning at some point.
9426     return true;
9427   }
9428 
9429   // Consume the argument.
9430   unsigned argIndex = FS.getArgIndex();
9431   if (argIndex < NumDataArgs) {
9432       // The check to see if the argIndex is valid will come later.
9433       // We set the bit here because we may exit early from this
9434       // function if we encounter some other error.
9435     CoveredArgs.set(argIndex);
9436   }
9437 
9438   // Check the length modifier is valid with the given conversion specifier.
9439   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9440                                  S.getLangOpts()))
9441     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9442                                 diag::warn_format_nonsensical_length);
9443   else if (!FS.hasStandardLengthModifier())
9444     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9445   else if (!FS.hasStandardLengthConversionCombination())
9446     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9447                                 diag::warn_format_non_standard_conversion_spec);
9448 
9449   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9450     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9451 
9452   // The remaining checks depend on the data arguments.
9453   if (HasVAListArg)
9454     return true;
9455 
9456   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9457     return false;
9458 
9459   // Check that the argument type matches the format specifier.
9460   const Expr *Ex = getDataArg(argIndex);
9461   if (!Ex)
9462     return true;
9463 
9464   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9465 
9466   if (!AT.isValid()) {
9467     return true;
9468   }
9469 
9470   analyze_format_string::ArgType::MatchKind Match =
9471       AT.matchesType(S.Context, Ex->getType());
9472   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9473   if (Match == analyze_format_string::ArgType::Match)
9474     return true;
9475 
9476   ScanfSpecifier fixedFS = FS;
9477   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9478                                  S.getLangOpts(), S.Context);
9479 
9480   unsigned Diag =
9481       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9482                : diag::warn_format_conversion_argument_type_mismatch;
9483 
9484   if (Success) {
9485     // Get the fix string from the fixed format specifier.
9486     SmallString<128> buf;
9487     llvm::raw_svector_ostream os(buf);
9488     fixedFS.toString(os);
9489 
9490     EmitFormatDiagnostic(
9491         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9492                       << Ex->getType() << false << Ex->getSourceRange(),
9493         Ex->getBeginLoc(),
9494         /*IsStringLocation*/ false,
9495         getSpecifierRange(startSpecifier, specifierLen),
9496         FixItHint::CreateReplacement(
9497             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9498   } else {
9499     EmitFormatDiagnostic(S.PDiag(Diag)
9500                              << AT.getRepresentativeTypeName(S.Context)
9501                              << Ex->getType() << false << Ex->getSourceRange(),
9502                          Ex->getBeginLoc(),
9503                          /*IsStringLocation*/ false,
9504                          getSpecifierRange(startSpecifier, specifierLen));
9505   }
9506 
9507   return true;
9508 }
9509 
CheckFormatString(Sema & S,const FormatStringLiteral * FExpr,const Expr * OrigFormatExpr,ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,Sema::FormatStringType Type,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs,UncoveredArgHandler & UncoveredArg,bool IgnoreStringsWithoutSpecifiers)9510 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9511                               const Expr *OrigFormatExpr,
9512                               ArrayRef<const Expr *> Args,
9513                               bool HasVAListArg, unsigned format_idx,
9514                               unsigned firstDataArg,
9515                               Sema::FormatStringType Type,
9516                               bool inFunctionCall,
9517                               Sema::VariadicCallType CallType,
9518                               llvm::SmallBitVector &CheckedVarArgs,
9519                               UncoveredArgHandler &UncoveredArg,
9520                               bool IgnoreStringsWithoutSpecifiers) {
9521   // CHECK: is the format string a wide literal?
9522   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9523     CheckFormatHandler::EmitFormatDiagnostic(
9524         S, inFunctionCall, Args[format_idx],
9525         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9526         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9527     return;
9528   }
9529 
9530   // Str - The format string.  NOTE: this is NOT null-terminated!
9531   StringRef StrRef = FExpr->getString();
9532   const char *Str = StrRef.data();
9533   // Account for cases where the string literal is truncated in a declaration.
9534   const ConstantArrayType *T =
9535     S.Context.getAsConstantArrayType(FExpr->getType());
9536   assert(T && "String literal not of constant array type!");
9537   size_t TypeSize = T->getSize().getZExtValue();
9538   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9539   const unsigned numDataArgs = Args.size() - firstDataArg;
9540 
9541   if (IgnoreStringsWithoutSpecifiers &&
9542       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9543           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9544     return;
9545 
9546   // Emit a warning if the string literal is truncated and does not contain an
9547   // embedded null character.
9548   if (TypeSize <= StrRef.size() &&
9549       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9550     CheckFormatHandler::EmitFormatDiagnostic(
9551         S, inFunctionCall, Args[format_idx],
9552         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9553         FExpr->getBeginLoc(),
9554         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9555     return;
9556   }
9557 
9558   // CHECK: empty format string?
9559   if (StrLen == 0 && numDataArgs > 0) {
9560     CheckFormatHandler::EmitFormatDiagnostic(
9561         S, inFunctionCall, Args[format_idx],
9562         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9563         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9564     return;
9565   }
9566 
9567   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9568       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9569       Type == Sema::FST_OSTrace) {
9570     CheckPrintfHandler H(
9571         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9572         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9573         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9574         CheckedVarArgs, UncoveredArg);
9575 
9576     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9577                                                   S.getLangOpts(),
9578                                                   S.Context.getTargetInfo(),
9579                                             Type == Sema::FST_FreeBSDKPrintf))
9580       H.DoneProcessing();
9581   } else if (Type == Sema::FST_Scanf) {
9582     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9583                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9584                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9585 
9586     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9587                                                  S.getLangOpts(),
9588                                                  S.Context.getTargetInfo()))
9589       H.DoneProcessing();
9590   } // TODO: handle other formats
9591 }
9592 
FormatStringHasSArg(const StringLiteral * FExpr)9593 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9594   // Str - The format string.  NOTE: this is NOT null-terminated!
9595   StringRef StrRef = FExpr->getString();
9596   const char *Str = StrRef.data();
9597   // Account for cases where the string literal is truncated in a declaration.
9598   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9599   assert(T && "String literal not of constant array type!");
9600   size_t TypeSize = T->getSize().getZExtValue();
9601   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9602   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9603                                                          getLangOpts(),
9604                                                          Context.getTargetInfo());
9605 }
9606 
9607 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9608 
9609 // Returns the related absolute value function that is larger, of 0 if one
9610 // does not exist.
getLargerAbsoluteValueFunction(unsigned AbsFunction)9611 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9612   switch (AbsFunction) {
9613   default:
9614     return 0;
9615 
9616   case Builtin::BI__builtin_abs:
9617     return Builtin::BI__builtin_labs;
9618   case Builtin::BI__builtin_labs:
9619     return Builtin::BI__builtin_llabs;
9620   case Builtin::BI__builtin_llabs:
9621     return 0;
9622 
9623   case Builtin::BI__builtin_fabsf:
9624     return Builtin::BI__builtin_fabs;
9625   case Builtin::BI__builtin_fabs:
9626     return Builtin::BI__builtin_fabsl;
9627   case Builtin::BI__builtin_fabsl:
9628     return 0;
9629 
9630   case Builtin::BI__builtin_cabsf:
9631     return Builtin::BI__builtin_cabs;
9632   case Builtin::BI__builtin_cabs:
9633     return Builtin::BI__builtin_cabsl;
9634   case Builtin::BI__builtin_cabsl:
9635     return 0;
9636 
9637   case Builtin::BIabs:
9638     return Builtin::BIlabs;
9639   case Builtin::BIlabs:
9640     return Builtin::BIllabs;
9641   case Builtin::BIllabs:
9642     return 0;
9643 
9644   case Builtin::BIfabsf:
9645     return Builtin::BIfabs;
9646   case Builtin::BIfabs:
9647     return Builtin::BIfabsl;
9648   case Builtin::BIfabsl:
9649     return 0;
9650 
9651   case Builtin::BIcabsf:
9652    return Builtin::BIcabs;
9653   case Builtin::BIcabs:
9654     return Builtin::BIcabsl;
9655   case Builtin::BIcabsl:
9656     return 0;
9657   }
9658 }
9659 
9660 // Returns the argument type of the absolute value function.
getAbsoluteValueArgumentType(ASTContext & Context,unsigned AbsType)9661 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9662                                              unsigned AbsType) {
9663   if (AbsType == 0)
9664     return QualType();
9665 
9666   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9667   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9668   if (Error != ASTContext::GE_None)
9669     return QualType();
9670 
9671   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9672   if (!FT)
9673     return QualType();
9674 
9675   if (FT->getNumParams() != 1)
9676     return QualType();
9677 
9678   return FT->getParamType(0);
9679 }
9680 
9681 // Returns the best absolute value function, or zero, based on type and
9682 // current absolute value function.
getBestAbsFunction(ASTContext & Context,QualType ArgType,unsigned AbsFunctionKind)9683 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9684                                    unsigned AbsFunctionKind) {
9685   unsigned BestKind = 0;
9686   uint64_t ArgSize = Context.getTypeSize(ArgType);
9687   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9688        Kind = getLargerAbsoluteValueFunction(Kind)) {
9689     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9690     if (Context.getTypeSize(ParamType) >= ArgSize) {
9691       if (BestKind == 0)
9692         BestKind = Kind;
9693       else if (Context.hasSameType(ParamType, ArgType)) {
9694         BestKind = Kind;
9695         break;
9696       }
9697     }
9698   }
9699   return BestKind;
9700 }
9701 
9702 enum AbsoluteValueKind {
9703   AVK_Integer,
9704   AVK_Floating,
9705   AVK_Complex
9706 };
9707 
getAbsoluteValueKind(QualType T)9708 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9709   if (T->isIntegralOrEnumerationType())
9710     return AVK_Integer;
9711   if (T->isRealFloatingType())
9712     return AVK_Floating;
9713   if (T->isAnyComplexType())
9714     return AVK_Complex;
9715 
9716   llvm_unreachable("Type not integer, floating, or complex");
9717 }
9718 
9719 // Changes the absolute value function to a different type.  Preserves whether
9720 // the function is a builtin.
changeAbsFunction(unsigned AbsKind,AbsoluteValueKind ValueKind)9721 static unsigned changeAbsFunction(unsigned AbsKind,
9722                                   AbsoluteValueKind ValueKind) {
9723   switch (ValueKind) {
9724   case AVK_Integer:
9725     switch (AbsKind) {
9726     default:
9727       return 0;
9728     case Builtin::BI__builtin_fabsf:
9729     case Builtin::BI__builtin_fabs:
9730     case Builtin::BI__builtin_fabsl:
9731     case Builtin::BI__builtin_cabsf:
9732     case Builtin::BI__builtin_cabs:
9733     case Builtin::BI__builtin_cabsl:
9734       return Builtin::BI__builtin_abs;
9735     case Builtin::BIfabsf:
9736     case Builtin::BIfabs:
9737     case Builtin::BIfabsl:
9738     case Builtin::BIcabsf:
9739     case Builtin::BIcabs:
9740     case Builtin::BIcabsl:
9741       return Builtin::BIabs;
9742     }
9743   case AVK_Floating:
9744     switch (AbsKind) {
9745     default:
9746       return 0;
9747     case Builtin::BI__builtin_abs:
9748     case Builtin::BI__builtin_labs:
9749     case Builtin::BI__builtin_llabs:
9750     case Builtin::BI__builtin_cabsf:
9751     case Builtin::BI__builtin_cabs:
9752     case Builtin::BI__builtin_cabsl:
9753       return Builtin::BI__builtin_fabsf;
9754     case Builtin::BIabs:
9755     case Builtin::BIlabs:
9756     case Builtin::BIllabs:
9757     case Builtin::BIcabsf:
9758     case Builtin::BIcabs:
9759     case Builtin::BIcabsl:
9760       return Builtin::BIfabsf;
9761     }
9762   case AVK_Complex:
9763     switch (AbsKind) {
9764     default:
9765       return 0;
9766     case Builtin::BI__builtin_abs:
9767     case Builtin::BI__builtin_labs:
9768     case Builtin::BI__builtin_llabs:
9769     case Builtin::BI__builtin_fabsf:
9770     case Builtin::BI__builtin_fabs:
9771     case Builtin::BI__builtin_fabsl:
9772       return Builtin::BI__builtin_cabsf;
9773     case Builtin::BIabs:
9774     case Builtin::BIlabs:
9775     case Builtin::BIllabs:
9776     case Builtin::BIfabsf:
9777     case Builtin::BIfabs:
9778     case Builtin::BIfabsl:
9779       return Builtin::BIcabsf;
9780     }
9781   }
9782   llvm_unreachable("Unable to convert function");
9783 }
9784 
getAbsoluteValueFunctionKind(const FunctionDecl * FDecl)9785 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9786   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9787   if (!FnInfo)
9788     return 0;
9789 
9790   switch (FDecl->getBuiltinID()) {
9791   default:
9792     return 0;
9793   case Builtin::BI__builtin_abs:
9794   case Builtin::BI__builtin_fabs:
9795   case Builtin::BI__builtin_fabsf:
9796   case Builtin::BI__builtin_fabsl:
9797   case Builtin::BI__builtin_labs:
9798   case Builtin::BI__builtin_llabs:
9799   case Builtin::BI__builtin_cabs:
9800   case Builtin::BI__builtin_cabsf:
9801   case Builtin::BI__builtin_cabsl:
9802   case Builtin::BIabs:
9803   case Builtin::BIlabs:
9804   case Builtin::BIllabs:
9805   case Builtin::BIfabs:
9806   case Builtin::BIfabsf:
9807   case Builtin::BIfabsl:
9808   case Builtin::BIcabs:
9809   case Builtin::BIcabsf:
9810   case Builtin::BIcabsl:
9811     return FDecl->getBuiltinID();
9812   }
9813   llvm_unreachable("Unknown Builtin type");
9814 }
9815 
9816 // If the replacement is valid, emit a note with replacement function.
9817 // Additionally, suggest including the proper header if not already included.
emitReplacement(Sema & S,SourceLocation Loc,SourceRange Range,unsigned AbsKind,QualType ArgType)9818 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9819                             unsigned AbsKind, QualType ArgType) {
9820   bool EmitHeaderHint = true;
9821   const char *HeaderName = nullptr;
9822   const char *FunctionName = nullptr;
9823   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9824     FunctionName = "std::abs";
9825     if (ArgType->isIntegralOrEnumerationType()) {
9826       HeaderName = "cstdlib";
9827     } else if (ArgType->isRealFloatingType()) {
9828       HeaderName = "cmath";
9829     } else {
9830       llvm_unreachable("Invalid Type");
9831     }
9832 
9833     // Lookup all std::abs
9834     if (NamespaceDecl *Std = S.getStdNamespace()) {
9835       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9836       R.suppressDiagnostics();
9837       S.LookupQualifiedName(R, Std);
9838 
9839       for (const auto *I : R) {
9840         const FunctionDecl *FDecl = nullptr;
9841         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9842           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9843         } else {
9844           FDecl = dyn_cast<FunctionDecl>(I);
9845         }
9846         if (!FDecl)
9847           continue;
9848 
9849         // Found std::abs(), check that they are the right ones.
9850         if (FDecl->getNumParams() != 1)
9851           continue;
9852 
9853         // Check that the parameter type can handle the argument.
9854         QualType ParamType = FDecl->getParamDecl(0)->getType();
9855         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9856             S.Context.getTypeSize(ArgType) <=
9857                 S.Context.getTypeSize(ParamType)) {
9858           // Found a function, don't need the header hint.
9859           EmitHeaderHint = false;
9860           break;
9861         }
9862       }
9863     }
9864   } else {
9865     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9866     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9867 
9868     if (HeaderName) {
9869       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9870       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9871       R.suppressDiagnostics();
9872       S.LookupName(R, S.getCurScope());
9873 
9874       if (R.isSingleResult()) {
9875         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9876         if (FD && FD->getBuiltinID() == AbsKind) {
9877           EmitHeaderHint = false;
9878         } else {
9879           return;
9880         }
9881       } else if (!R.empty()) {
9882         return;
9883       }
9884     }
9885   }
9886 
9887   S.Diag(Loc, diag::note_replace_abs_function)
9888       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9889 
9890   if (!HeaderName)
9891     return;
9892 
9893   if (!EmitHeaderHint)
9894     return;
9895 
9896   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9897                                                     << FunctionName;
9898 }
9899 
9900 template <std::size_t StrLen>
IsStdFunction(const FunctionDecl * FDecl,const char (& Str)[StrLen])9901 static bool IsStdFunction(const FunctionDecl *FDecl,
9902                           const char (&Str)[StrLen]) {
9903   if (!FDecl)
9904     return false;
9905   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9906     return false;
9907   if (!FDecl->isInStdNamespace())
9908     return false;
9909 
9910   return true;
9911 }
9912 
9913 // Warn when using the wrong abs() function.
CheckAbsoluteValueFunction(const CallExpr * Call,const FunctionDecl * FDecl)9914 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9915                                       const FunctionDecl *FDecl) {
9916   if (Call->getNumArgs() != 1)
9917     return;
9918 
9919   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9920   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9921   if (AbsKind == 0 && !IsStdAbs)
9922     return;
9923 
9924   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9925   QualType ParamType = Call->getArg(0)->getType();
9926 
9927   // Unsigned types cannot be negative.  Suggest removing the absolute value
9928   // function call.
9929   if (ArgType->isUnsignedIntegerType()) {
9930     const char *FunctionName =
9931         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9932     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9933     Diag(Call->getExprLoc(), diag::note_remove_abs)
9934         << FunctionName
9935         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9936     return;
9937   }
9938 
9939   // Taking the absolute value of a pointer is very suspicious, they probably
9940   // wanted to index into an array, dereference a pointer, call a function, etc.
9941   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9942     unsigned DiagType = 0;
9943     if (ArgType->isFunctionType())
9944       DiagType = 1;
9945     else if (ArgType->isArrayType())
9946       DiagType = 2;
9947 
9948     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9949     return;
9950   }
9951 
9952   // std::abs has overloads which prevent most of the absolute value problems
9953   // from occurring.
9954   if (IsStdAbs)
9955     return;
9956 
9957   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9958   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9959 
9960   // The argument and parameter are the same kind.  Check if they are the right
9961   // size.
9962   if (ArgValueKind == ParamValueKind) {
9963     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9964       return;
9965 
9966     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9967     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9968         << FDecl << ArgType << ParamType;
9969 
9970     if (NewAbsKind == 0)
9971       return;
9972 
9973     emitReplacement(*this, Call->getExprLoc(),
9974                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9975     return;
9976   }
9977 
9978   // ArgValueKind != ParamValueKind
9979   // The wrong type of absolute value function was used.  Attempt to find the
9980   // proper one.
9981   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9982   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9983   if (NewAbsKind == 0)
9984     return;
9985 
9986   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9987       << FDecl << ParamValueKind << ArgValueKind;
9988 
9989   emitReplacement(*this, Call->getExprLoc(),
9990                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9991 }
9992 
9993 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
CheckMaxUnsignedZero(const CallExpr * Call,const FunctionDecl * FDecl)9994 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9995                                 const FunctionDecl *FDecl) {
9996   if (!Call || !FDecl) return;
9997 
9998   // Ignore template specializations and macros.
9999   if (inTemplateInstantiation()) return;
10000   if (Call->getExprLoc().isMacroID()) return;
10001 
10002   // Only care about the one template argument, two function parameter std::max
10003   if (Call->getNumArgs() != 2) return;
10004   if (!IsStdFunction(FDecl, "max")) return;
10005   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10006   if (!ArgList) return;
10007   if (ArgList->size() != 1) return;
10008 
10009   // Check that template type argument is unsigned integer.
10010   const auto& TA = ArgList->get(0);
10011   if (TA.getKind() != TemplateArgument::Type) return;
10012   QualType ArgType = TA.getAsType();
10013   if (!ArgType->isUnsignedIntegerType()) return;
10014 
10015   // See if either argument is a literal zero.
10016   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10017     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10018     if (!MTE) return false;
10019     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10020     if (!Num) return false;
10021     if (Num->getValue() != 0) return false;
10022     return true;
10023   };
10024 
10025   const Expr *FirstArg = Call->getArg(0);
10026   const Expr *SecondArg = Call->getArg(1);
10027   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10028   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10029 
10030   // Only warn when exactly one argument is zero.
10031   if (IsFirstArgZero == IsSecondArgZero) return;
10032 
10033   SourceRange FirstRange = FirstArg->getSourceRange();
10034   SourceRange SecondRange = SecondArg->getSourceRange();
10035 
10036   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10037 
10038   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10039       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10040 
10041   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10042   SourceRange RemovalRange;
10043   if (IsFirstArgZero) {
10044     RemovalRange = SourceRange(FirstRange.getBegin(),
10045                                SecondRange.getBegin().getLocWithOffset(-1));
10046   } else {
10047     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10048                                SecondRange.getEnd());
10049   }
10050 
10051   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10052         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10053         << FixItHint::CreateRemoval(RemovalRange);
10054 }
10055 
10056 //===--- CHECK: Standard memory functions ---------------------------------===//
10057 
10058 /// Takes the expression passed to the size_t parameter of functions
10059 /// such as memcmp, strncat, etc and warns if it's a comparison.
10060 ///
10061 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
CheckMemorySizeofForComparison(Sema & S,const Expr * E,IdentifierInfo * FnName,SourceLocation FnLoc,SourceLocation RParenLoc)10062 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10063                                            IdentifierInfo *FnName,
10064                                            SourceLocation FnLoc,
10065                                            SourceLocation RParenLoc) {
10066   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10067   if (!Size)
10068     return false;
10069 
10070   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10071   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10072     return false;
10073 
10074   SourceRange SizeRange = Size->getSourceRange();
10075   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10076       << SizeRange << FnName;
10077   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10078       << FnName
10079       << FixItHint::CreateInsertion(
10080              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10081       << FixItHint::CreateRemoval(RParenLoc);
10082   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10083       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10084       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10085                                     ")");
10086 
10087   return true;
10088 }
10089 
10090 /// Determine whether the given type is or contains a dynamic class type
10091 /// (e.g., whether it has a vtable).
getContainedDynamicClass(QualType T,bool & IsContained)10092 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10093                                                      bool &IsContained) {
10094   // Look through array types while ignoring qualifiers.
10095   const Type *Ty = T->getBaseElementTypeUnsafe();
10096   IsContained = false;
10097 
10098   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10099   RD = RD ? RD->getDefinition() : nullptr;
10100   if (!RD || RD->isInvalidDecl())
10101     return nullptr;
10102 
10103   if (RD->isDynamicClass())
10104     return RD;
10105 
10106   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10107   // It's impossible for a class to transitively contain itself by value, so
10108   // infinite recursion is impossible.
10109   for (auto *FD : RD->fields()) {
10110     bool SubContained;
10111     if (const CXXRecordDecl *ContainedRD =
10112             getContainedDynamicClass(FD->getType(), SubContained)) {
10113       IsContained = true;
10114       return ContainedRD;
10115     }
10116   }
10117 
10118   return nullptr;
10119 }
10120 
getAsSizeOfExpr(const Expr * E)10121 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10122   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10123     if (Unary->getKind() == UETT_SizeOf)
10124       return Unary;
10125   return nullptr;
10126 }
10127 
10128 /// If E is a sizeof expression, returns its argument expression,
10129 /// otherwise returns NULL.
getSizeOfExprArg(const Expr * E)10130 static const Expr *getSizeOfExprArg(const Expr *E) {
10131   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10132     if (!SizeOf->isArgumentType())
10133       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10134   return nullptr;
10135 }
10136 
10137 /// If E is a sizeof expression, returns its argument type.
getSizeOfArgType(const Expr * E)10138 static QualType getSizeOfArgType(const Expr *E) {
10139   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10140     return SizeOf->getTypeOfArgument();
10141   return QualType();
10142 }
10143 
10144 namespace {
10145 
10146 struct SearchNonTrivialToInitializeField
10147     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10148   using Super =
10149       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10150 
SearchNonTrivialToInitializeField__anona96a15881711::SearchNonTrivialToInitializeField10151   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10152 
visitWithKind__anona96a15881711::SearchNonTrivialToInitializeField10153   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10154                      SourceLocation SL) {
10155     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10156       asDerived().visitArray(PDIK, AT, SL);
10157       return;
10158     }
10159 
10160     Super::visitWithKind(PDIK, FT, SL);
10161   }
10162 
visitARCStrong__anona96a15881711::SearchNonTrivialToInitializeField10163   void visitARCStrong(QualType FT, SourceLocation SL) {
10164     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10165   }
visitARCWeak__anona96a15881711::SearchNonTrivialToInitializeField10166   void visitARCWeak(QualType FT, SourceLocation SL) {
10167     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10168   }
visitStruct__anona96a15881711::SearchNonTrivialToInitializeField10169   void visitStruct(QualType FT, SourceLocation SL) {
10170     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10171       visit(FD->getType(), FD->getLocation());
10172   }
visitArray__anona96a15881711::SearchNonTrivialToInitializeField10173   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10174                   const ArrayType *AT, SourceLocation SL) {
10175     visit(getContext().getBaseElementType(AT), SL);
10176   }
visitTrivial__anona96a15881711::SearchNonTrivialToInitializeField10177   void visitTrivial(QualType FT, SourceLocation SL) {}
10178 
diag__anona96a15881711::SearchNonTrivialToInitializeField10179   static void diag(QualType RT, const Expr *E, Sema &S) {
10180     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10181   }
10182 
getContext__anona96a15881711::SearchNonTrivialToInitializeField10183   ASTContext &getContext() { return S.getASTContext(); }
10184 
10185   const Expr *E;
10186   Sema &S;
10187 };
10188 
10189 struct SearchNonTrivialToCopyField
10190     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10191   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10192 
SearchNonTrivialToCopyField__anona96a15881711::SearchNonTrivialToCopyField10193   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10194 
visitWithKind__anona96a15881711::SearchNonTrivialToCopyField10195   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10196                      SourceLocation SL) {
10197     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10198       asDerived().visitArray(PCK, AT, SL);
10199       return;
10200     }
10201 
10202     Super::visitWithKind(PCK, FT, SL);
10203   }
10204 
visitARCStrong__anona96a15881711::SearchNonTrivialToCopyField10205   void visitARCStrong(QualType FT, SourceLocation SL) {
10206     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10207   }
visitARCWeak__anona96a15881711::SearchNonTrivialToCopyField10208   void visitARCWeak(QualType FT, SourceLocation SL) {
10209     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10210   }
visitStruct__anona96a15881711::SearchNonTrivialToCopyField10211   void visitStruct(QualType FT, SourceLocation SL) {
10212     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10213       visit(FD->getType(), FD->getLocation());
10214   }
visitArray__anona96a15881711::SearchNonTrivialToCopyField10215   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10216                   SourceLocation SL) {
10217     visit(getContext().getBaseElementType(AT), SL);
10218   }
preVisit__anona96a15881711::SearchNonTrivialToCopyField10219   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10220                 SourceLocation SL) {}
visitTrivial__anona96a15881711::SearchNonTrivialToCopyField10221   void visitTrivial(QualType FT, SourceLocation SL) {}
visitVolatileTrivial__anona96a15881711::SearchNonTrivialToCopyField10222   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10223 
diag__anona96a15881711::SearchNonTrivialToCopyField10224   static void diag(QualType RT, const Expr *E, Sema &S) {
10225     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10226   }
10227 
getContext__anona96a15881711::SearchNonTrivialToCopyField10228   ASTContext &getContext() { return S.getASTContext(); }
10229 
10230   const Expr *E;
10231   Sema &S;
10232 };
10233 
10234 }
10235 
10236 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
doesExprLikelyComputeSize(const Expr * SizeofExpr)10237 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10238   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10239 
10240   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10241     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10242       return false;
10243 
10244     return doesExprLikelyComputeSize(BO->getLHS()) ||
10245            doesExprLikelyComputeSize(BO->getRHS());
10246   }
10247 
10248   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10249 }
10250 
10251 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10252 ///
10253 /// \code
10254 ///   #define MACRO 0
10255 ///   foo(MACRO);
10256 ///   foo(0);
10257 /// \endcode
10258 ///
10259 /// This should return true for the first call to foo, but not for the second
10260 /// (regardless of whether foo is a macro or function).
isArgumentExpandedFromMacro(SourceManager & SM,SourceLocation CallLoc,SourceLocation ArgLoc)10261 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10262                                         SourceLocation CallLoc,
10263                                         SourceLocation ArgLoc) {
10264   if (!CallLoc.isMacroID())
10265     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10266 
10267   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10268          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10269 }
10270 
10271 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10272 /// last two arguments transposed.
CheckMemaccessSize(Sema & S,unsigned BId,const CallExpr * Call)10273 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10274   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10275     return;
10276 
10277   const Expr *SizeArg =
10278     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10279 
10280   auto isLiteralZero = [](const Expr *E) {
10281     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10282   };
10283 
10284   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10285   SourceLocation CallLoc = Call->getRParenLoc();
10286   SourceManager &SM = S.getSourceManager();
10287   if (isLiteralZero(SizeArg) &&
10288       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10289 
10290     SourceLocation DiagLoc = SizeArg->getExprLoc();
10291 
10292     // Some platforms #define bzero to __builtin_memset. See if this is the
10293     // case, and if so, emit a better diagnostic.
10294     if (BId == Builtin::BIbzero ||
10295         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10296                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10297       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10298       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10299     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10300       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10301       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10302     }
10303     return;
10304   }
10305 
10306   // If the second argument to a memset is a sizeof expression and the third
10307   // isn't, this is also likely an error. This should catch
10308   // 'memset(buf, sizeof(buf), 0xff)'.
10309   if (BId == Builtin::BImemset &&
10310       doesExprLikelyComputeSize(Call->getArg(1)) &&
10311       !doesExprLikelyComputeSize(Call->getArg(2))) {
10312     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10313     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10314     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10315     return;
10316   }
10317 }
10318 
10319 /// Check for dangerous or invalid arguments to memset().
10320 ///
10321 /// This issues warnings on known problematic, dangerous or unspecified
10322 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10323 /// function calls.
10324 ///
10325 /// \param Call The call expression to diagnose.
CheckMemaccessArguments(const CallExpr * Call,unsigned BId,IdentifierInfo * FnName)10326 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10327                                    unsigned BId,
10328                                    IdentifierInfo *FnName) {
10329   assert(BId != 0);
10330 
10331   // It is possible to have a non-standard definition of memset.  Validate
10332   // we have enough arguments, and if not, abort further checking.
10333   unsigned ExpectedNumArgs =
10334       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10335   if (Call->getNumArgs() < ExpectedNumArgs)
10336     return;
10337 
10338   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10339                       BId == Builtin::BIstrndup ? 1 : 2);
10340   unsigned LenArg =
10341       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10342   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10343 
10344   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10345                                      Call->getBeginLoc(), Call->getRParenLoc()))
10346     return;
10347 
10348   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10349   CheckMemaccessSize(*this, BId, Call);
10350 
10351   // We have special checking when the length is a sizeof expression.
10352   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10353   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10354   llvm::FoldingSetNodeID SizeOfArgID;
10355 
10356   // Although widely used, 'bzero' is not a standard function. Be more strict
10357   // with the argument types before allowing diagnostics and only allow the
10358   // form bzero(ptr, sizeof(...)).
10359   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10360   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10361     return;
10362 
10363   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10364     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10365     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10366 
10367     QualType DestTy = Dest->getType();
10368     QualType PointeeTy;
10369     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10370       PointeeTy = DestPtrTy->getPointeeType();
10371 
10372       // Never warn about void type pointers. This can be used to suppress
10373       // false positives.
10374       if (PointeeTy->isVoidType())
10375         continue;
10376 
10377       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10378       // actually comparing the expressions for equality. Because computing the
10379       // expression IDs can be expensive, we only do this if the diagnostic is
10380       // enabled.
10381       if (SizeOfArg &&
10382           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10383                            SizeOfArg->getExprLoc())) {
10384         // We only compute IDs for expressions if the warning is enabled, and
10385         // cache the sizeof arg's ID.
10386         if (SizeOfArgID == llvm::FoldingSetNodeID())
10387           SizeOfArg->Profile(SizeOfArgID, Context, true);
10388         llvm::FoldingSetNodeID DestID;
10389         Dest->Profile(DestID, Context, true);
10390         if (DestID == SizeOfArgID) {
10391           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10392           //       over sizeof(src) as well.
10393           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10394           StringRef ReadableName = FnName->getName();
10395 
10396           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10397             if (UnaryOp->getOpcode() == UO_AddrOf)
10398               ActionIdx = 1; // If its an address-of operator, just remove it.
10399           if (!PointeeTy->isIncompleteType() &&
10400               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10401             ActionIdx = 2; // If the pointee's size is sizeof(char),
10402                            // suggest an explicit length.
10403 
10404           // If the function is defined as a builtin macro, do not show macro
10405           // expansion.
10406           SourceLocation SL = SizeOfArg->getExprLoc();
10407           SourceRange DSR = Dest->getSourceRange();
10408           SourceRange SSR = SizeOfArg->getSourceRange();
10409           SourceManager &SM = getSourceManager();
10410 
10411           if (SM.isMacroArgExpansion(SL)) {
10412             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10413             SL = SM.getSpellingLoc(SL);
10414             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10415                              SM.getSpellingLoc(DSR.getEnd()));
10416             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10417                              SM.getSpellingLoc(SSR.getEnd()));
10418           }
10419 
10420           DiagRuntimeBehavior(SL, SizeOfArg,
10421                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10422                                 << ReadableName
10423                                 << PointeeTy
10424                                 << DestTy
10425                                 << DSR
10426                                 << SSR);
10427           DiagRuntimeBehavior(SL, SizeOfArg,
10428                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10429                                 << ActionIdx
10430                                 << SSR);
10431 
10432           break;
10433         }
10434       }
10435 
10436       // Also check for cases where the sizeof argument is the exact same
10437       // type as the memory argument, and where it points to a user-defined
10438       // record type.
10439       if (SizeOfArgTy != QualType()) {
10440         if (PointeeTy->isRecordType() &&
10441             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10442           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10443                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10444                                 << FnName << SizeOfArgTy << ArgIdx
10445                                 << PointeeTy << Dest->getSourceRange()
10446                                 << LenExpr->getSourceRange());
10447           break;
10448         }
10449       }
10450     } else if (DestTy->isArrayType()) {
10451       PointeeTy = DestTy;
10452     }
10453 
10454     if (PointeeTy == QualType())
10455       continue;
10456 
10457     // Always complain about dynamic classes.
10458     bool IsContained;
10459     if (const CXXRecordDecl *ContainedRD =
10460             getContainedDynamicClass(PointeeTy, IsContained)) {
10461 
10462       unsigned OperationType = 0;
10463       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10464       // "overwritten" if we're warning about the destination for any call
10465       // but memcmp; otherwise a verb appropriate to the call.
10466       if (ArgIdx != 0 || IsCmp) {
10467         if (BId == Builtin::BImemcpy)
10468           OperationType = 1;
10469         else if(BId == Builtin::BImemmove)
10470           OperationType = 2;
10471         else if (IsCmp)
10472           OperationType = 3;
10473       }
10474 
10475       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10476                           PDiag(diag::warn_dyn_class_memaccess)
10477                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10478                               << IsContained << ContainedRD << OperationType
10479                               << Call->getCallee()->getSourceRange());
10480     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10481              BId != Builtin::BImemset)
10482       DiagRuntimeBehavior(
10483         Dest->getExprLoc(), Dest,
10484         PDiag(diag::warn_arc_object_memaccess)
10485           << ArgIdx << FnName << PointeeTy
10486           << Call->getCallee()->getSourceRange());
10487     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10488       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10489           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10490         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10491                             PDiag(diag::warn_cstruct_memaccess)
10492                                 << ArgIdx << FnName << PointeeTy << 0);
10493         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10494       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10495                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10496         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10497                             PDiag(diag::warn_cstruct_memaccess)
10498                                 << ArgIdx << FnName << PointeeTy << 1);
10499         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10500       } else {
10501         continue;
10502       }
10503     } else
10504       continue;
10505 
10506     DiagRuntimeBehavior(
10507       Dest->getExprLoc(), Dest,
10508       PDiag(diag::note_bad_memaccess_silence)
10509         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10510     break;
10511   }
10512 }
10513 
10514 // A little helper routine: ignore addition and subtraction of integer literals.
10515 // This intentionally does not ignore all integer constant expressions because
10516 // we don't want to remove sizeof().
ignoreLiteralAdditions(const Expr * Ex,ASTContext & Ctx)10517 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10518   Ex = Ex->IgnoreParenCasts();
10519 
10520   while (true) {
10521     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10522     if (!BO || !BO->isAdditiveOp())
10523       break;
10524 
10525     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10526     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10527 
10528     if (isa<IntegerLiteral>(RHS))
10529       Ex = LHS;
10530     else if (isa<IntegerLiteral>(LHS))
10531       Ex = RHS;
10532     else
10533       break;
10534   }
10535 
10536   return Ex;
10537 }
10538 
isConstantSizeArrayWithMoreThanOneElement(QualType Ty,ASTContext & Context)10539 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10540                                                       ASTContext &Context) {
10541   // Only handle constant-sized or VLAs, but not flexible members.
10542   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10543     // Only issue the FIXIT for arrays of size > 1.
10544     if (CAT->getSize().getSExtValue() <= 1)
10545       return false;
10546   } else if (!Ty->isVariableArrayType()) {
10547     return false;
10548   }
10549   return true;
10550 }
10551 
10552 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10553 // be the size of the source, instead of the destination.
CheckStrlcpycatArguments(const CallExpr * Call,IdentifierInfo * FnName)10554 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10555                                     IdentifierInfo *FnName) {
10556 
10557   // Don't crash if the user has the wrong number of arguments
10558   unsigned NumArgs = Call->getNumArgs();
10559   if ((NumArgs != 3) && (NumArgs != 4))
10560     return;
10561 
10562   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10563   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10564   const Expr *CompareWithSrc = nullptr;
10565 
10566   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10567                                      Call->getBeginLoc(), Call->getRParenLoc()))
10568     return;
10569 
10570   // Look for 'strlcpy(dst, x, sizeof(x))'
10571   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10572     CompareWithSrc = Ex;
10573   else {
10574     // Look for 'strlcpy(dst, x, strlen(x))'
10575     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10576       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10577           SizeCall->getNumArgs() == 1)
10578         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10579     }
10580   }
10581 
10582   if (!CompareWithSrc)
10583     return;
10584 
10585   // Determine if the argument to sizeof/strlen is equal to the source
10586   // argument.  In principle there's all kinds of things you could do
10587   // here, for instance creating an == expression and evaluating it with
10588   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10589   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10590   if (!SrcArgDRE)
10591     return;
10592 
10593   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10594   if (!CompareWithSrcDRE ||
10595       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10596     return;
10597 
10598   const Expr *OriginalSizeArg = Call->getArg(2);
10599   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10600       << OriginalSizeArg->getSourceRange() << FnName;
10601 
10602   // Output a FIXIT hint if the destination is an array (rather than a
10603   // pointer to an array).  This could be enhanced to handle some
10604   // pointers if we know the actual size, like if DstArg is 'array+2'
10605   // we could say 'sizeof(array)-2'.
10606   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10607   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10608     return;
10609 
10610   SmallString<128> sizeString;
10611   llvm::raw_svector_ostream OS(sizeString);
10612   OS << "sizeof(";
10613   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10614   OS << ")";
10615 
10616   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10617       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10618                                       OS.str());
10619 }
10620 
10621 /// Check if two expressions refer to the same declaration.
referToTheSameDecl(const Expr * E1,const Expr * E2)10622 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10623   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10624     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10625       return D1->getDecl() == D2->getDecl();
10626   return false;
10627 }
10628 
getStrlenExprArg(const Expr * E)10629 static const Expr *getStrlenExprArg(const Expr *E) {
10630   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10631     const FunctionDecl *FD = CE->getDirectCallee();
10632     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10633       return nullptr;
10634     return CE->getArg(0)->IgnoreParenCasts();
10635   }
10636   return nullptr;
10637 }
10638 
10639 // Warn on anti-patterns as the 'size' argument to strncat.
10640 // The correct size argument should look like following:
10641 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
CheckStrncatArguments(const CallExpr * CE,IdentifierInfo * FnName)10642 void Sema::CheckStrncatArguments(const CallExpr *CE,
10643                                  IdentifierInfo *FnName) {
10644   // Don't crash if the user has the wrong number of arguments.
10645   if (CE->getNumArgs() < 3)
10646     return;
10647   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10648   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10649   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10650 
10651   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10652                                      CE->getRParenLoc()))
10653     return;
10654 
10655   // Identify common expressions, which are wrongly used as the size argument
10656   // to strncat and may lead to buffer overflows.
10657   unsigned PatternType = 0;
10658   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10659     // - sizeof(dst)
10660     if (referToTheSameDecl(SizeOfArg, DstArg))
10661       PatternType = 1;
10662     // - sizeof(src)
10663     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10664       PatternType = 2;
10665   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10666     if (BE->getOpcode() == BO_Sub) {
10667       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10668       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10669       // - sizeof(dst) - strlen(dst)
10670       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10671           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10672         PatternType = 1;
10673       // - sizeof(src) - (anything)
10674       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10675         PatternType = 2;
10676     }
10677   }
10678 
10679   if (PatternType == 0)
10680     return;
10681 
10682   // Generate the diagnostic.
10683   SourceLocation SL = LenArg->getBeginLoc();
10684   SourceRange SR = LenArg->getSourceRange();
10685   SourceManager &SM = getSourceManager();
10686 
10687   // If the function is defined as a builtin macro, do not show macro expansion.
10688   if (SM.isMacroArgExpansion(SL)) {
10689     SL = SM.getSpellingLoc(SL);
10690     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10691                      SM.getSpellingLoc(SR.getEnd()));
10692   }
10693 
10694   // Check if the destination is an array (rather than a pointer to an array).
10695   QualType DstTy = DstArg->getType();
10696   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10697                                                                     Context);
10698   if (!isKnownSizeArray) {
10699     if (PatternType == 1)
10700       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10701     else
10702       Diag(SL, diag::warn_strncat_src_size) << SR;
10703     return;
10704   }
10705 
10706   if (PatternType == 1)
10707     Diag(SL, diag::warn_strncat_large_size) << SR;
10708   else
10709     Diag(SL, diag::warn_strncat_src_size) << SR;
10710 
10711   SmallString<128> sizeString;
10712   llvm::raw_svector_ostream OS(sizeString);
10713   OS << "sizeof(";
10714   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10715   OS << ") - ";
10716   OS << "strlen(";
10717   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10718   OS << ") - 1";
10719 
10720   Diag(SL, diag::note_strncat_wrong_size)
10721     << FixItHint::CreateReplacement(SR, OS.str());
10722 }
10723 
10724 namespace {
CheckFreeArgumentsOnLvalue(Sema & S,const std::string & CalleeName,const UnaryOperator * UnaryExpr,const Decl * D)10725 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10726                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10727   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10728     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10729         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10730     return;
10731   }
10732 }
10733 
CheckFreeArgumentsAddressof(Sema & S,const std::string & CalleeName,const UnaryOperator * UnaryExpr)10734 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10735                                  const UnaryOperator *UnaryExpr) {
10736   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10737     const Decl *D = Lvalue->getDecl();
10738     if (isa<DeclaratorDecl>(D))
10739       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10740         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10741   }
10742 
10743   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10744     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10745                                       Lvalue->getMemberDecl());
10746 }
10747 
CheckFreeArgumentsPlus(Sema & S,const std::string & CalleeName,const UnaryOperator * UnaryExpr)10748 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10749                             const UnaryOperator *UnaryExpr) {
10750   const auto *Lambda = dyn_cast<LambdaExpr>(
10751       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10752   if (!Lambda)
10753     return;
10754 
10755   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10756       << CalleeName << 2 /*object: lambda expression*/;
10757 }
10758 
CheckFreeArgumentsStackArray(Sema & S,const std::string & CalleeName,const DeclRefExpr * Lvalue)10759 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10760                                   const DeclRefExpr *Lvalue) {
10761   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10762   if (Var == nullptr)
10763     return;
10764 
10765   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10766       << CalleeName << 0 /*object: */ << Var;
10767 }
10768 
CheckFreeArgumentsCast(Sema & S,const std::string & CalleeName,const CastExpr * Cast)10769 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10770                             const CastExpr *Cast) {
10771   SmallString<128> SizeString;
10772   llvm::raw_svector_ostream OS(SizeString);
10773 
10774   clang::CastKind Kind = Cast->getCastKind();
10775   if (Kind == clang::CK_BitCast &&
10776       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10777     return;
10778   if (Kind == clang::CK_IntegralToPointer &&
10779       !isa<IntegerLiteral>(
10780           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10781     return;
10782 
10783   switch (Cast->getCastKind()) {
10784   case clang::CK_BitCast:
10785   case clang::CK_IntegralToPointer:
10786   case clang::CK_FunctionToPointerDecay:
10787     OS << '\'';
10788     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10789     OS << '\'';
10790     break;
10791   default:
10792     return;
10793   }
10794 
10795   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10796       << CalleeName << 0 /*object: */ << OS.str();
10797 }
10798 } // namespace
10799 
10800 /// Alerts the user that they are attempting to free a non-malloc'd object.
CheckFreeArguments(const CallExpr * E)10801 void Sema::CheckFreeArguments(const CallExpr *E) {
10802   const std::string CalleeName =
10803       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10804 
10805   { // Prefer something that doesn't involve a cast to make things simpler.
10806     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10807     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10808       switch (UnaryExpr->getOpcode()) {
10809       case UnaryOperator::Opcode::UO_AddrOf:
10810         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10811       case UnaryOperator::Opcode::UO_Plus:
10812         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10813       default:
10814         break;
10815       }
10816 
10817     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10818       if (Lvalue->getType()->isArrayType())
10819         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10820 
10821     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10822       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10823           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10824       return;
10825     }
10826 
10827     if (isa<BlockExpr>(Arg)) {
10828       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10829           << CalleeName << 1 /*object: block*/;
10830       return;
10831     }
10832   }
10833   // Maybe the cast was important, check after the other cases.
10834   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10835     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10836 }
10837 
10838 void
CheckReturnValExpr(Expr * RetValExp,QualType lhsType,SourceLocation ReturnLoc,bool isObjCMethod,const AttrVec * Attrs,const FunctionDecl * FD)10839 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10840                          SourceLocation ReturnLoc,
10841                          bool isObjCMethod,
10842                          const AttrVec *Attrs,
10843                          const FunctionDecl *FD) {
10844   // Check if the return value is null but should not be.
10845   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10846        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10847       CheckNonNullExpr(*this, RetValExp))
10848     Diag(ReturnLoc, diag::warn_null_ret)
10849       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10850 
10851   // C++11 [basic.stc.dynamic.allocation]p4:
10852   //   If an allocation function declared with a non-throwing
10853   //   exception-specification fails to allocate storage, it shall return
10854   //   a null pointer. Any other allocation function that fails to allocate
10855   //   storage shall indicate failure only by throwing an exception [...]
10856   if (FD) {
10857     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10858     if (Op == OO_New || Op == OO_Array_New) {
10859       const FunctionProtoType *Proto
10860         = FD->getType()->castAs<FunctionProtoType>();
10861       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10862           CheckNonNullExpr(*this, RetValExp))
10863         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10864           << FD << getLangOpts().CPlusPlus11;
10865     }
10866   }
10867 
10868   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10869   // here prevent the user from using a PPC MMA type as trailing return type.
10870   if (Context.getTargetInfo().getTriple().isPPC64())
10871     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10872 }
10873 
10874 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10875 
10876 /// Check for comparisons of floating point operands using != and ==.
10877 /// Issue a warning if these are no self-comparisons, as they are not likely
10878 /// to do what the programmer intended.
CheckFloatComparison(SourceLocation Loc,Expr * LHS,Expr * RHS)10879 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10880   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10881   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10882 
10883   // Special case: check for x == x (which is OK).
10884   // Do not emit warnings for such cases.
10885   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10886     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10887       if (DRL->getDecl() == DRR->getDecl())
10888         return;
10889 
10890   // Special case: check for comparisons against literals that can be exactly
10891   //  represented by APFloat.  In such cases, do not emit a warning.  This
10892   //  is a heuristic: often comparison against such literals are used to
10893   //  detect if a value in a variable has not changed.  This clearly can
10894   //  lead to false negatives.
10895   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10896     if (FLL->isExact())
10897       return;
10898   } else
10899     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10900       if (FLR->isExact())
10901         return;
10902 
10903   // Check for comparisons with builtin types.
10904   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10905     if (CL->getBuiltinCallee())
10906       return;
10907 
10908   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10909     if (CR->getBuiltinCallee())
10910       return;
10911 
10912   // Emit the diagnostic.
10913   Diag(Loc, diag::warn_floatingpoint_eq)
10914     << LHS->getSourceRange() << RHS->getSourceRange();
10915 }
10916 
10917 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10918 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10919 
10920 namespace {
10921 
10922 /// Structure recording the 'active' range of an integer-valued
10923 /// expression.
10924 struct IntRange {
10925   /// The number of bits active in the int. Note that this includes exactly one
10926   /// sign bit if !NonNegative.
10927   unsigned Width;
10928 
10929   /// True if the int is known not to have negative values. If so, all leading
10930   /// bits before Width are known zero, otherwise they are known to be the
10931   /// same as the MSB within Width.
10932   bool NonNegative;
10933 
IntRange__anona96a15881a11::IntRange10934   IntRange(unsigned Width, bool NonNegative)
10935       : Width(Width), NonNegative(NonNegative) {}
10936 
10937   /// Number of bits excluding the sign bit.
valueBits__anona96a15881a11::IntRange10938   unsigned valueBits() const {
10939     return NonNegative ? Width : Width - 1;
10940   }
10941 
10942   /// Returns the range of the bool type.
forBoolType__anona96a15881a11::IntRange10943   static IntRange forBoolType() {
10944     return IntRange(1, true);
10945   }
10946 
10947   /// Returns the range of an opaque value of the given integral type.
forValueOfType__anona96a15881a11::IntRange10948   static IntRange forValueOfType(ASTContext &C, QualType T) {
10949     return forValueOfCanonicalType(C,
10950                           T->getCanonicalTypeInternal().getTypePtr());
10951   }
10952 
10953   /// Returns the range of an opaque value of a canonical integral type.
forValueOfCanonicalType__anona96a15881a11::IntRange10954   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10955     assert(T->isCanonicalUnqualified());
10956 
10957     if (const VectorType *VT = dyn_cast<VectorType>(T))
10958       T = VT->getElementType().getTypePtr();
10959     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10960       T = CT->getElementType().getTypePtr();
10961     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10962       T = AT->getValueType().getTypePtr();
10963 
10964     if (!C.getLangOpts().CPlusPlus) {
10965       // For enum types in C code, use the underlying datatype.
10966       if (const EnumType *ET = dyn_cast<EnumType>(T))
10967         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10968     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10969       // For enum types in C++, use the known bit width of the enumerators.
10970       EnumDecl *Enum = ET->getDecl();
10971       // In C++11, enums can have a fixed underlying type. Use this type to
10972       // compute the range.
10973       if (Enum->isFixed()) {
10974         return IntRange(C.getIntWidth(QualType(T, 0)),
10975                         !ET->isSignedIntegerOrEnumerationType());
10976       }
10977 
10978       unsigned NumPositive = Enum->getNumPositiveBits();
10979       unsigned NumNegative = Enum->getNumNegativeBits();
10980 
10981       if (NumNegative == 0)
10982         return IntRange(NumPositive, true/*NonNegative*/);
10983       else
10984         return IntRange(std::max(NumPositive + 1, NumNegative),
10985                         false/*NonNegative*/);
10986     }
10987 
10988     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10989       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10990 
10991     const BuiltinType *BT = cast<BuiltinType>(T);
10992     assert(BT->isInteger());
10993 
10994     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10995   }
10996 
10997   /// Returns the "target" range of a canonical integral type, i.e.
10998   /// the range of values expressible in the type.
10999   ///
11000   /// This matches forValueOfCanonicalType except that enums have the
11001   /// full range of their type, not the range of their enumerators.
forTargetOfCanonicalType__anona96a15881a11::IntRange11002   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11003     assert(T->isCanonicalUnqualified());
11004 
11005     if (const VectorType *VT = dyn_cast<VectorType>(T))
11006       T = VT->getElementType().getTypePtr();
11007     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11008       T = CT->getElementType().getTypePtr();
11009     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11010       T = AT->getValueType().getTypePtr();
11011     if (const EnumType *ET = dyn_cast<EnumType>(T))
11012       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11013 
11014     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11015       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11016 
11017     const BuiltinType *BT = cast<BuiltinType>(T);
11018     assert(BT->isInteger());
11019 
11020     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11021   }
11022 
11023   /// Returns the supremum of two ranges: i.e. their conservative merge.
join__anona96a15881a11::IntRange11024   static IntRange join(IntRange L, IntRange R) {
11025     bool Unsigned = L.NonNegative && R.NonNegative;
11026     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11027                     L.NonNegative && R.NonNegative);
11028   }
11029 
11030   /// Return the range of a bitwise-AND of the two ranges.
bit_and__anona96a15881a11::IntRange11031   static IntRange bit_and(IntRange L, IntRange R) {
11032     unsigned Bits = std::max(L.Width, R.Width);
11033     bool NonNegative = false;
11034     if (L.NonNegative) {
11035       Bits = std::min(Bits, L.Width);
11036       NonNegative = true;
11037     }
11038     if (R.NonNegative) {
11039       Bits = std::min(Bits, R.Width);
11040       NonNegative = true;
11041     }
11042     return IntRange(Bits, NonNegative);
11043   }
11044 
11045   /// Return the range of a sum of the two ranges.
sum__anona96a15881a11::IntRange11046   static IntRange sum(IntRange L, IntRange R) {
11047     bool Unsigned = L.NonNegative && R.NonNegative;
11048     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11049                     Unsigned);
11050   }
11051 
11052   /// Return the range of a difference of the two ranges.
difference__anona96a15881a11::IntRange11053   static IntRange difference(IntRange L, IntRange R) {
11054     // We need a 1-bit-wider range if:
11055     //   1) LHS can be negative: least value can be reduced.
11056     //   2) RHS can be negative: greatest value can be increased.
11057     bool CanWiden = !L.NonNegative || !R.NonNegative;
11058     bool Unsigned = L.NonNegative && R.Width == 0;
11059     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11060                         !Unsigned,
11061                     Unsigned);
11062   }
11063 
11064   /// Return the range of a product of the two ranges.
product__anona96a15881a11::IntRange11065   static IntRange product(IntRange L, IntRange R) {
11066     // If both LHS and RHS can be negative, we can form
11067     //   -2^L * -2^R = 2^(L + R)
11068     // which requires L + R + 1 value bits to represent.
11069     bool CanWiden = !L.NonNegative && !R.NonNegative;
11070     bool Unsigned = L.NonNegative && R.NonNegative;
11071     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11072                     Unsigned);
11073   }
11074 
11075   /// Return the range of a remainder operation between the two ranges.
rem__anona96a15881a11::IntRange11076   static IntRange rem(IntRange L, IntRange R) {
11077     // The result of a remainder can't be larger than the result of
11078     // either side. The sign of the result is the sign of the LHS.
11079     bool Unsigned = L.NonNegative;
11080     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11081                     Unsigned);
11082   }
11083 };
11084 
11085 } // namespace
11086 
GetValueRange(ASTContext & C,llvm::APSInt & value,unsigned MaxWidth)11087 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11088                               unsigned MaxWidth) {
11089   if (value.isSigned() && value.isNegative())
11090     return IntRange(value.getMinSignedBits(), false);
11091 
11092   if (value.getBitWidth() > MaxWidth)
11093     value = value.trunc(MaxWidth);
11094 
11095   // isNonNegative() just checks the sign bit without considering
11096   // signedness.
11097   return IntRange(value.getActiveBits(), true);
11098 }
11099 
GetValueRange(ASTContext & C,APValue & result,QualType Ty,unsigned MaxWidth)11100 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11101                               unsigned MaxWidth) {
11102   if (result.isInt())
11103     return GetValueRange(C, result.getInt(), MaxWidth);
11104 
11105   if (result.isVector()) {
11106     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11107     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11108       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11109       R = IntRange::join(R, El);
11110     }
11111     return R;
11112   }
11113 
11114   if (result.isComplexInt()) {
11115     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11116     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11117     return IntRange::join(R, I);
11118   }
11119 
11120   // This can happen with lossless casts to intptr_t of "based" lvalues.
11121   // Assume it might use arbitrary bits.
11122   // FIXME: The only reason we need to pass the type in here is to get
11123   // the sign right on this one case.  It would be nice if APValue
11124   // preserved this.
11125   assert(result.isLValue() || result.isAddrLabelDiff());
11126   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11127 }
11128 
GetExprType(const Expr * E)11129 static QualType GetExprType(const Expr *E) {
11130   QualType Ty = E->getType();
11131   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11132     Ty = AtomicRHS->getValueType();
11133   return Ty;
11134 }
11135 
11136 /// Pseudo-evaluate the given integer expression, estimating the
11137 /// range of values it might take.
11138 ///
11139 /// \param MaxWidth The width to which the value will be truncated.
11140 /// \param Approximate If \c true, return a likely range for the result: in
11141 ///        particular, assume that aritmetic on narrower types doesn't leave
11142 ///        those types. If \c false, return a range including all possible
11143 ///        result values.
GetExprRange(ASTContext & C,const Expr * E,unsigned MaxWidth,bool InConstantContext,bool Approximate)11144 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11145                              bool InConstantContext, bool Approximate) {
11146   E = E->IgnoreParens();
11147 
11148   // Try a full evaluation first.
11149   Expr::EvalResult result;
11150   if (E->EvaluateAsRValue(result, C, InConstantContext))
11151     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11152 
11153   // I think we only want to look through implicit casts here; if the
11154   // user has an explicit widening cast, we should treat the value as
11155   // being of the new, wider type.
11156   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11157     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11158       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11159                           Approximate);
11160 
11161     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11162 
11163     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11164                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11165 
11166     // Assume that non-integer casts can span the full range of the type.
11167     if (!isIntegerCast)
11168       return OutputTypeRange;
11169 
11170     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11171                                      std::min(MaxWidth, OutputTypeRange.Width),
11172                                      InConstantContext, Approximate);
11173 
11174     // Bail out if the subexpr's range is as wide as the cast type.
11175     if (SubRange.Width >= OutputTypeRange.Width)
11176       return OutputTypeRange;
11177 
11178     // Otherwise, we take the smaller width, and we're non-negative if
11179     // either the output type or the subexpr is.
11180     return IntRange(SubRange.Width,
11181                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11182   }
11183 
11184   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11185     // If we can fold the condition, just take that operand.
11186     bool CondResult;
11187     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11188       return GetExprRange(C,
11189                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11190                           MaxWidth, InConstantContext, Approximate);
11191 
11192     // Otherwise, conservatively merge.
11193     // GetExprRange requires an integer expression, but a throw expression
11194     // results in a void type.
11195     Expr *E = CO->getTrueExpr();
11196     IntRange L = E->getType()->isVoidType()
11197                      ? IntRange{0, true}
11198                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11199     E = CO->getFalseExpr();
11200     IntRange R = E->getType()->isVoidType()
11201                      ? IntRange{0, true}
11202                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11203     return IntRange::join(L, R);
11204   }
11205 
11206   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11207     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11208 
11209     switch (BO->getOpcode()) {
11210     case BO_Cmp:
11211       llvm_unreachable("builtin <=> should have class type");
11212 
11213     // Boolean-valued operations are single-bit and positive.
11214     case BO_LAnd:
11215     case BO_LOr:
11216     case BO_LT:
11217     case BO_GT:
11218     case BO_LE:
11219     case BO_GE:
11220     case BO_EQ:
11221     case BO_NE:
11222       return IntRange::forBoolType();
11223 
11224     // The type of the assignments is the type of the LHS, so the RHS
11225     // is not necessarily the same type.
11226     case BO_MulAssign:
11227     case BO_DivAssign:
11228     case BO_RemAssign:
11229     case BO_AddAssign:
11230     case BO_SubAssign:
11231     case BO_XorAssign:
11232     case BO_OrAssign:
11233       // TODO: bitfields?
11234       return IntRange::forValueOfType(C, GetExprType(E));
11235 
11236     // Simple assignments just pass through the RHS, which will have
11237     // been coerced to the LHS type.
11238     case BO_Assign:
11239       // TODO: bitfields?
11240       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11241                           Approximate);
11242 
11243     // Operations with opaque sources are black-listed.
11244     case BO_PtrMemD:
11245     case BO_PtrMemI:
11246       return IntRange::forValueOfType(C, GetExprType(E));
11247 
11248     // Bitwise-and uses the *infinum* of the two source ranges.
11249     case BO_And:
11250     case BO_AndAssign:
11251       Combine = IntRange::bit_and;
11252       break;
11253 
11254     // Left shift gets black-listed based on a judgement call.
11255     case BO_Shl:
11256       // ...except that we want to treat '1 << (blah)' as logically
11257       // positive.  It's an important idiom.
11258       if (IntegerLiteral *I
11259             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11260         if (I->getValue() == 1) {
11261           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11262           return IntRange(R.Width, /*NonNegative*/ true);
11263         }
11264       }
11265       LLVM_FALLTHROUGH;
11266 
11267     case BO_ShlAssign:
11268       return IntRange::forValueOfType(C, GetExprType(E));
11269 
11270     // Right shift by a constant can narrow its left argument.
11271     case BO_Shr:
11272     case BO_ShrAssign: {
11273       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11274                                 Approximate);
11275 
11276       // If the shift amount is a positive constant, drop the width by
11277       // that much.
11278       if (Optional<llvm::APSInt> shift =
11279               BO->getRHS()->getIntegerConstantExpr(C)) {
11280         if (shift->isNonNegative()) {
11281           unsigned zext = shift->getZExtValue();
11282           if (zext >= L.Width)
11283             L.Width = (L.NonNegative ? 0 : 1);
11284           else
11285             L.Width -= zext;
11286         }
11287       }
11288 
11289       return L;
11290     }
11291 
11292     // Comma acts as its right operand.
11293     case BO_Comma:
11294       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11295                           Approximate);
11296 
11297     case BO_Add:
11298       if (!Approximate)
11299         Combine = IntRange::sum;
11300       break;
11301 
11302     case BO_Sub:
11303       if (BO->getLHS()->getType()->isPointerType())
11304         return IntRange::forValueOfType(C, GetExprType(E));
11305       if (!Approximate)
11306         Combine = IntRange::difference;
11307       break;
11308 
11309     case BO_Mul:
11310       if (!Approximate)
11311         Combine = IntRange::product;
11312       break;
11313 
11314     // The width of a division result is mostly determined by the size
11315     // of the LHS.
11316     case BO_Div: {
11317       // Don't 'pre-truncate' the operands.
11318       unsigned opWidth = C.getIntWidth(GetExprType(E));
11319       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11320                                 Approximate);
11321 
11322       // If the divisor is constant, use that.
11323       if (Optional<llvm::APSInt> divisor =
11324               BO->getRHS()->getIntegerConstantExpr(C)) {
11325         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11326         if (log2 >= L.Width)
11327           L.Width = (L.NonNegative ? 0 : 1);
11328         else
11329           L.Width = std::min(L.Width - log2, MaxWidth);
11330         return L;
11331       }
11332 
11333       // Otherwise, just use the LHS's width.
11334       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11335       // could be -1.
11336       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11337                                 Approximate);
11338       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11339     }
11340 
11341     case BO_Rem:
11342       Combine = IntRange::rem;
11343       break;
11344 
11345     // The default behavior is okay for these.
11346     case BO_Xor:
11347     case BO_Or:
11348       break;
11349     }
11350 
11351     // Combine the two ranges, but limit the result to the type in which we
11352     // performed the computation.
11353     QualType T = GetExprType(E);
11354     unsigned opWidth = C.getIntWidth(T);
11355     IntRange L =
11356         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11357     IntRange R =
11358         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11359     IntRange C = Combine(L, R);
11360     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11361     C.Width = std::min(C.Width, MaxWidth);
11362     return C;
11363   }
11364 
11365   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11366     switch (UO->getOpcode()) {
11367     // Boolean-valued operations are white-listed.
11368     case UO_LNot:
11369       return IntRange::forBoolType();
11370 
11371     // Operations with opaque sources are black-listed.
11372     case UO_Deref:
11373     case UO_AddrOf: // should be impossible
11374       return IntRange::forValueOfType(C, GetExprType(E));
11375 
11376     default:
11377       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11378                           Approximate);
11379     }
11380   }
11381 
11382   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11383     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11384                         Approximate);
11385 
11386   if (const auto *BitField = E->getSourceBitField())
11387     return IntRange(BitField->getBitWidthValue(C),
11388                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11389 
11390   return IntRange::forValueOfType(C, GetExprType(E));
11391 }
11392 
GetExprRange(ASTContext & C,const Expr * E,bool InConstantContext,bool Approximate)11393 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11394                              bool InConstantContext, bool Approximate) {
11395   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11396                       Approximate);
11397 }
11398 
11399 /// Checks whether the given value, which currently has the given
11400 /// source semantics, has the same value when coerced through the
11401 /// target semantics.
IsSameFloatAfterCast(const llvm::APFloat & value,const llvm::fltSemantics & Src,const llvm::fltSemantics & Tgt)11402 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11403                                  const llvm::fltSemantics &Src,
11404                                  const llvm::fltSemantics &Tgt) {
11405   llvm::APFloat truncated = value;
11406 
11407   bool ignored;
11408   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11409   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11410 
11411   return truncated.bitwiseIsEqual(value);
11412 }
11413 
11414 /// Checks whether the given value, which currently has the given
11415 /// source semantics, has the same value when coerced through the
11416 /// target semantics.
11417 ///
11418 /// The value might be a vector of floats (or a complex number).
IsSameFloatAfterCast(const APValue & value,const llvm::fltSemantics & Src,const llvm::fltSemantics & Tgt)11419 static bool IsSameFloatAfterCast(const APValue &value,
11420                                  const llvm::fltSemantics &Src,
11421                                  const llvm::fltSemantics &Tgt) {
11422   if (value.isFloat())
11423     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11424 
11425   if (value.isVector()) {
11426     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11427       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11428         return false;
11429     return true;
11430   }
11431 
11432   assert(value.isComplexFloat());
11433   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11434           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11435 }
11436 
11437 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11438                                        bool IsListInit = false);
11439 
IsEnumConstOrFromMacro(Sema & S,Expr * E)11440 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11441   // Suppress cases where we are comparing against an enum constant.
11442   if (const DeclRefExpr *DR =
11443       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11444     if (isa<EnumConstantDecl>(DR->getDecl()))
11445       return true;
11446 
11447   // Suppress cases where the value is expanded from a macro, unless that macro
11448   // is how a language represents a boolean literal. This is the case in both C
11449   // and Objective-C.
11450   SourceLocation BeginLoc = E->getBeginLoc();
11451   if (BeginLoc.isMacroID()) {
11452     StringRef MacroName = Lexer::getImmediateMacroName(
11453         BeginLoc, S.getSourceManager(), S.getLangOpts());
11454     return MacroName != "YES" && MacroName != "NO" &&
11455            MacroName != "true" && MacroName != "false";
11456   }
11457 
11458   return false;
11459 }
11460 
isKnownToHaveUnsignedValue(Expr * E)11461 static bool isKnownToHaveUnsignedValue(Expr *E) {
11462   return E->getType()->isIntegerType() &&
11463          (!E->getType()->isSignedIntegerType() ||
11464           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11465 }
11466 
11467 namespace {
11468 /// The promoted range of values of a type. In general this has the
11469 /// following structure:
11470 ///
11471 ///     |-----------| . . . |-----------|
11472 ///     ^           ^       ^           ^
11473 ///    Min       HoleMin  HoleMax      Max
11474 ///
11475 /// ... where there is only a hole if a signed type is promoted to unsigned
11476 /// (in which case Min and Max are the smallest and largest representable
11477 /// values).
11478 struct PromotedRange {
11479   // Min, or HoleMax if there is a hole.
11480   llvm::APSInt PromotedMin;
11481   // Max, or HoleMin if there is a hole.
11482   llvm::APSInt PromotedMax;
11483 
PromotedRange__anona96a15881b11::PromotedRange11484   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11485     if (R.Width == 0)
11486       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11487     else if (R.Width >= BitWidth && !Unsigned) {
11488       // Promotion made the type *narrower*. This happens when promoting
11489       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11490       // Treat all values of 'signed int' as being in range for now.
11491       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11492       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11493     } else {
11494       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11495                         .extOrTrunc(BitWidth);
11496       PromotedMin.setIsUnsigned(Unsigned);
11497 
11498       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11499                         .extOrTrunc(BitWidth);
11500       PromotedMax.setIsUnsigned(Unsigned);
11501     }
11502   }
11503 
11504   // Determine whether this range is contiguous (has no hole).
isContiguous__anona96a15881b11::PromotedRange11505   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11506 
11507   // Where a constant value is within the range.
11508   enum ComparisonResult {
11509     LT = 0x1,
11510     LE = 0x2,
11511     GT = 0x4,
11512     GE = 0x8,
11513     EQ = 0x10,
11514     NE = 0x20,
11515     InRangeFlag = 0x40,
11516 
11517     Less = LE | LT | NE,
11518     Min = LE | InRangeFlag,
11519     InRange = InRangeFlag,
11520     Max = GE | InRangeFlag,
11521     Greater = GE | GT | NE,
11522 
11523     OnlyValue = LE | GE | EQ | InRangeFlag,
11524     InHole = NE
11525   };
11526 
compare__anona96a15881b11::PromotedRange11527   ComparisonResult compare(const llvm::APSInt &Value) const {
11528     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11529            Value.isUnsigned() == PromotedMin.isUnsigned());
11530     if (!isContiguous()) {
11531       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11532       if (Value.isMinValue()) return Min;
11533       if (Value.isMaxValue()) return Max;
11534       if (Value >= PromotedMin) return InRange;
11535       if (Value <= PromotedMax) return InRange;
11536       return InHole;
11537     }
11538 
11539     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11540     case -1: return Less;
11541     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11542     case 1:
11543       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11544       case -1: return InRange;
11545       case 0: return Max;
11546       case 1: return Greater;
11547       }
11548     }
11549 
11550     llvm_unreachable("impossible compare result");
11551   }
11552 
11553   static llvm::Optional<StringRef>
constantValue__anona96a15881b11::PromotedRange11554   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11555     if (Op == BO_Cmp) {
11556       ComparisonResult LTFlag = LT, GTFlag = GT;
11557       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11558 
11559       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11560       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11561       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11562       return llvm::None;
11563     }
11564 
11565     ComparisonResult TrueFlag, FalseFlag;
11566     if (Op == BO_EQ) {
11567       TrueFlag = EQ;
11568       FalseFlag = NE;
11569     } else if (Op == BO_NE) {
11570       TrueFlag = NE;
11571       FalseFlag = EQ;
11572     } else {
11573       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11574         TrueFlag = LT;
11575         FalseFlag = GE;
11576       } else {
11577         TrueFlag = GT;
11578         FalseFlag = LE;
11579       }
11580       if (Op == BO_GE || Op == BO_LE)
11581         std::swap(TrueFlag, FalseFlag);
11582     }
11583     if (R & TrueFlag)
11584       return StringRef("true");
11585     if (R & FalseFlag)
11586       return StringRef("false");
11587     return llvm::None;
11588   }
11589 };
11590 }
11591 
HasEnumType(Expr * E)11592 static bool HasEnumType(Expr *E) {
11593   // Strip off implicit integral promotions.
11594   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11595     if (ICE->getCastKind() != CK_IntegralCast &&
11596         ICE->getCastKind() != CK_NoOp)
11597       break;
11598     E = ICE->getSubExpr();
11599   }
11600 
11601   return E->getType()->isEnumeralType();
11602 }
11603 
classifyConstantValue(Expr * Constant)11604 static int classifyConstantValue(Expr *Constant) {
11605   // The values of this enumeration are used in the diagnostics
11606   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11607   enum ConstantValueKind {
11608     Miscellaneous = 0,
11609     LiteralTrue,
11610     LiteralFalse
11611   };
11612   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11613     return BL->getValue() ? ConstantValueKind::LiteralTrue
11614                           : ConstantValueKind::LiteralFalse;
11615   return ConstantValueKind::Miscellaneous;
11616 }
11617 
CheckTautologicalComparison(Sema & S,BinaryOperator * E,Expr * Constant,Expr * Other,const llvm::APSInt & Value,bool RhsConstant)11618 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11619                                         Expr *Constant, Expr *Other,
11620                                         const llvm::APSInt &Value,
11621                                         bool RhsConstant) {
11622   if (S.inTemplateInstantiation())
11623     return false;
11624 
11625   Expr *OriginalOther = Other;
11626 
11627   Constant = Constant->IgnoreParenImpCasts();
11628   Other = Other->IgnoreParenImpCasts();
11629 
11630   // Suppress warnings on tautological comparisons between values of the same
11631   // enumeration type. There are only two ways we could warn on this:
11632   //  - If the constant is outside the range of representable values of
11633   //    the enumeration. In such a case, we should warn about the cast
11634   //    to enumeration type, not about the comparison.
11635   //  - If the constant is the maximum / minimum in-range value. For an
11636   //    enumeratin type, such comparisons can be meaningful and useful.
11637   if (Constant->getType()->isEnumeralType() &&
11638       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11639     return false;
11640 
11641   IntRange OtherValueRange = GetExprRange(
11642       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11643 
11644   QualType OtherT = Other->getType();
11645   if (const auto *AT = OtherT->getAs<AtomicType>())
11646     OtherT = AT->getValueType();
11647   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11648 
11649   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11650   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11651   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11652                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11653                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11654 
11655   // Whether we're treating Other as being a bool because of the form of
11656   // expression despite it having another type (typically 'int' in C).
11657   bool OtherIsBooleanDespiteType =
11658       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11659   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11660     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11661 
11662   // Check if all values in the range of possible values of this expression
11663   // lead to the same comparison outcome.
11664   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11665                                         Value.isUnsigned());
11666   auto Cmp = OtherPromotedValueRange.compare(Value);
11667   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11668   if (!Result)
11669     return false;
11670 
11671   // Also consider the range determined by the type alone. This allows us to
11672   // classify the warning under the proper diagnostic group.
11673   bool TautologicalTypeCompare = false;
11674   {
11675     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11676                                          Value.isUnsigned());
11677     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11678     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11679                                                        RhsConstant)) {
11680       TautologicalTypeCompare = true;
11681       Cmp = TypeCmp;
11682       Result = TypeResult;
11683     }
11684   }
11685 
11686   // Don't warn if the non-constant operand actually always evaluates to the
11687   // same value.
11688   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11689     return false;
11690 
11691   // Suppress the diagnostic for an in-range comparison if the constant comes
11692   // from a macro or enumerator. We don't want to diagnose
11693   //
11694   //   some_long_value <= INT_MAX
11695   //
11696   // when sizeof(int) == sizeof(long).
11697   bool InRange = Cmp & PromotedRange::InRangeFlag;
11698   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11699     return false;
11700 
11701   // A comparison of an unsigned bit-field against 0 is really a type problem,
11702   // even though at the type level the bit-field might promote to 'signed int'.
11703   if (Other->refersToBitField() && InRange && Value == 0 &&
11704       Other->getType()->isUnsignedIntegerOrEnumerationType())
11705     TautologicalTypeCompare = true;
11706 
11707   // If this is a comparison to an enum constant, include that
11708   // constant in the diagnostic.
11709   const EnumConstantDecl *ED = nullptr;
11710   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11711     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11712 
11713   // Should be enough for uint128 (39 decimal digits)
11714   SmallString<64> PrettySourceValue;
11715   llvm::raw_svector_ostream OS(PrettySourceValue);
11716   if (ED) {
11717     OS << '\'' << *ED << "' (" << Value << ")";
11718   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11719                Constant->IgnoreParenImpCasts())) {
11720     OS << (BL->getValue() ? "YES" : "NO");
11721   } else {
11722     OS << Value;
11723   }
11724 
11725   if (!TautologicalTypeCompare) {
11726     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11727         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11728         << E->getOpcodeStr() << OS.str() << *Result
11729         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11730     return true;
11731   }
11732 
11733   if (IsObjCSignedCharBool) {
11734     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11735                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11736                               << OS.str() << *Result);
11737     return true;
11738   }
11739 
11740   // FIXME: We use a somewhat different formatting for the in-range cases and
11741   // cases involving boolean values for historical reasons. We should pick a
11742   // consistent way of presenting these diagnostics.
11743   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11744 
11745     S.DiagRuntimeBehavior(
11746         E->getOperatorLoc(), E,
11747         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11748                          : diag::warn_tautological_bool_compare)
11749             << OS.str() << classifyConstantValue(Constant) << OtherT
11750             << OtherIsBooleanDespiteType << *Result
11751             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11752   } else {
11753     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11754     unsigned Diag =
11755         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11756             ? (HasEnumType(OriginalOther)
11757                    ? diag::warn_unsigned_enum_always_true_comparison
11758                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11759                               : diag::warn_unsigned_always_true_comparison)
11760             : diag::warn_tautological_constant_compare;
11761 
11762     S.Diag(E->getOperatorLoc(), Diag)
11763         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11764         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11765   }
11766 
11767   return true;
11768 }
11769 
11770 /// Analyze the operands of the given comparison.  Implements the
11771 /// fallback case from AnalyzeComparison.
AnalyzeImpConvsInComparison(Sema & S,BinaryOperator * E)11772 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11773   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11774   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11775 }
11776 
11777 /// Implements -Wsign-compare.
11778 ///
11779 /// \param E the binary operator to check for warnings
AnalyzeComparison(Sema & S,BinaryOperator * E)11780 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11781   // The type the comparison is being performed in.
11782   QualType T = E->getLHS()->getType();
11783 
11784   // Only analyze comparison operators where both sides have been converted to
11785   // the same type.
11786   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11787     return AnalyzeImpConvsInComparison(S, E);
11788 
11789   // Don't analyze value-dependent comparisons directly.
11790   if (E->isValueDependent())
11791     return AnalyzeImpConvsInComparison(S, E);
11792 
11793   Expr *LHS = E->getLHS();
11794   Expr *RHS = E->getRHS();
11795 
11796   if (T->isIntegralType(S.Context)) {
11797     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11798     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11799 
11800     // We don't care about expressions whose result is a constant.
11801     if (RHSValue && LHSValue)
11802       return AnalyzeImpConvsInComparison(S, E);
11803 
11804     // We only care about expressions where just one side is literal
11805     if ((bool)RHSValue ^ (bool)LHSValue) {
11806       // Is the constant on the RHS or LHS?
11807       const bool RhsConstant = (bool)RHSValue;
11808       Expr *Const = RhsConstant ? RHS : LHS;
11809       Expr *Other = RhsConstant ? LHS : RHS;
11810       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11811 
11812       // Check whether an integer constant comparison results in a value
11813       // of 'true' or 'false'.
11814       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11815         return AnalyzeImpConvsInComparison(S, E);
11816     }
11817   }
11818 
11819   if (!T->hasUnsignedIntegerRepresentation()) {
11820     // We don't do anything special if this isn't an unsigned integral
11821     // comparison:  we're only interested in integral comparisons, and
11822     // signed comparisons only happen in cases we don't care to warn about.
11823     return AnalyzeImpConvsInComparison(S, E);
11824   }
11825 
11826   LHS = LHS->IgnoreParenImpCasts();
11827   RHS = RHS->IgnoreParenImpCasts();
11828 
11829   if (!S.getLangOpts().CPlusPlus) {
11830     // Avoid warning about comparison of integers with different signs when
11831     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11832     // the type of `E`.
11833     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11834       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11835     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11836       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11837   }
11838 
11839   // Check to see if one of the (unmodified) operands is of different
11840   // signedness.
11841   Expr *signedOperand, *unsignedOperand;
11842   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11843     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11844            "unsigned comparison between two signed integer expressions?");
11845     signedOperand = LHS;
11846     unsignedOperand = RHS;
11847   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11848     signedOperand = RHS;
11849     unsignedOperand = LHS;
11850   } else {
11851     return AnalyzeImpConvsInComparison(S, E);
11852   }
11853 
11854   // Otherwise, calculate the effective range of the signed operand.
11855   IntRange signedRange = GetExprRange(
11856       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11857 
11858   // Go ahead and analyze implicit conversions in the operands.  Note
11859   // that we skip the implicit conversions on both sides.
11860   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11861   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11862 
11863   // If the signed range is non-negative, -Wsign-compare won't fire.
11864   if (signedRange.NonNegative)
11865     return;
11866 
11867   // For (in)equality comparisons, if the unsigned operand is a
11868   // constant which cannot collide with a overflowed signed operand,
11869   // then reinterpreting the signed operand as unsigned will not
11870   // change the result of the comparison.
11871   if (E->isEqualityOp()) {
11872     unsigned comparisonWidth = S.Context.getIntWidth(T);
11873     IntRange unsignedRange =
11874         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11875                      /*Approximate*/ true);
11876 
11877     // We should never be unable to prove that the unsigned operand is
11878     // non-negative.
11879     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11880 
11881     if (unsignedRange.Width < comparisonWidth)
11882       return;
11883   }
11884 
11885   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11886                         S.PDiag(diag::warn_mixed_sign_comparison)
11887                             << LHS->getType() << RHS->getType()
11888                             << LHS->getSourceRange() << RHS->getSourceRange());
11889 }
11890 
11891 /// Analyzes an attempt to assign the given value to a bitfield.
11892 ///
11893 /// Returns true if there was something fishy about the attempt.
AnalyzeBitFieldAssignment(Sema & S,FieldDecl * Bitfield,Expr * Init,SourceLocation InitLoc)11894 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11895                                       SourceLocation InitLoc) {
11896   assert(Bitfield->isBitField());
11897   if (Bitfield->isInvalidDecl())
11898     return false;
11899 
11900   // White-list bool bitfields.
11901   QualType BitfieldType = Bitfield->getType();
11902   if (BitfieldType->isBooleanType())
11903      return false;
11904 
11905   if (BitfieldType->isEnumeralType()) {
11906     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11907     // If the underlying enum type was not explicitly specified as an unsigned
11908     // type and the enum contain only positive values, MSVC++ will cause an
11909     // inconsistency by storing this as a signed type.
11910     if (S.getLangOpts().CPlusPlus11 &&
11911         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11912         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11913         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11914       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11915           << BitfieldEnumDecl;
11916     }
11917   }
11918 
11919   if (Bitfield->getType()->isBooleanType())
11920     return false;
11921 
11922   // Ignore value- or type-dependent expressions.
11923   if (Bitfield->getBitWidth()->isValueDependent() ||
11924       Bitfield->getBitWidth()->isTypeDependent() ||
11925       Init->isValueDependent() ||
11926       Init->isTypeDependent())
11927     return false;
11928 
11929   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11930   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11931 
11932   Expr::EvalResult Result;
11933   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11934                                    Expr::SE_AllowSideEffects)) {
11935     // The RHS is not constant.  If the RHS has an enum type, make sure the
11936     // bitfield is wide enough to hold all the values of the enum without
11937     // truncation.
11938     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11939       EnumDecl *ED = EnumTy->getDecl();
11940       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11941 
11942       // Enum types are implicitly signed on Windows, so check if there are any
11943       // negative enumerators to see if the enum was intended to be signed or
11944       // not.
11945       bool SignedEnum = ED->getNumNegativeBits() > 0;
11946 
11947       // Check for surprising sign changes when assigning enum values to a
11948       // bitfield of different signedness.  If the bitfield is signed and we
11949       // have exactly the right number of bits to store this unsigned enum,
11950       // suggest changing the enum to an unsigned type. This typically happens
11951       // on Windows where unfixed enums always use an underlying type of 'int'.
11952       unsigned DiagID = 0;
11953       if (SignedEnum && !SignedBitfield) {
11954         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11955       } else if (SignedBitfield && !SignedEnum &&
11956                  ED->getNumPositiveBits() == FieldWidth) {
11957         DiagID = diag::warn_signed_bitfield_enum_conversion;
11958       }
11959 
11960       if (DiagID) {
11961         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11962         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11963         SourceRange TypeRange =
11964             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11965         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11966             << SignedEnum << TypeRange;
11967       }
11968 
11969       // Compute the required bitwidth. If the enum has negative values, we need
11970       // one more bit than the normal number of positive bits to represent the
11971       // sign bit.
11972       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11973                                                   ED->getNumNegativeBits())
11974                                        : ED->getNumPositiveBits();
11975 
11976       // Check the bitwidth.
11977       if (BitsNeeded > FieldWidth) {
11978         Expr *WidthExpr = Bitfield->getBitWidth();
11979         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11980             << Bitfield << ED;
11981         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11982             << BitsNeeded << ED << WidthExpr->getSourceRange();
11983       }
11984     }
11985 
11986     return false;
11987   }
11988 
11989   llvm::APSInt Value = Result.Val.getInt();
11990 
11991   unsigned OriginalWidth = Value.getBitWidth();
11992 
11993   if (!Value.isSigned() || Value.isNegative())
11994     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11995       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11996         OriginalWidth = Value.getMinSignedBits();
11997 
11998   if (OriginalWidth <= FieldWidth)
11999     return false;
12000 
12001   // Compute the value which the bitfield will contain.
12002   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12003   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12004 
12005   // Check whether the stored value is equal to the original value.
12006   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12007   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12008     return false;
12009 
12010   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12011   // therefore don't strictly fit into a signed bitfield of width 1.
12012   if (FieldWidth == 1 && Value == 1)
12013     return false;
12014 
12015   std::string PrettyValue = toString(Value, 10);
12016   std::string PrettyTrunc = toString(TruncatedValue, 10);
12017 
12018   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12019     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12020     << Init->getSourceRange();
12021 
12022   return true;
12023 }
12024 
12025 /// Analyze the given simple or compound assignment for warning-worthy
12026 /// operations.
AnalyzeAssignment(Sema & S,BinaryOperator * E)12027 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12028   // Just recurse on the LHS.
12029   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12030 
12031   // We want to recurse on the RHS as normal unless we're assigning to
12032   // a bitfield.
12033   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12034     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12035                                   E->getOperatorLoc())) {
12036       // Recurse, ignoring any implicit conversions on the RHS.
12037       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12038                                         E->getOperatorLoc());
12039     }
12040   }
12041 
12042   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12043 
12044   // Diagnose implicitly sequentially-consistent atomic assignment.
12045   if (E->getLHS()->getType()->isAtomicType())
12046     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12047 }
12048 
12049 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
DiagnoseImpCast(Sema & S,Expr * E,QualType SourceType,QualType T,SourceLocation CContext,unsigned diag,bool pruneControlFlow=false)12050 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12051                             SourceLocation CContext, unsigned diag,
12052                             bool pruneControlFlow = false) {
12053   if (pruneControlFlow) {
12054     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12055                           S.PDiag(diag)
12056                               << SourceType << T << E->getSourceRange()
12057                               << SourceRange(CContext));
12058     return;
12059   }
12060   S.Diag(E->getExprLoc(), diag)
12061     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12062 }
12063 
12064 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
DiagnoseImpCast(Sema & S,Expr * E,QualType T,SourceLocation CContext,unsigned diag,bool pruneControlFlow=false)12065 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12066                             SourceLocation CContext,
12067                             unsigned diag, bool pruneControlFlow = false) {
12068   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12069 }
12070 
isObjCSignedCharBool(Sema & S,QualType Ty)12071 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12072   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12073       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12074 }
12075 
adornObjCBoolConversionDiagWithTernaryFixit(Sema & S,Expr * SourceExpr,const Sema::SemaDiagnosticBuilder & Builder)12076 static void adornObjCBoolConversionDiagWithTernaryFixit(
12077     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12078   Expr *Ignored = SourceExpr->IgnoreImplicit();
12079   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12080     Ignored = OVE->getSourceExpr();
12081   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12082                      isa<BinaryOperator>(Ignored) ||
12083                      isa<CXXOperatorCallExpr>(Ignored);
12084   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12085   if (NeedsParens)
12086     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12087             << FixItHint::CreateInsertion(EndLoc, ")");
12088   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12089 }
12090 
12091 /// Diagnose an implicit cast from a floating point value to an integer value.
DiagnoseFloatingImpCast(Sema & S,Expr * E,QualType T,SourceLocation CContext)12092 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12093                                     SourceLocation CContext) {
12094   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12095   const bool PruneWarnings = S.inTemplateInstantiation();
12096 
12097   Expr *InnerE = E->IgnoreParenImpCasts();
12098   // We also want to warn on, e.g., "int i = -1.234"
12099   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12100     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12101       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12102 
12103   const bool IsLiteral =
12104       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12105 
12106   llvm::APFloat Value(0.0);
12107   bool IsConstant =
12108     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12109   if (!IsConstant) {
12110     if (isObjCSignedCharBool(S, T)) {
12111       return adornObjCBoolConversionDiagWithTernaryFixit(
12112           S, E,
12113           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12114               << E->getType());
12115     }
12116 
12117     return DiagnoseImpCast(S, E, T, CContext,
12118                            diag::warn_impcast_float_integer, PruneWarnings);
12119   }
12120 
12121   bool isExact = false;
12122 
12123   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12124                             T->hasUnsignedIntegerRepresentation());
12125   llvm::APFloat::opStatus Result = Value.convertToInteger(
12126       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12127 
12128   // FIXME: Force the precision of the source value down so we don't print
12129   // digits which are usually useless (we don't really care here if we
12130   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12131   // would automatically print the shortest representation, but it's a bit
12132   // tricky to implement.
12133   SmallString<16> PrettySourceValue;
12134   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12135   precision = (precision * 59 + 195) / 196;
12136   Value.toString(PrettySourceValue, precision);
12137 
12138   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12139     return adornObjCBoolConversionDiagWithTernaryFixit(
12140         S, E,
12141         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12142             << PrettySourceValue);
12143   }
12144 
12145   if (Result == llvm::APFloat::opOK && isExact) {
12146     if (IsLiteral) return;
12147     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12148                            PruneWarnings);
12149   }
12150 
12151   // Conversion of a floating-point value to a non-bool integer where the
12152   // integral part cannot be represented by the integer type is undefined.
12153   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12154     return DiagnoseImpCast(
12155         S, E, T, CContext,
12156         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12157                   : diag::warn_impcast_float_to_integer_out_of_range,
12158         PruneWarnings);
12159 
12160   unsigned DiagID = 0;
12161   if (IsLiteral) {
12162     // Warn on floating point literal to integer.
12163     DiagID = diag::warn_impcast_literal_float_to_integer;
12164   } else if (IntegerValue == 0) {
12165     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12166       return DiagnoseImpCast(S, E, T, CContext,
12167                              diag::warn_impcast_float_integer, PruneWarnings);
12168     }
12169     // Warn on non-zero to zero conversion.
12170     DiagID = diag::warn_impcast_float_to_integer_zero;
12171   } else {
12172     if (IntegerValue.isUnsigned()) {
12173       if (!IntegerValue.isMaxValue()) {
12174         return DiagnoseImpCast(S, E, T, CContext,
12175                                diag::warn_impcast_float_integer, PruneWarnings);
12176       }
12177     } else {  // IntegerValue.isSigned()
12178       if (!IntegerValue.isMaxSignedValue() &&
12179           !IntegerValue.isMinSignedValue()) {
12180         return DiagnoseImpCast(S, E, T, CContext,
12181                                diag::warn_impcast_float_integer, PruneWarnings);
12182       }
12183     }
12184     // Warn on evaluatable floating point expression to integer conversion.
12185     DiagID = diag::warn_impcast_float_to_integer;
12186   }
12187 
12188   SmallString<16> PrettyTargetValue;
12189   if (IsBool)
12190     PrettyTargetValue = Value.isZero() ? "false" : "true";
12191   else
12192     IntegerValue.toString(PrettyTargetValue);
12193 
12194   if (PruneWarnings) {
12195     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12196                           S.PDiag(DiagID)
12197                               << E->getType() << T.getUnqualifiedType()
12198                               << PrettySourceValue << PrettyTargetValue
12199                               << E->getSourceRange() << SourceRange(CContext));
12200   } else {
12201     S.Diag(E->getExprLoc(), DiagID)
12202         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12203         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12204   }
12205 }
12206 
12207 /// Analyze the given compound assignment for the possible losing of
12208 /// floating-point precision.
AnalyzeCompoundAssignment(Sema & S,BinaryOperator * E)12209 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12210   assert(isa<CompoundAssignOperator>(E) &&
12211          "Must be compound assignment operation");
12212   // Recurse on the LHS and RHS in here
12213   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12214   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12215 
12216   if (E->getLHS()->getType()->isAtomicType())
12217     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12218 
12219   // Now check the outermost expression
12220   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12221   const auto *RBT = cast<CompoundAssignOperator>(E)
12222                         ->getComputationResultType()
12223                         ->getAs<BuiltinType>();
12224 
12225   // The below checks assume source is floating point.
12226   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12227 
12228   // If source is floating point but target is an integer.
12229   if (ResultBT->isInteger())
12230     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12231                            E->getExprLoc(), diag::warn_impcast_float_integer);
12232 
12233   if (!ResultBT->isFloatingPoint())
12234     return;
12235 
12236   // If both source and target are floating points, warn about losing precision.
12237   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12238       QualType(ResultBT, 0), QualType(RBT, 0));
12239   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12240     // warn about dropping FP rank.
12241     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12242                     diag::warn_impcast_float_result_precision);
12243 }
12244 
PrettyPrintInRange(const llvm::APSInt & Value,IntRange Range)12245 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12246                                       IntRange Range) {
12247   if (!Range.Width) return "0";
12248 
12249   llvm::APSInt ValueInRange = Value;
12250   ValueInRange.setIsSigned(!Range.NonNegative);
12251   ValueInRange = ValueInRange.trunc(Range.Width);
12252   return toString(ValueInRange, 10);
12253 }
12254 
IsImplicitBoolFloatConversion(Sema & S,Expr * Ex,bool ToBool)12255 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12256   if (!isa<ImplicitCastExpr>(Ex))
12257     return false;
12258 
12259   Expr *InnerE = Ex->IgnoreParenImpCasts();
12260   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12261   const Type *Source =
12262     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12263   if (Target->isDependentType())
12264     return false;
12265 
12266   const BuiltinType *FloatCandidateBT =
12267     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12268   const Type *BoolCandidateType = ToBool ? Target : Source;
12269 
12270   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12271           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12272 }
12273 
CheckImplicitArgumentConversions(Sema & S,CallExpr * TheCall,SourceLocation CC)12274 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12275                                              SourceLocation CC) {
12276   unsigned NumArgs = TheCall->getNumArgs();
12277   for (unsigned i = 0; i < NumArgs; ++i) {
12278     Expr *CurrA = TheCall->getArg(i);
12279     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12280       continue;
12281 
12282     bool IsSwapped = ((i > 0) &&
12283         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12284     IsSwapped |= ((i < (NumArgs - 1)) &&
12285         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12286     if (IsSwapped) {
12287       // Warn on this floating-point to bool conversion.
12288       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12289                       CurrA->getType(), CC,
12290                       diag::warn_impcast_floating_point_to_bool);
12291     }
12292   }
12293 }
12294 
DiagnoseNullConversion(Sema & S,Expr * E,QualType T,SourceLocation CC)12295 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12296                                    SourceLocation CC) {
12297   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12298                         E->getExprLoc()))
12299     return;
12300 
12301   // Don't warn on functions which have return type nullptr_t.
12302   if (isa<CallExpr>(E))
12303     return;
12304 
12305   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12306   const Expr::NullPointerConstantKind NullKind =
12307       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12308   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12309     return;
12310 
12311   // Return if target type is a safe conversion.
12312   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12313       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12314     return;
12315 
12316   SourceLocation Loc = E->getSourceRange().getBegin();
12317 
12318   // Venture through the macro stacks to get to the source of macro arguments.
12319   // The new location is a better location than the complete location that was
12320   // passed in.
12321   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12322   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12323 
12324   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12325   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12326     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12327         Loc, S.SourceMgr, S.getLangOpts());
12328     if (MacroName == "NULL")
12329       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12330   }
12331 
12332   // Only warn if the null and context location are in the same macro expansion.
12333   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12334     return;
12335 
12336   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12337       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12338       << FixItHint::CreateReplacement(Loc,
12339                                       S.getFixItZeroLiteralForType(T, Loc));
12340 }
12341 
12342 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12343                                   ObjCArrayLiteral *ArrayLiteral);
12344 
12345 static void
12346 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12347                            ObjCDictionaryLiteral *DictionaryLiteral);
12348 
12349 /// Check a single element within a collection literal against the
12350 /// target element type.
checkObjCCollectionLiteralElement(Sema & S,QualType TargetElementType,Expr * Element,unsigned ElementKind)12351 static void checkObjCCollectionLiteralElement(Sema &S,
12352                                               QualType TargetElementType,
12353                                               Expr *Element,
12354                                               unsigned ElementKind) {
12355   // Skip a bitcast to 'id' or qualified 'id'.
12356   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12357     if (ICE->getCastKind() == CK_BitCast &&
12358         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12359       Element = ICE->getSubExpr();
12360   }
12361 
12362   QualType ElementType = Element->getType();
12363   ExprResult ElementResult(Element);
12364   if (ElementType->getAs<ObjCObjectPointerType>() &&
12365       S.CheckSingleAssignmentConstraints(TargetElementType,
12366                                          ElementResult,
12367                                          false, false)
12368         != Sema::Compatible) {
12369     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12370         << ElementType << ElementKind << TargetElementType
12371         << Element->getSourceRange();
12372   }
12373 
12374   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12375     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12376   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12377     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12378 }
12379 
12380 /// Check an Objective-C array literal being converted to the given
12381 /// target type.
checkObjCArrayLiteral(Sema & S,QualType TargetType,ObjCArrayLiteral * ArrayLiteral)12382 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12383                                   ObjCArrayLiteral *ArrayLiteral) {
12384   if (!S.NSArrayDecl)
12385     return;
12386 
12387   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12388   if (!TargetObjCPtr)
12389     return;
12390 
12391   if (TargetObjCPtr->isUnspecialized() ||
12392       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12393         != S.NSArrayDecl->getCanonicalDecl())
12394     return;
12395 
12396   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12397   if (TypeArgs.size() != 1)
12398     return;
12399 
12400   QualType TargetElementType = TypeArgs[0];
12401   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12402     checkObjCCollectionLiteralElement(S, TargetElementType,
12403                                       ArrayLiteral->getElement(I),
12404                                       0);
12405   }
12406 }
12407 
12408 /// Check an Objective-C dictionary literal being converted to the given
12409 /// target type.
12410 static void
checkObjCDictionaryLiteral(Sema & S,QualType TargetType,ObjCDictionaryLiteral * DictionaryLiteral)12411 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12412                            ObjCDictionaryLiteral *DictionaryLiteral) {
12413   if (!S.NSDictionaryDecl)
12414     return;
12415 
12416   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12417   if (!TargetObjCPtr)
12418     return;
12419 
12420   if (TargetObjCPtr->isUnspecialized() ||
12421       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12422         != S.NSDictionaryDecl->getCanonicalDecl())
12423     return;
12424 
12425   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12426   if (TypeArgs.size() != 2)
12427     return;
12428 
12429   QualType TargetKeyType = TypeArgs[0];
12430   QualType TargetObjectType = TypeArgs[1];
12431   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12432     auto Element = DictionaryLiteral->getKeyValueElement(I);
12433     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12434     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12435   }
12436 }
12437 
12438 // Helper function to filter out cases for constant width constant conversion.
12439 // Don't warn on char array initialization or for non-decimal values.
isSameWidthConstantConversion(Sema & S,Expr * E,QualType T,SourceLocation CC)12440 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12441                                           SourceLocation CC) {
12442   // If initializing from a constant, and the constant starts with '0',
12443   // then it is a binary, octal, or hexadecimal.  Allow these constants
12444   // to fill all the bits, even if there is a sign change.
12445   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12446     const char FirstLiteralCharacter =
12447         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12448     if (FirstLiteralCharacter == '0')
12449       return false;
12450   }
12451 
12452   // If the CC location points to a '{', and the type is char, then assume
12453   // assume it is an array initialization.
12454   if (CC.isValid() && T->isCharType()) {
12455     const char FirstContextCharacter =
12456         S.getSourceManager().getCharacterData(CC)[0];
12457     if (FirstContextCharacter == '{')
12458       return false;
12459   }
12460 
12461   return true;
12462 }
12463 
getIntegerLiteral(Expr * E)12464 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12465   const auto *IL = dyn_cast<IntegerLiteral>(E);
12466   if (!IL) {
12467     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12468       if (UO->getOpcode() == UO_Minus)
12469         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12470     }
12471   }
12472 
12473   return IL;
12474 }
12475 
DiagnoseIntInBoolContext(Sema & S,Expr * E)12476 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12477   E = E->IgnoreParenImpCasts();
12478   SourceLocation ExprLoc = E->getExprLoc();
12479 
12480   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12481     BinaryOperator::Opcode Opc = BO->getOpcode();
12482     Expr::EvalResult Result;
12483     // Do not diagnose unsigned shifts.
12484     if (Opc == BO_Shl) {
12485       const auto *LHS = getIntegerLiteral(BO->getLHS());
12486       const auto *RHS = getIntegerLiteral(BO->getRHS());
12487       if (LHS && LHS->getValue() == 0)
12488         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12489       else if (!E->isValueDependent() && LHS && RHS &&
12490                RHS->getValue().isNonNegative() &&
12491                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12492         S.Diag(ExprLoc, diag::warn_left_shift_always)
12493             << (Result.Val.getInt() != 0);
12494       else if (E->getType()->isSignedIntegerType())
12495         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12496     }
12497   }
12498 
12499   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12500     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12501     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12502     if (!LHS || !RHS)
12503       return;
12504     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12505         (RHS->getValue() == 0 || RHS->getValue() == 1))
12506       // Do not diagnose common idioms.
12507       return;
12508     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12509       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12510   }
12511 }
12512 
CheckImplicitConversion(Sema & S,Expr * E,QualType T,SourceLocation CC,bool * ICContext=nullptr,bool IsListInit=false)12513 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12514                                     SourceLocation CC,
12515                                     bool *ICContext = nullptr,
12516                                     bool IsListInit = false) {
12517   if (E->isTypeDependent() || E->isValueDependent()) return;
12518 
12519   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12520   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12521   if (Source == Target) return;
12522   if (Target->isDependentType()) return;
12523 
12524   // If the conversion context location is invalid don't complain. We also
12525   // don't want to emit a warning if the issue occurs from the expansion of
12526   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12527   // delay this check as long as possible. Once we detect we are in that
12528   // scenario, we just return.
12529   if (CC.isInvalid())
12530     return;
12531 
12532   if (Source->isAtomicType())
12533     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12534 
12535   // Diagnose implicit casts to bool.
12536   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12537     if (isa<StringLiteral>(E))
12538       // Warn on string literal to bool.  Checks for string literals in logical
12539       // and expressions, for instance, assert(0 && "error here"), are
12540       // prevented by a check in AnalyzeImplicitConversions().
12541       return DiagnoseImpCast(S, E, T, CC,
12542                              diag::warn_impcast_string_literal_to_bool);
12543     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12544         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12545       // This covers the literal expressions that evaluate to Objective-C
12546       // objects.
12547       return DiagnoseImpCast(S, E, T, CC,
12548                              diag::warn_impcast_objective_c_literal_to_bool);
12549     }
12550     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12551       // Warn on pointer to bool conversion that is always true.
12552       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12553                                      SourceRange(CC));
12554     }
12555   }
12556 
12557   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12558   // is a typedef for signed char (macOS), then that constant value has to be 1
12559   // or 0.
12560   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12561     Expr::EvalResult Result;
12562     if (E->EvaluateAsInt(Result, S.getASTContext(),
12563                          Expr::SE_AllowSideEffects)) {
12564       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12565         adornObjCBoolConversionDiagWithTernaryFixit(
12566             S, E,
12567             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12568                 << toString(Result.Val.getInt(), 10));
12569       }
12570       return;
12571     }
12572   }
12573 
12574   // Check implicit casts from Objective-C collection literals to specialized
12575   // collection types, e.g., NSArray<NSString *> *.
12576   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12577     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12578   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12579     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12580 
12581   // Strip vector types.
12582   if (isa<VectorType>(Source)) {
12583     if (Target->isVLSTBuiltinType() &&
12584         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12585                                          QualType(Source, 0)) ||
12586          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12587                                             QualType(Source, 0))))
12588       return;
12589 
12590     if (!isa<VectorType>(Target)) {
12591       if (S.SourceMgr.isInSystemMacro(CC))
12592         return;
12593       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12594     }
12595 
12596     // If the vector cast is cast between two vectors of the same size, it is
12597     // a bitcast, not a conversion.
12598     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12599       return;
12600 
12601     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12602     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12603   }
12604   if (auto VecTy = dyn_cast<VectorType>(Target))
12605     Target = VecTy->getElementType().getTypePtr();
12606 
12607   // Strip complex types.
12608   if (isa<ComplexType>(Source)) {
12609     if (!isa<ComplexType>(Target)) {
12610       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12611         return;
12612 
12613       return DiagnoseImpCast(S, E, T, CC,
12614                              S.getLangOpts().CPlusPlus
12615                                  ? diag::err_impcast_complex_scalar
12616                                  : diag::warn_impcast_complex_scalar);
12617     }
12618 
12619     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12620     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12621   }
12622 
12623   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12624   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12625 
12626   // If the source is floating point...
12627   if (SourceBT && SourceBT->isFloatingPoint()) {
12628     // ...and the target is floating point...
12629     if (TargetBT && TargetBT->isFloatingPoint()) {
12630       // ...then warn if we're dropping FP rank.
12631 
12632       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12633           QualType(SourceBT, 0), QualType(TargetBT, 0));
12634       if (Order > 0) {
12635         // Don't warn about float constants that are precisely
12636         // representable in the target type.
12637         Expr::EvalResult result;
12638         if (E->EvaluateAsRValue(result, S.Context)) {
12639           // Value might be a float, a float vector, or a float complex.
12640           if (IsSameFloatAfterCast(result.Val,
12641                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12642                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12643             return;
12644         }
12645 
12646         if (S.SourceMgr.isInSystemMacro(CC))
12647           return;
12648 
12649         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12650       }
12651       // ... or possibly if we're increasing rank, too
12652       else if (Order < 0) {
12653         if (S.SourceMgr.isInSystemMacro(CC))
12654           return;
12655 
12656         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12657       }
12658       return;
12659     }
12660 
12661     // If the target is integral, always warn.
12662     if (TargetBT && TargetBT->isInteger()) {
12663       if (S.SourceMgr.isInSystemMacro(CC))
12664         return;
12665 
12666       DiagnoseFloatingImpCast(S, E, T, CC);
12667     }
12668 
12669     // Detect the case where a call result is converted from floating-point to
12670     // to bool, and the final argument to the call is converted from bool, to
12671     // discover this typo:
12672     //
12673     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12674     //
12675     // FIXME: This is an incredibly special case; is there some more general
12676     // way to detect this class of misplaced-parentheses bug?
12677     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12678       // Check last argument of function call to see if it is an
12679       // implicit cast from a type matching the type the result
12680       // is being cast to.
12681       CallExpr *CEx = cast<CallExpr>(E);
12682       if (unsigned NumArgs = CEx->getNumArgs()) {
12683         Expr *LastA = CEx->getArg(NumArgs - 1);
12684         Expr *InnerE = LastA->IgnoreParenImpCasts();
12685         if (isa<ImplicitCastExpr>(LastA) &&
12686             InnerE->getType()->isBooleanType()) {
12687           // Warn on this floating-point to bool conversion
12688           DiagnoseImpCast(S, E, T, CC,
12689                           diag::warn_impcast_floating_point_to_bool);
12690         }
12691       }
12692     }
12693     return;
12694   }
12695 
12696   // Valid casts involving fixed point types should be accounted for here.
12697   if (Source->isFixedPointType()) {
12698     if (Target->isUnsaturatedFixedPointType()) {
12699       Expr::EvalResult Result;
12700       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12701                                   S.isConstantEvaluated())) {
12702         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12703         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12704         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12705         if (Value > MaxVal || Value < MinVal) {
12706           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12707                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12708                                     << Value.toString() << T
12709                                     << E->getSourceRange()
12710                                     << clang::SourceRange(CC));
12711           return;
12712         }
12713       }
12714     } else if (Target->isIntegerType()) {
12715       Expr::EvalResult Result;
12716       if (!S.isConstantEvaluated() &&
12717           E->EvaluateAsFixedPoint(Result, S.Context,
12718                                   Expr::SE_AllowSideEffects)) {
12719         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12720 
12721         bool Overflowed;
12722         llvm::APSInt IntResult = FXResult.convertToInt(
12723             S.Context.getIntWidth(T),
12724             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12725 
12726         if (Overflowed) {
12727           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12728                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12729                                     << FXResult.toString() << T
12730                                     << E->getSourceRange()
12731                                     << clang::SourceRange(CC));
12732           return;
12733         }
12734       }
12735     }
12736   } else if (Target->isUnsaturatedFixedPointType()) {
12737     if (Source->isIntegerType()) {
12738       Expr::EvalResult Result;
12739       if (!S.isConstantEvaluated() &&
12740           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12741         llvm::APSInt Value = Result.Val.getInt();
12742 
12743         bool Overflowed;
12744         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12745             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12746 
12747         if (Overflowed) {
12748           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12749                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12750                                     << toString(Value, /*Radix=*/10) << T
12751                                     << E->getSourceRange()
12752                                     << clang::SourceRange(CC));
12753           return;
12754         }
12755       }
12756     }
12757   }
12758 
12759   // If we are casting an integer type to a floating point type without
12760   // initialization-list syntax, we might lose accuracy if the floating
12761   // point type has a narrower significand than the integer type.
12762   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12763       TargetBT->isFloatingType() && !IsListInit) {
12764     // Determine the number of precision bits in the source integer type.
12765     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12766                                         /*Approximate*/ true);
12767     unsigned int SourcePrecision = SourceRange.Width;
12768 
12769     // Determine the number of precision bits in the
12770     // target floating point type.
12771     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12772         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12773 
12774     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12775         SourcePrecision > TargetPrecision) {
12776 
12777       if (Optional<llvm::APSInt> SourceInt =
12778               E->getIntegerConstantExpr(S.Context)) {
12779         // If the source integer is a constant, convert it to the target
12780         // floating point type. Issue a warning if the value changes
12781         // during the whole conversion.
12782         llvm::APFloat TargetFloatValue(
12783             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12784         llvm::APFloat::opStatus ConversionStatus =
12785             TargetFloatValue.convertFromAPInt(
12786                 *SourceInt, SourceBT->isSignedInteger(),
12787                 llvm::APFloat::rmNearestTiesToEven);
12788 
12789         if (ConversionStatus != llvm::APFloat::opOK) {
12790           SmallString<32> PrettySourceValue;
12791           SourceInt->toString(PrettySourceValue, 10);
12792           SmallString<32> PrettyTargetValue;
12793           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12794 
12795           S.DiagRuntimeBehavior(
12796               E->getExprLoc(), E,
12797               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12798                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12799                   << E->getSourceRange() << clang::SourceRange(CC));
12800         }
12801       } else {
12802         // Otherwise, the implicit conversion may lose precision.
12803         DiagnoseImpCast(S, E, T, CC,
12804                         diag::warn_impcast_integer_float_precision);
12805       }
12806     }
12807   }
12808 
12809   DiagnoseNullConversion(S, E, T, CC);
12810 
12811   S.DiscardMisalignedMemberAddress(Target, E);
12812 
12813   if (Target->isBooleanType())
12814     DiagnoseIntInBoolContext(S, E);
12815 
12816   if (!Source->isIntegerType() || !Target->isIntegerType())
12817     return;
12818 
12819   // TODO: remove this early return once the false positives for constant->bool
12820   // in templates, macros, etc, are reduced or removed.
12821   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12822     return;
12823 
12824   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12825       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12826     return adornObjCBoolConversionDiagWithTernaryFixit(
12827         S, E,
12828         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12829             << E->getType());
12830   }
12831 
12832   IntRange SourceTypeRange =
12833       IntRange::forTargetOfCanonicalType(S.Context, Source);
12834   IntRange LikelySourceRange =
12835       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12836   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12837 
12838   if (LikelySourceRange.Width > TargetRange.Width) {
12839     // If the source is a constant, use a default-on diagnostic.
12840     // TODO: this should happen for bitfield stores, too.
12841     Expr::EvalResult Result;
12842     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12843                          S.isConstantEvaluated())) {
12844       llvm::APSInt Value(32);
12845       Value = Result.Val.getInt();
12846 
12847       if (S.SourceMgr.isInSystemMacro(CC))
12848         return;
12849 
12850       std::string PrettySourceValue = toString(Value, 10);
12851       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12852 
12853       S.DiagRuntimeBehavior(
12854           E->getExprLoc(), E,
12855           S.PDiag(diag::warn_impcast_integer_precision_constant)
12856               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12857               << E->getSourceRange() << SourceRange(CC));
12858       return;
12859     }
12860 
12861     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12862     if (S.SourceMgr.isInSystemMacro(CC))
12863       return;
12864 
12865     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12866       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12867                              /* pruneControlFlow */ true);
12868     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12869   }
12870 
12871   if (TargetRange.Width > SourceTypeRange.Width) {
12872     if (auto *UO = dyn_cast<UnaryOperator>(E))
12873       if (UO->getOpcode() == UO_Minus)
12874         if (Source->isUnsignedIntegerType()) {
12875           if (Target->isUnsignedIntegerType())
12876             return DiagnoseImpCast(S, E, T, CC,
12877                                    diag::warn_impcast_high_order_zero_bits);
12878           if (Target->isSignedIntegerType())
12879             return DiagnoseImpCast(S, E, T, CC,
12880                                    diag::warn_impcast_nonnegative_result);
12881         }
12882   }
12883 
12884   if (TargetRange.Width == LikelySourceRange.Width &&
12885       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12886       Source->isSignedIntegerType()) {
12887     // Warn when doing a signed to signed conversion, warn if the positive
12888     // source value is exactly the width of the target type, which will
12889     // cause a negative value to be stored.
12890 
12891     Expr::EvalResult Result;
12892     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12893         !S.SourceMgr.isInSystemMacro(CC)) {
12894       llvm::APSInt Value = Result.Val.getInt();
12895       if (isSameWidthConstantConversion(S, E, T, CC)) {
12896         std::string PrettySourceValue = toString(Value, 10);
12897         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12898 
12899         S.DiagRuntimeBehavior(
12900             E->getExprLoc(), E,
12901             S.PDiag(diag::warn_impcast_integer_precision_constant)
12902                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12903                 << E->getSourceRange() << SourceRange(CC));
12904         return;
12905       }
12906     }
12907 
12908     // Fall through for non-constants to give a sign conversion warning.
12909   }
12910 
12911   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12912       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12913        LikelySourceRange.Width == TargetRange.Width)) {
12914     if (S.SourceMgr.isInSystemMacro(CC))
12915       return;
12916 
12917     unsigned DiagID = diag::warn_impcast_integer_sign;
12918 
12919     // Traditionally, gcc has warned about this under -Wsign-compare.
12920     // We also want to warn about it in -Wconversion.
12921     // So if -Wconversion is off, use a completely identical diagnostic
12922     // in the sign-compare group.
12923     // The conditional-checking code will
12924     if (ICContext) {
12925       DiagID = diag::warn_impcast_integer_sign_conditional;
12926       *ICContext = true;
12927     }
12928 
12929     return DiagnoseImpCast(S, E, T, CC, DiagID);
12930   }
12931 
12932   // Diagnose conversions between different enumeration types.
12933   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12934   // type, to give us better diagnostics.
12935   QualType SourceType = E->getType();
12936   if (!S.getLangOpts().CPlusPlus) {
12937     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12938       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12939         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12940         SourceType = S.Context.getTypeDeclType(Enum);
12941         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12942       }
12943   }
12944 
12945   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12946     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12947       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12948           TargetEnum->getDecl()->hasNameForLinkage() &&
12949           SourceEnum != TargetEnum) {
12950         if (S.SourceMgr.isInSystemMacro(CC))
12951           return;
12952 
12953         return DiagnoseImpCast(S, E, SourceType, T, CC,
12954                                diag::warn_impcast_different_enum_types);
12955       }
12956 }
12957 
12958 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12959                                      SourceLocation CC, QualType T);
12960 
CheckConditionalOperand(Sema & S,Expr * E,QualType T,SourceLocation CC,bool & ICContext)12961 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12962                                     SourceLocation CC, bool &ICContext) {
12963   E = E->IgnoreParenImpCasts();
12964 
12965   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12966     return CheckConditionalOperator(S, CO, CC, T);
12967 
12968   AnalyzeImplicitConversions(S, E, CC);
12969   if (E->getType() != T)
12970     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12971 }
12972 
CheckConditionalOperator(Sema & S,AbstractConditionalOperator * E,SourceLocation CC,QualType T)12973 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12974                                      SourceLocation CC, QualType T) {
12975   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12976 
12977   Expr *TrueExpr = E->getTrueExpr();
12978   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12979     TrueExpr = BCO->getCommon();
12980 
12981   bool Suspicious = false;
12982   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12983   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12984 
12985   if (T->isBooleanType())
12986     DiagnoseIntInBoolContext(S, E);
12987 
12988   // If -Wconversion would have warned about either of the candidates
12989   // for a signedness conversion to the context type...
12990   if (!Suspicious) return;
12991 
12992   // ...but it's currently ignored...
12993   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12994     return;
12995 
12996   // ...then check whether it would have warned about either of the
12997   // candidates for a signedness conversion to the condition type.
12998   if (E->getType() == T) return;
12999 
13000   Suspicious = false;
13001   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13002                           E->getType(), CC, &Suspicious);
13003   if (!Suspicious)
13004     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13005                             E->getType(), CC, &Suspicious);
13006 }
13007 
13008 /// Check conversion of given expression to boolean.
13009 /// Input argument E is a logical expression.
CheckBoolLikeConversion(Sema & S,Expr * E,SourceLocation CC)13010 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13011   if (S.getLangOpts().Bool)
13012     return;
13013   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13014     return;
13015   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13016 }
13017 
13018 namespace {
13019 struct AnalyzeImplicitConversionsWorkItem {
13020   Expr *E;
13021   SourceLocation CC;
13022   bool IsListInit;
13023 };
13024 }
13025 
13026 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13027 /// that should be visited are added to WorkList.
AnalyzeImplicitConversions(Sema & S,AnalyzeImplicitConversionsWorkItem Item,llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> & WorkList)13028 static void AnalyzeImplicitConversions(
13029     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13030     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13031   Expr *OrigE = Item.E;
13032   SourceLocation CC = Item.CC;
13033 
13034   QualType T = OrigE->getType();
13035   Expr *E = OrigE->IgnoreParenImpCasts();
13036 
13037   // Propagate whether we are in a C++ list initialization expression.
13038   // If so, we do not issue warnings for implicit int-float conversion
13039   // precision loss, because C++11 narrowing already handles it.
13040   bool IsListInit = Item.IsListInit ||
13041                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13042 
13043   if (E->isTypeDependent() || E->isValueDependent())
13044     return;
13045 
13046   Expr *SourceExpr = E;
13047   // Examine, but don't traverse into the source expression of an
13048   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13049   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13050   // evaluate it in the context of checking the specific conversion to T though.
13051   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13052     if (auto *Src = OVE->getSourceExpr())
13053       SourceExpr = Src;
13054 
13055   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13056     if (UO->getOpcode() == UO_Not &&
13057         UO->getSubExpr()->isKnownToHaveBooleanValue())
13058       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13059           << OrigE->getSourceRange() << T->isBooleanType()
13060           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13061 
13062   // For conditional operators, we analyze the arguments as if they
13063   // were being fed directly into the output.
13064   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13065     CheckConditionalOperator(S, CO, CC, T);
13066     return;
13067   }
13068 
13069   // Check implicit argument conversions for function calls.
13070   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13071     CheckImplicitArgumentConversions(S, Call, CC);
13072 
13073   // Go ahead and check any implicit conversions we might have skipped.
13074   // The non-canonical typecheck is just an optimization;
13075   // CheckImplicitConversion will filter out dead implicit conversions.
13076   if (SourceExpr->getType() != T)
13077     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13078 
13079   // Now continue drilling into this expression.
13080 
13081   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13082     // The bound subexpressions in a PseudoObjectExpr are not reachable
13083     // as transitive children.
13084     // FIXME: Use a more uniform representation for this.
13085     for (auto *SE : POE->semantics())
13086       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13087         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13088   }
13089 
13090   // Skip past explicit casts.
13091   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13092     E = CE->getSubExpr()->IgnoreParenImpCasts();
13093     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13094       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13095     WorkList.push_back({E, CC, IsListInit});
13096     return;
13097   }
13098 
13099   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13100     // Do a somewhat different check with comparison operators.
13101     if (BO->isComparisonOp())
13102       return AnalyzeComparison(S, BO);
13103 
13104     // And with simple assignments.
13105     if (BO->getOpcode() == BO_Assign)
13106       return AnalyzeAssignment(S, BO);
13107     // And with compound assignments.
13108     if (BO->isAssignmentOp())
13109       return AnalyzeCompoundAssignment(S, BO);
13110   }
13111 
13112   // These break the otherwise-useful invariant below.  Fortunately,
13113   // we don't really need to recurse into them, because any internal
13114   // expressions should have been analyzed already when they were
13115   // built into statements.
13116   if (isa<StmtExpr>(E)) return;
13117 
13118   // Don't descend into unevaluated contexts.
13119   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13120 
13121   // Now just recurse over the expression's children.
13122   CC = E->getExprLoc();
13123   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13124   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13125   for (Stmt *SubStmt : E->children()) {
13126     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13127     if (!ChildExpr)
13128       continue;
13129 
13130     if (IsLogicalAndOperator &&
13131         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13132       // Ignore checking string literals that are in logical and operators.
13133       // This is a common pattern for asserts.
13134       continue;
13135     WorkList.push_back({ChildExpr, CC, IsListInit});
13136   }
13137 
13138   if (BO && BO->isLogicalOp()) {
13139     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13140     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13141       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13142 
13143     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13144     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13145       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13146   }
13147 
13148   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13149     if (U->getOpcode() == UO_LNot) {
13150       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13151     } else if (U->getOpcode() != UO_AddrOf) {
13152       if (U->getSubExpr()->getType()->isAtomicType())
13153         S.Diag(U->getSubExpr()->getBeginLoc(),
13154                diag::warn_atomic_implicit_seq_cst);
13155     }
13156   }
13157 }
13158 
13159 /// AnalyzeImplicitConversions - Find and report any interesting
13160 /// implicit conversions in the given expression.  There are a couple
13161 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
AnalyzeImplicitConversions(Sema & S,Expr * OrigE,SourceLocation CC,bool IsListInit)13162 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13163                                        bool IsListInit/*= false*/) {
13164   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13165   WorkList.push_back({OrigE, CC, IsListInit});
13166   while (!WorkList.empty())
13167     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13168 }
13169 
13170 /// Diagnose integer type and any valid implicit conversion to it.
checkOpenCLEnqueueIntType(Sema & S,Expr * E,const QualType & IntT)13171 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13172   // Taking into account implicit conversions,
13173   // allow any integer.
13174   if (!E->getType()->isIntegerType()) {
13175     S.Diag(E->getBeginLoc(),
13176            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13177     return true;
13178   }
13179   // Potentially emit standard warnings for implicit conversions if enabled
13180   // using -Wconversion.
13181   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13182   return false;
13183 }
13184 
13185 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13186 // Returns true when emitting a warning about taking the address of a reference.
CheckForReference(Sema & SemaRef,const Expr * E,const PartialDiagnostic & PD)13187 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13188                               const PartialDiagnostic &PD) {
13189   E = E->IgnoreParenImpCasts();
13190 
13191   const FunctionDecl *FD = nullptr;
13192 
13193   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13194     if (!DRE->getDecl()->getType()->isReferenceType())
13195       return false;
13196   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13197     if (!M->getMemberDecl()->getType()->isReferenceType())
13198       return false;
13199   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13200     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13201       return false;
13202     FD = Call->getDirectCallee();
13203   } else {
13204     return false;
13205   }
13206 
13207   SemaRef.Diag(E->getExprLoc(), PD);
13208 
13209   // If possible, point to location of function.
13210   if (FD) {
13211     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13212   }
13213 
13214   return true;
13215 }
13216 
13217 // Returns true if the SourceLocation is expanded from any macro body.
13218 // Returns false if the SourceLocation is invalid, is from not in a macro
13219 // expansion, or is from expanded from a top-level macro argument.
IsInAnyMacroBody(const SourceManager & SM,SourceLocation Loc)13220 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13221   if (Loc.isInvalid())
13222     return false;
13223 
13224   while (Loc.isMacroID()) {
13225     if (SM.isMacroBodyExpansion(Loc))
13226       return true;
13227     Loc = SM.getImmediateMacroCallerLoc(Loc);
13228   }
13229 
13230   return false;
13231 }
13232 
13233 /// Diagnose pointers that are always non-null.
13234 /// \param E the expression containing the pointer
13235 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13236 /// compared to a null pointer
13237 /// \param IsEqual True when the comparison is equal to a null pointer
13238 /// \param Range Extra SourceRange to highlight in the diagnostic
DiagnoseAlwaysNonNullPointer(Expr * E,Expr::NullPointerConstantKind NullKind,bool IsEqual,SourceRange Range)13239 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13240                                         Expr::NullPointerConstantKind NullKind,
13241                                         bool IsEqual, SourceRange Range) {
13242   if (!E)
13243     return;
13244 
13245   // Don't warn inside macros.
13246   if (E->getExprLoc().isMacroID()) {
13247     const SourceManager &SM = getSourceManager();
13248     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13249         IsInAnyMacroBody(SM, Range.getBegin()))
13250       return;
13251   }
13252   E = E->IgnoreImpCasts();
13253 
13254   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13255 
13256   if (isa<CXXThisExpr>(E)) {
13257     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13258                                 : diag::warn_this_bool_conversion;
13259     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13260     return;
13261   }
13262 
13263   bool IsAddressOf = false;
13264 
13265   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13266     if (UO->getOpcode() != UO_AddrOf)
13267       return;
13268     IsAddressOf = true;
13269     E = UO->getSubExpr();
13270   }
13271 
13272   if (IsAddressOf) {
13273     unsigned DiagID = IsCompare
13274                           ? diag::warn_address_of_reference_null_compare
13275                           : diag::warn_address_of_reference_bool_conversion;
13276     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13277                                          << IsEqual;
13278     if (CheckForReference(*this, E, PD)) {
13279       return;
13280     }
13281   }
13282 
13283   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13284     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13285     std::string Str;
13286     llvm::raw_string_ostream S(Str);
13287     E->printPretty(S, nullptr, getPrintingPolicy());
13288     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13289                                 : diag::warn_cast_nonnull_to_bool;
13290     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13291       << E->getSourceRange() << Range << IsEqual;
13292     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13293   };
13294 
13295   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13296   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13297     if (auto *Callee = Call->getDirectCallee()) {
13298       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13299         ComplainAboutNonnullParamOrCall(A);
13300         return;
13301       }
13302     }
13303   }
13304 
13305   // Expect to find a single Decl.  Skip anything more complicated.
13306   ValueDecl *D = nullptr;
13307   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13308     D = R->getDecl();
13309   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13310     D = M->getMemberDecl();
13311   }
13312 
13313   // Weak Decls can be null.
13314   if (!D || D->isWeak())
13315     return;
13316 
13317   // Check for parameter decl with nonnull attribute
13318   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13319     if (getCurFunction() &&
13320         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13321       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13322         ComplainAboutNonnullParamOrCall(A);
13323         return;
13324       }
13325 
13326       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13327         // Skip function template not specialized yet.
13328         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13329           return;
13330         auto ParamIter = llvm::find(FD->parameters(), PV);
13331         assert(ParamIter != FD->param_end());
13332         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13333 
13334         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13335           if (!NonNull->args_size()) {
13336               ComplainAboutNonnullParamOrCall(NonNull);
13337               return;
13338           }
13339 
13340           for (const ParamIdx &ArgNo : NonNull->args()) {
13341             if (ArgNo.getASTIndex() == ParamNo) {
13342               ComplainAboutNonnullParamOrCall(NonNull);
13343               return;
13344             }
13345           }
13346         }
13347       }
13348     }
13349   }
13350 
13351   QualType T = D->getType();
13352   const bool IsArray = T->isArrayType();
13353   const bool IsFunction = T->isFunctionType();
13354 
13355   // Address of function is used to silence the function warning.
13356   if (IsAddressOf && IsFunction) {
13357     return;
13358   }
13359 
13360   // Found nothing.
13361   if (!IsAddressOf && !IsFunction && !IsArray)
13362     return;
13363 
13364   // Pretty print the expression for the diagnostic.
13365   std::string Str;
13366   llvm::raw_string_ostream S(Str);
13367   E->printPretty(S, nullptr, getPrintingPolicy());
13368 
13369   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13370                               : diag::warn_impcast_pointer_to_bool;
13371   enum {
13372     AddressOf,
13373     FunctionPointer,
13374     ArrayPointer
13375   } DiagType;
13376   if (IsAddressOf)
13377     DiagType = AddressOf;
13378   else if (IsFunction)
13379     DiagType = FunctionPointer;
13380   else if (IsArray)
13381     DiagType = ArrayPointer;
13382   else
13383     llvm_unreachable("Could not determine diagnostic.");
13384   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13385                                 << Range << IsEqual;
13386 
13387   if (!IsFunction)
13388     return;
13389 
13390   // Suggest '&' to silence the function warning.
13391   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13392       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13393 
13394   // Check to see if '()' fixit should be emitted.
13395   QualType ReturnType;
13396   UnresolvedSet<4> NonTemplateOverloads;
13397   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13398   if (ReturnType.isNull())
13399     return;
13400 
13401   if (IsCompare) {
13402     // There are two cases here.  If there is null constant, the only suggest
13403     // for a pointer return type.  If the null is 0, then suggest if the return
13404     // type is a pointer or an integer type.
13405     if (!ReturnType->isPointerType()) {
13406       if (NullKind == Expr::NPCK_ZeroExpression ||
13407           NullKind == Expr::NPCK_ZeroLiteral) {
13408         if (!ReturnType->isIntegerType())
13409           return;
13410       } else {
13411         return;
13412       }
13413     }
13414   } else { // !IsCompare
13415     // For function to bool, only suggest if the function pointer has bool
13416     // return type.
13417     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13418       return;
13419   }
13420   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13421       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13422 }
13423 
13424 /// Diagnoses "dangerous" implicit conversions within the given
13425 /// expression (which is a full expression).  Implements -Wconversion
13426 /// and -Wsign-compare.
13427 ///
13428 /// \param CC the "context" location of the implicit conversion, i.e.
13429 ///   the most location of the syntactic entity requiring the implicit
13430 ///   conversion
CheckImplicitConversions(Expr * E,SourceLocation CC)13431 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13432   // Don't diagnose in unevaluated contexts.
13433   if (isUnevaluatedContext())
13434     return;
13435 
13436   // Don't diagnose for value- or type-dependent expressions.
13437   if (E->isTypeDependent() || E->isValueDependent())
13438     return;
13439 
13440   // Check for array bounds violations in cases where the check isn't triggered
13441   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13442   // ArraySubscriptExpr is on the RHS of a variable initialization.
13443   CheckArrayAccess(E);
13444 
13445   // This is not the right CC for (e.g.) a variable initialization.
13446   AnalyzeImplicitConversions(*this, E, CC);
13447 }
13448 
13449 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13450 /// Input argument E is a logical expression.
CheckBoolLikeConversion(Expr * E,SourceLocation CC)13451 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13452   ::CheckBoolLikeConversion(*this, E, CC);
13453 }
13454 
13455 /// Diagnose when expression is an integer constant expression and its evaluation
13456 /// results in integer overflow
CheckForIntOverflow(Expr * E)13457 void Sema::CheckForIntOverflow (Expr *E) {
13458   // Use a work list to deal with nested struct initializers.
13459   SmallVector<Expr *, 2> Exprs(1, E);
13460 
13461   do {
13462     Expr *OriginalE = Exprs.pop_back_val();
13463     Expr *E = OriginalE->IgnoreParenCasts();
13464 
13465     if (isa<BinaryOperator>(E)) {
13466       E->EvaluateForOverflow(Context);
13467       continue;
13468     }
13469 
13470     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13471       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13472     else if (isa<ObjCBoxedExpr>(OriginalE))
13473       E->EvaluateForOverflow(Context);
13474     else if (auto Call = dyn_cast<CallExpr>(E))
13475       Exprs.append(Call->arg_begin(), Call->arg_end());
13476     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13477       Exprs.append(Message->arg_begin(), Message->arg_end());
13478   } while (!Exprs.empty());
13479 }
13480 
13481 namespace {
13482 
13483 /// Visitor for expressions which looks for unsequenced operations on the
13484 /// same object.
13485 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13486   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13487 
13488   /// A tree of sequenced regions within an expression. Two regions are
13489   /// unsequenced if one is an ancestor or a descendent of the other. When we
13490   /// finish processing an expression with sequencing, such as a comma
13491   /// expression, we fold its tree nodes into its parent, since they are
13492   /// unsequenced with respect to nodes we will visit later.
13493   class SequenceTree {
13494     struct Value {
Value__anona96a15881f11::SequenceChecker::SequenceTree::Value13495       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13496       unsigned Parent : 31;
13497       unsigned Merged : 1;
13498     };
13499     SmallVector<Value, 8> Values;
13500 
13501   public:
13502     /// A region within an expression which may be sequenced with respect
13503     /// to some other region.
13504     class Seq {
13505       friend class SequenceTree;
13506 
13507       unsigned Index;
13508 
Seq(unsigned N)13509       explicit Seq(unsigned N) : Index(N) {}
13510 
13511     public:
Seq()13512       Seq() : Index(0) {}
13513     };
13514 
SequenceTree()13515     SequenceTree() { Values.push_back(Value(0)); }
root() const13516     Seq root() const { return Seq(0); }
13517 
13518     /// Create a new sequence of operations, which is an unsequenced
13519     /// subset of \p Parent. This sequence of operations is sequenced with
13520     /// respect to other children of \p Parent.
allocate(Seq Parent)13521     Seq allocate(Seq Parent) {
13522       Values.push_back(Value(Parent.Index));
13523       return Seq(Values.size() - 1);
13524     }
13525 
13526     /// Merge a sequence of operations into its parent.
merge(Seq S)13527     void merge(Seq S) {
13528       Values[S.Index].Merged = true;
13529     }
13530 
13531     /// Determine whether two operations are unsequenced. This operation
13532     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13533     /// should have been merged into its parent as appropriate.
isUnsequenced(Seq Cur,Seq Old)13534     bool isUnsequenced(Seq Cur, Seq Old) {
13535       unsigned C = representative(Cur.Index);
13536       unsigned Target = representative(Old.Index);
13537       while (C >= Target) {
13538         if (C == Target)
13539           return true;
13540         C = Values[C].Parent;
13541       }
13542       return false;
13543     }
13544 
13545   private:
13546     /// Pick a representative for a sequence.
representative(unsigned K)13547     unsigned representative(unsigned K) {
13548       if (Values[K].Merged)
13549         // Perform path compression as we go.
13550         return Values[K].Parent = representative(Values[K].Parent);
13551       return K;
13552     }
13553   };
13554 
13555   /// An object for which we can track unsequenced uses.
13556   using Object = const NamedDecl *;
13557 
13558   /// Different flavors of object usage which we track. We only track the
13559   /// least-sequenced usage of each kind.
13560   enum UsageKind {
13561     /// A read of an object. Multiple unsequenced reads are OK.
13562     UK_Use,
13563 
13564     /// A modification of an object which is sequenced before the value
13565     /// computation of the expression, such as ++n in C++.
13566     UK_ModAsValue,
13567 
13568     /// A modification of an object which is not sequenced before the value
13569     /// computation of the expression, such as n++.
13570     UK_ModAsSideEffect,
13571 
13572     UK_Count = UK_ModAsSideEffect + 1
13573   };
13574 
13575   /// Bundle together a sequencing region and the expression corresponding
13576   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13577   struct Usage {
13578     const Expr *UsageExpr;
13579     SequenceTree::Seq Seq;
13580 
Usage__anona96a15881f11::SequenceChecker::Usage13581     Usage() : UsageExpr(nullptr), Seq() {}
13582   };
13583 
13584   struct UsageInfo {
13585     Usage Uses[UK_Count];
13586 
13587     /// Have we issued a diagnostic for this object already?
13588     bool Diagnosed;
13589 
UsageInfo__anona96a15881f11::SequenceChecker::UsageInfo13590     UsageInfo() : Uses(), Diagnosed(false) {}
13591   };
13592   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13593 
13594   Sema &SemaRef;
13595 
13596   /// Sequenced regions within the expression.
13597   SequenceTree Tree;
13598 
13599   /// Declaration modifications and references which we have seen.
13600   UsageInfoMap UsageMap;
13601 
13602   /// The region we are currently within.
13603   SequenceTree::Seq Region;
13604 
13605   /// Filled in with declarations which were modified as a side-effect
13606   /// (that is, post-increment operations).
13607   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13608 
13609   /// Expressions to check later. We defer checking these to reduce
13610   /// stack usage.
13611   SmallVectorImpl<const Expr *> &WorkList;
13612 
13613   /// RAII object wrapping the visitation of a sequenced subexpression of an
13614   /// expression. At the end of this process, the side-effects of the evaluation
13615   /// become sequenced with respect to the value computation of the result, so
13616   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13617   /// UK_ModAsValue.
13618   struct SequencedSubexpression {
SequencedSubexpression__anona96a15881f11::SequenceChecker::SequencedSubexpression13619     SequencedSubexpression(SequenceChecker &Self)
13620       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13621       Self.ModAsSideEffect = &ModAsSideEffect;
13622     }
13623 
~SequencedSubexpression__anona96a15881f11::SequenceChecker::SequencedSubexpression13624     ~SequencedSubexpression() {
13625       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13626         // Add a new usage with usage kind UK_ModAsValue, and then restore
13627         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13628         // the previous one was empty).
13629         UsageInfo &UI = Self.UsageMap[M.first];
13630         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13631         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13632         SideEffectUsage = M.second;
13633       }
13634       Self.ModAsSideEffect = OldModAsSideEffect;
13635     }
13636 
13637     SequenceChecker &Self;
13638     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13639     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13640   };
13641 
13642   /// RAII object wrapping the visitation of a subexpression which we might
13643   /// choose to evaluate as a constant. If any subexpression is evaluated and
13644   /// found to be non-constant, this allows us to suppress the evaluation of
13645   /// the outer expression.
13646   class EvaluationTracker {
13647   public:
EvaluationTracker(SequenceChecker & Self)13648     EvaluationTracker(SequenceChecker &Self)
13649         : Self(Self), Prev(Self.EvalTracker) {
13650       Self.EvalTracker = this;
13651     }
13652 
~EvaluationTracker()13653     ~EvaluationTracker() {
13654       Self.EvalTracker = Prev;
13655       if (Prev)
13656         Prev->EvalOK &= EvalOK;
13657     }
13658 
evaluate(const Expr * E,bool & Result)13659     bool evaluate(const Expr *E, bool &Result) {
13660       if (!EvalOK || E->isValueDependent())
13661         return false;
13662       EvalOK = E->EvaluateAsBooleanCondition(
13663           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13664       return EvalOK;
13665     }
13666 
13667   private:
13668     SequenceChecker &Self;
13669     EvaluationTracker *Prev;
13670     bool EvalOK = true;
13671   } *EvalTracker = nullptr;
13672 
13673   /// Find the object which is produced by the specified expression,
13674   /// if any.
getObject(const Expr * E,bool Mod) const13675   Object getObject(const Expr *E, bool Mod) const {
13676     E = E->IgnoreParenCasts();
13677     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13678       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13679         return getObject(UO->getSubExpr(), Mod);
13680     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13681       if (BO->getOpcode() == BO_Comma)
13682         return getObject(BO->getRHS(), Mod);
13683       if (Mod && BO->isAssignmentOp())
13684         return getObject(BO->getLHS(), Mod);
13685     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13686       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13687       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13688         return ME->getMemberDecl();
13689     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13690       // FIXME: If this is a reference, map through to its value.
13691       return DRE->getDecl();
13692     return nullptr;
13693   }
13694 
13695   /// Note that an object \p O was modified or used by an expression
13696   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13697   /// the object \p O as obtained via the \p UsageMap.
addUsage(Object O,UsageInfo & UI,const Expr * UsageExpr,UsageKind UK)13698   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13699     // Get the old usage for the given object and usage kind.
13700     Usage &U = UI.Uses[UK];
13701     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13702       // If we have a modification as side effect and are in a sequenced
13703       // subexpression, save the old Usage so that we can restore it later
13704       // in SequencedSubexpression::~SequencedSubexpression.
13705       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13706         ModAsSideEffect->push_back(std::make_pair(O, U));
13707       // Then record the new usage with the current sequencing region.
13708       U.UsageExpr = UsageExpr;
13709       U.Seq = Region;
13710     }
13711   }
13712 
13713   /// Check whether a modification or use of an object \p O in an expression
13714   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13715   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13716   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13717   /// usage and false we are checking for a mod-use unsequenced usage.
checkUsage(Object O,UsageInfo & UI,const Expr * UsageExpr,UsageKind OtherKind,bool IsModMod)13718   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13719                   UsageKind OtherKind, bool IsModMod) {
13720     if (UI.Diagnosed)
13721       return;
13722 
13723     const Usage &U = UI.Uses[OtherKind];
13724     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13725       return;
13726 
13727     const Expr *Mod = U.UsageExpr;
13728     const Expr *ModOrUse = UsageExpr;
13729     if (OtherKind == UK_Use)
13730       std::swap(Mod, ModOrUse);
13731 
13732     SemaRef.DiagRuntimeBehavior(
13733         Mod->getExprLoc(), {Mod, ModOrUse},
13734         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13735                                : diag::warn_unsequenced_mod_use)
13736             << O << SourceRange(ModOrUse->getExprLoc()));
13737     UI.Diagnosed = true;
13738   }
13739 
13740   // A note on note{Pre, Post}{Use, Mod}:
13741   //
13742   // (It helps to follow the algorithm with an expression such as
13743   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13744   //  operations before C++17 and both are well-defined in C++17).
13745   //
13746   // When visiting a node which uses/modify an object we first call notePreUse
13747   // or notePreMod before visiting its sub-expression(s). At this point the
13748   // children of the current node have not yet been visited and so the eventual
13749   // uses/modifications resulting from the children of the current node have not
13750   // been recorded yet.
13751   //
13752   // We then visit the children of the current node. After that notePostUse or
13753   // notePostMod is called. These will 1) detect an unsequenced modification
13754   // as side effect (as in "k++ + k") and 2) add a new usage with the
13755   // appropriate usage kind.
13756   //
13757   // We also have to be careful that some operation sequences modification as
13758   // side effect as well (for example: || or ,). To account for this we wrap
13759   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13760   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13761   // which record usages which are modifications as side effect, and then
13762   // downgrade them (or more accurately restore the previous usage which was a
13763   // modification as side effect) when exiting the scope of the sequenced
13764   // subexpression.
13765 
notePreUse(Object O,const Expr * UseExpr)13766   void notePreUse(Object O, const Expr *UseExpr) {
13767     UsageInfo &UI = UsageMap[O];
13768     // Uses conflict with other modifications.
13769     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13770   }
13771 
notePostUse(Object O,const Expr * UseExpr)13772   void notePostUse(Object O, const Expr *UseExpr) {
13773     UsageInfo &UI = UsageMap[O];
13774     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13775                /*IsModMod=*/false);
13776     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13777   }
13778 
notePreMod(Object O,const Expr * ModExpr)13779   void notePreMod(Object O, const Expr *ModExpr) {
13780     UsageInfo &UI = UsageMap[O];
13781     // Modifications conflict with other modifications and with uses.
13782     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13783     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13784   }
13785 
notePostMod(Object O,const Expr * ModExpr,UsageKind UK)13786   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13787     UsageInfo &UI = UsageMap[O];
13788     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13789                /*IsModMod=*/true);
13790     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13791   }
13792 
13793 public:
SequenceChecker(Sema & S,const Expr * E,SmallVectorImpl<const Expr * > & WorkList)13794   SequenceChecker(Sema &S, const Expr *E,
13795                   SmallVectorImpl<const Expr *> &WorkList)
13796       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13797     Visit(E);
13798     // Silence a -Wunused-private-field since WorkList is now unused.
13799     // TODO: Evaluate if it can be used, and if not remove it.
13800     (void)this->WorkList;
13801   }
13802 
VisitStmt(const Stmt * S)13803   void VisitStmt(const Stmt *S) {
13804     // Skip all statements which aren't expressions for now.
13805   }
13806 
VisitExpr(const Expr * E)13807   void VisitExpr(const Expr *E) {
13808     // By default, just recurse to evaluated subexpressions.
13809     Base::VisitStmt(E);
13810   }
13811 
VisitCastExpr(const CastExpr * E)13812   void VisitCastExpr(const CastExpr *E) {
13813     Object O = Object();
13814     if (E->getCastKind() == CK_LValueToRValue)
13815       O = getObject(E->getSubExpr(), false);
13816 
13817     if (O)
13818       notePreUse(O, E);
13819     VisitExpr(E);
13820     if (O)
13821       notePostUse(O, E);
13822   }
13823 
VisitSequencedExpressions(const Expr * SequencedBefore,const Expr * SequencedAfter)13824   void VisitSequencedExpressions(const Expr *SequencedBefore,
13825                                  const Expr *SequencedAfter) {
13826     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13827     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13828     SequenceTree::Seq OldRegion = Region;
13829 
13830     {
13831       SequencedSubexpression SeqBefore(*this);
13832       Region = BeforeRegion;
13833       Visit(SequencedBefore);
13834     }
13835 
13836     Region = AfterRegion;
13837     Visit(SequencedAfter);
13838 
13839     Region = OldRegion;
13840 
13841     Tree.merge(BeforeRegion);
13842     Tree.merge(AfterRegion);
13843   }
13844 
VisitArraySubscriptExpr(const ArraySubscriptExpr * ASE)13845   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13846     // C++17 [expr.sub]p1:
13847     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13848     //   expression E1 is sequenced before the expression E2.
13849     if (SemaRef.getLangOpts().CPlusPlus17)
13850       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13851     else {
13852       Visit(ASE->getLHS());
13853       Visit(ASE->getRHS());
13854     }
13855   }
13856 
VisitBinPtrMemD(const BinaryOperator * BO)13857   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
VisitBinPtrMemI(const BinaryOperator * BO)13858   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
VisitBinPtrMem(const BinaryOperator * BO)13859   void VisitBinPtrMem(const BinaryOperator *BO) {
13860     // C++17 [expr.mptr.oper]p4:
13861     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13862     //  the expression E1 is sequenced before the expression E2.
13863     if (SemaRef.getLangOpts().CPlusPlus17)
13864       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13865     else {
13866       Visit(BO->getLHS());
13867       Visit(BO->getRHS());
13868     }
13869   }
13870 
VisitBinShl(const BinaryOperator * BO)13871   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
VisitBinShr(const BinaryOperator * BO)13872   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
VisitBinShlShr(const BinaryOperator * BO)13873   void VisitBinShlShr(const BinaryOperator *BO) {
13874     // C++17 [expr.shift]p4:
13875     //  The expression E1 is sequenced before the expression E2.
13876     if (SemaRef.getLangOpts().CPlusPlus17)
13877       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13878     else {
13879       Visit(BO->getLHS());
13880       Visit(BO->getRHS());
13881     }
13882   }
13883 
VisitBinComma(const BinaryOperator * BO)13884   void VisitBinComma(const BinaryOperator *BO) {
13885     // C++11 [expr.comma]p1:
13886     //   Every value computation and side effect associated with the left
13887     //   expression is sequenced before every value computation and side
13888     //   effect associated with the right expression.
13889     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13890   }
13891 
VisitBinAssign(const BinaryOperator * BO)13892   void VisitBinAssign(const BinaryOperator *BO) {
13893     SequenceTree::Seq RHSRegion;
13894     SequenceTree::Seq LHSRegion;
13895     if (SemaRef.getLangOpts().CPlusPlus17) {
13896       RHSRegion = Tree.allocate(Region);
13897       LHSRegion = Tree.allocate(Region);
13898     } else {
13899       RHSRegion = Region;
13900       LHSRegion = Region;
13901     }
13902     SequenceTree::Seq OldRegion = Region;
13903 
13904     // C++11 [expr.ass]p1:
13905     //  [...] the assignment is sequenced after the value computation
13906     //  of the right and left operands, [...]
13907     //
13908     // so check it before inspecting the operands and update the
13909     // map afterwards.
13910     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13911     if (O)
13912       notePreMod(O, BO);
13913 
13914     if (SemaRef.getLangOpts().CPlusPlus17) {
13915       // C++17 [expr.ass]p1:
13916       //  [...] The right operand is sequenced before the left operand. [...]
13917       {
13918         SequencedSubexpression SeqBefore(*this);
13919         Region = RHSRegion;
13920         Visit(BO->getRHS());
13921       }
13922 
13923       Region = LHSRegion;
13924       Visit(BO->getLHS());
13925 
13926       if (O && isa<CompoundAssignOperator>(BO))
13927         notePostUse(O, BO);
13928 
13929     } else {
13930       // C++11 does not specify any sequencing between the LHS and RHS.
13931       Region = LHSRegion;
13932       Visit(BO->getLHS());
13933 
13934       if (O && isa<CompoundAssignOperator>(BO))
13935         notePostUse(O, BO);
13936 
13937       Region = RHSRegion;
13938       Visit(BO->getRHS());
13939     }
13940 
13941     // C++11 [expr.ass]p1:
13942     //  the assignment is sequenced [...] before the value computation of the
13943     //  assignment expression.
13944     // C11 6.5.16/3 has no such rule.
13945     Region = OldRegion;
13946     if (O)
13947       notePostMod(O, BO,
13948                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13949                                                   : UK_ModAsSideEffect);
13950     if (SemaRef.getLangOpts().CPlusPlus17) {
13951       Tree.merge(RHSRegion);
13952       Tree.merge(LHSRegion);
13953     }
13954   }
13955 
VisitCompoundAssignOperator(const CompoundAssignOperator * CAO)13956   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13957     VisitBinAssign(CAO);
13958   }
13959 
VisitUnaryPreInc(const UnaryOperator * UO)13960   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
VisitUnaryPreDec(const UnaryOperator * UO)13961   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
VisitUnaryPreIncDec(const UnaryOperator * UO)13962   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13963     Object O = getObject(UO->getSubExpr(), true);
13964     if (!O)
13965       return VisitExpr(UO);
13966 
13967     notePreMod(O, UO);
13968     Visit(UO->getSubExpr());
13969     // C++11 [expr.pre.incr]p1:
13970     //   the expression ++x is equivalent to x+=1
13971     notePostMod(O, UO,
13972                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13973                                                 : UK_ModAsSideEffect);
13974   }
13975 
VisitUnaryPostInc(const UnaryOperator * UO)13976   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
VisitUnaryPostDec(const UnaryOperator * UO)13977   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
VisitUnaryPostIncDec(const UnaryOperator * UO)13978   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13979     Object O = getObject(UO->getSubExpr(), true);
13980     if (!O)
13981       return VisitExpr(UO);
13982 
13983     notePreMod(O, UO);
13984     Visit(UO->getSubExpr());
13985     notePostMod(O, UO, UK_ModAsSideEffect);
13986   }
13987 
VisitBinLOr(const BinaryOperator * BO)13988   void VisitBinLOr(const BinaryOperator *BO) {
13989     // C++11 [expr.log.or]p2:
13990     //  If the second expression is evaluated, every value computation and
13991     //  side effect associated with the first expression is sequenced before
13992     //  every value computation and side effect associated with the
13993     //  second expression.
13994     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13995     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13996     SequenceTree::Seq OldRegion = Region;
13997 
13998     EvaluationTracker Eval(*this);
13999     {
14000       SequencedSubexpression Sequenced(*this);
14001       Region = LHSRegion;
14002       Visit(BO->getLHS());
14003     }
14004 
14005     // C++11 [expr.log.or]p1:
14006     //  [...] the second operand is not evaluated if the first operand
14007     //  evaluates to true.
14008     bool EvalResult = false;
14009     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14010     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14011     if (ShouldVisitRHS) {
14012       Region = RHSRegion;
14013       Visit(BO->getRHS());
14014     }
14015 
14016     Region = OldRegion;
14017     Tree.merge(LHSRegion);
14018     Tree.merge(RHSRegion);
14019   }
14020 
VisitBinLAnd(const BinaryOperator * BO)14021   void VisitBinLAnd(const BinaryOperator *BO) {
14022     // C++11 [expr.log.and]p2:
14023     //  If the second expression is evaluated, every value computation and
14024     //  side effect associated with the first expression is sequenced before
14025     //  every value computation and side effect associated with the
14026     //  second expression.
14027     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14028     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14029     SequenceTree::Seq OldRegion = Region;
14030 
14031     EvaluationTracker Eval(*this);
14032     {
14033       SequencedSubexpression Sequenced(*this);
14034       Region = LHSRegion;
14035       Visit(BO->getLHS());
14036     }
14037 
14038     // C++11 [expr.log.and]p1:
14039     //  [...] the second operand is not evaluated if the first operand is false.
14040     bool EvalResult = false;
14041     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14042     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14043     if (ShouldVisitRHS) {
14044       Region = RHSRegion;
14045       Visit(BO->getRHS());
14046     }
14047 
14048     Region = OldRegion;
14049     Tree.merge(LHSRegion);
14050     Tree.merge(RHSRegion);
14051   }
14052 
VisitAbstractConditionalOperator(const AbstractConditionalOperator * CO)14053   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14054     // C++11 [expr.cond]p1:
14055     //  [...] Every value computation and side effect associated with the first
14056     //  expression is sequenced before every value computation and side effect
14057     //  associated with the second or third expression.
14058     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14059 
14060     // No sequencing is specified between the true and false expression.
14061     // However since exactly one of both is going to be evaluated we can
14062     // consider them to be sequenced. This is needed to avoid warning on
14063     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14064     // both the true and false expressions because we can't evaluate x.
14065     // This will still allow us to detect an expression like (pre C++17)
14066     // "(x ? y += 1 : y += 2) = y".
14067     //
14068     // We don't wrap the visitation of the true and false expression with
14069     // SequencedSubexpression because we don't want to downgrade modifications
14070     // as side effect in the true and false expressions after the visition
14071     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14072     // not warn between the two "y++", but we should warn between the "y++"
14073     // and the "y".
14074     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14075     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14076     SequenceTree::Seq OldRegion = Region;
14077 
14078     EvaluationTracker Eval(*this);
14079     {
14080       SequencedSubexpression Sequenced(*this);
14081       Region = ConditionRegion;
14082       Visit(CO->getCond());
14083     }
14084 
14085     // C++11 [expr.cond]p1:
14086     // [...] The first expression is contextually converted to bool (Clause 4).
14087     // It is evaluated and if it is true, the result of the conditional
14088     // expression is the value of the second expression, otherwise that of the
14089     // third expression. Only one of the second and third expressions is
14090     // evaluated. [...]
14091     bool EvalResult = false;
14092     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14093     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14094     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14095     if (ShouldVisitTrueExpr) {
14096       Region = TrueRegion;
14097       Visit(CO->getTrueExpr());
14098     }
14099     if (ShouldVisitFalseExpr) {
14100       Region = FalseRegion;
14101       Visit(CO->getFalseExpr());
14102     }
14103 
14104     Region = OldRegion;
14105     Tree.merge(ConditionRegion);
14106     Tree.merge(TrueRegion);
14107     Tree.merge(FalseRegion);
14108   }
14109 
VisitCallExpr(const CallExpr * CE)14110   void VisitCallExpr(const CallExpr *CE) {
14111     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14112 
14113     if (CE->isUnevaluatedBuiltinCall(Context))
14114       return;
14115 
14116     // C++11 [intro.execution]p15:
14117     //   When calling a function [...], every value computation and side effect
14118     //   associated with any argument expression, or with the postfix expression
14119     //   designating the called function, is sequenced before execution of every
14120     //   expression or statement in the body of the function [and thus before
14121     //   the value computation of its result].
14122     SequencedSubexpression Sequenced(*this);
14123     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14124       // C++17 [expr.call]p5
14125       //   The postfix-expression is sequenced before each expression in the
14126       //   expression-list and any default argument. [...]
14127       SequenceTree::Seq CalleeRegion;
14128       SequenceTree::Seq OtherRegion;
14129       if (SemaRef.getLangOpts().CPlusPlus17) {
14130         CalleeRegion = Tree.allocate(Region);
14131         OtherRegion = Tree.allocate(Region);
14132       } else {
14133         CalleeRegion = Region;
14134         OtherRegion = Region;
14135       }
14136       SequenceTree::Seq OldRegion = Region;
14137 
14138       // Visit the callee expression first.
14139       Region = CalleeRegion;
14140       if (SemaRef.getLangOpts().CPlusPlus17) {
14141         SequencedSubexpression Sequenced(*this);
14142         Visit(CE->getCallee());
14143       } else {
14144         Visit(CE->getCallee());
14145       }
14146 
14147       // Then visit the argument expressions.
14148       Region = OtherRegion;
14149       for (const Expr *Argument : CE->arguments())
14150         Visit(Argument);
14151 
14152       Region = OldRegion;
14153       if (SemaRef.getLangOpts().CPlusPlus17) {
14154         Tree.merge(CalleeRegion);
14155         Tree.merge(OtherRegion);
14156       }
14157     });
14158   }
14159 
VisitCXXOperatorCallExpr(const CXXOperatorCallExpr * CXXOCE)14160   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14161     // C++17 [over.match.oper]p2:
14162     //   [...] the operator notation is first transformed to the equivalent
14163     //   function-call notation as summarized in Table 12 (where @ denotes one
14164     //   of the operators covered in the specified subclause). However, the
14165     //   operands are sequenced in the order prescribed for the built-in
14166     //   operator (Clause 8).
14167     //
14168     // From the above only overloaded binary operators and overloaded call
14169     // operators have sequencing rules in C++17 that we need to handle
14170     // separately.
14171     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14172         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14173       return VisitCallExpr(CXXOCE);
14174 
14175     enum {
14176       NoSequencing,
14177       LHSBeforeRHS,
14178       RHSBeforeLHS,
14179       LHSBeforeRest
14180     } SequencingKind;
14181     switch (CXXOCE->getOperator()) {
14182     case OO_Equal:
14183     case OO_PlusEqual:
14184     case OO_MinusEqual:
14185     case OO_StarEqual:
14186     case OO_SlashEqual:
14187     case OO_PercentEqual:
14188     case OO_CaretEqual:
14189     case OO_AmpEqual:
14190     case OO_PipeEqual:
14191     case OO_LessLessEqual:
14192     case OO_GreaterGreaterEqual:
14193       SequencingKind = RHSBeforeLHS;
14194       break;
14195 
14196     case OO_LessLess:
14197     case OO_GreaterGreater:
14198     case OO_AmpAmp:
14199     case OO_PipePipe:
14200     case OO_Comma:
14201     case OO_ArrowStar:
14202     case OO_Subscript:
14203       SequencingKind = LHSBeforeRHS;
14204       break;
14205 
14206     case OO_Call:
14207       SequencingKind = LHSBeforeRest;
14208       break;
14209 
14210     default:
14211       SequencingKind = NoSequencing;
14212       break;
14213     }
14214 
14215     if (SequencingKind == NoSequencing)
14216       return VisitCallExpr(CXXOCE);
14217 
14218     // This is a call, so all subexpressions are sequenced before the result.
14219     SequencedSubexpression Sequenced(*this);
14220 
14221     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14222       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14223              "Should only get there with C++17 and above!");
14224       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14225              "Should only get there with an overloaded binary operator"
14226              " or an overloaded call operator!");
14227 
14228       if (SequencingKind == LHSBeforeRest) {
14229         assert(CXXOCE->getOperator() == OO_Call &&
14230                "We should only have an overloaded call operator here!");
14231 
14232         // This is very similar to VisitCallExpr, except that we only have the
14233         // C++17 case. The postfix-expression is the first argument of the
14234         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14235         // are in the following arguments.
14236         //
14237         // Note that we intentionally do not visit the callee expression since
14238         // it is just a decayed reference to a function.
14239         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14240         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14241         SequenceTree::Seq OldRegion = Region;
14242 
14243         assert(CXXOCE->getNumArgs() >= 1 &&
14244                "An overloaded call operator must have at least one argument"
14245                " for the postfix-expression!");
14246         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14247         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14248                                           CXXOCE->getNumArgs() - 1);
14249 
14250         // Visit the postfix-expression first.
14251         {
14252           Region = PostfixExprRegion;
14253           SequencedSubexpression Sequenced(*this);
14254           Visit(PostfixExpr);
14255         }
14256 
14257         // Then visit the argument expressions.
14258         Region = ArgsRegion;
14259         for (const Expr *Arg : Args)
14260           Visit(Arg);
14261 
14262         Region = OldRegion;
14263         Tree.merge(PostfixExprRegion);
14264         Tree.merge(ArgsRegion);
14265       } else {
14266         assert(CXXOCE->getNumArgs() == 2 &&
14267                "Should only have two arguments here!");
14268         assert((SequencingKind == LHSBeforeRHS ||
14269                 SequencingKind == RHSBeforeLHS) &&
14270                "Unexpected sequencing kind!");
14271 
14272         // We do not visit the callee expression since it is just a decayed
14273         // reference to a function.
14274         const Expr *E1 = CXXOCE->getArg(0);
14275         const Expr *E2 = CXXOCE->getArg(1);
14276         if (SequencingKind == RHSBeforeLHS)
14277           std::swap(E1, E2);
14278 
14279         return VisitSequencedExpressions(E1, E2);
14280       }
14281     });
14282   }
14283 
VisitCXXConstructExpr(const CXXConstructExpr * CCE)14284   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14285     // This is a call, so all subexpressions are sequenced before the result.
14286     SequencedSubexpression Sequenced(*this);
14287 
14288     if (!CCE->isListInitialization())
14289       return VisitExpr(CCE);
14290 
14291     // In C++11, list initializations are sequenced.
14292     SmallVector<SequenceTree::Seq, 32> Elts;
14293     SequenceTree::Seq Parent = Region;
14294     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14295                                               E = CCE->arg_end();
14296          I != E; ++I) {
14297       Region = Tree.allocate(Parent);
14298       Elts.push_back(Region);
14299       Visit(*I);
14300     }
14301 
14302     // Forget that the initializers are sequenced.
14303     Region = Parent;
14304     for (unsigned I = 0; I < Elts.size(); ++I)
14305       Tree.merge(Elts[I]);
14306   }
14307 
VisitInitListExpr(const InitListExpr * ILE)14308   void VisitInitListExpr(const InitListExpr *ILE) {
14309     if (!SemaRef.getLangOpts().CPlusPlus11)
14310       return VisitExpr(ILE);
14311 
14312     // In C++11, list initializations are sequenced.
14313     SmallVector<SequenceTree::Seq, 32> Elts;
14314     SequenceTree::Seq Parent = Region;
14315     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14316       const Expr *E = ILE->getInit(I);
14317       if (!E)
14318         continue;
14319       Region = Tree.allocate(Parent);
14320       Elts.push_back(Region);
14321       Visit(E);
14322     }
14323 
14324     // Forget that the initializers are sequenced.
14325     Region = Parent;
14326     for (unsigned I = 0; I < Elts.size(); ++I)
14327       Tree.merge(Elts[I]);
14328   }
14329 };
14330 
14331 } // namespace
14332 
CheckUnsequencedOperations(const Expr * E)14333 void Sema::CheckUnsequencedOperations(const Expr *E) {
14334   SmallVector<const Expr *, 8> WorkList;
14335   WorkList.push_back(E);
14336   while (!WorkList.empty()) {
14337     const Expr *Item = WorkList.pop_back_val();
14338     SequenceChecker(*this, Item, WorkList);
14339   }
14340 }
14341 
CheckCompletedExpr(Expr * E,SourceLocation CheckLoc,bool IsConstexpr)14342 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14343                               bool IsConstexpr) {
14344   llvm::SaveAndRestore<bool> ConstantContext(
14345       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14346   CheckImplicitConversions(E, CheckLoc);
14347   if (!E->isInstantiationDependent())
14348     CheckUnsequencedOperations(E);
14349   if (!IsConstexpr && !E->isValueDependent())
14350     CheckForIntOverflow(E);
14351   DiagnoseMisalignedMembers();
14352 }
14353 
CheckBitFieldInitialization(SourceLocation InitLoc,FieldDecl * BitField,Expr * Init)14354 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14355                                        FieldDecl *BitField,
14356                                        Expr *Init) {
14357   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14358 }
14359 
diagnoseArrayStarInParamType(Sema & S,QualType PType,SourceLocation Loc)14360 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14361                                          SourceLocation Loc) {
14362   if (!PType->isVariablyModifiedType())
14363     return;
14364   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14365     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14366     return;
14367   }
14368   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14369     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14370     return;
14371   }
14372   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14373     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14374     return;
14375   }
14376 
14377   const ArrayType *AT = S.Context.getAsArrayType(PType);
14378   if (!AT)
14379     return;
14380 
14381   if (AT->getSizeModifier() != ArrayType::Star) {
14382     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14383     return;
14384   }
14385 
14386   S.Diag(Loc, diag::err_array_star_in_function_definition);
14387 }
14388 
14389 /// CheckParmsForFunctionDef - Check that the parameters of the given
14390 /// function are appropriate for the definition of a function. This
14391 /// takes care of any checks that cannot be performed on the
14392 /// declaration itself, e.g., that the types of each of the function
14393 /// parameters are complete.
CheckParmsForFunctionDef(ArrayRef<ParmVarDecl * > Parameters,bool CheckParameterNames)14394 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14395                                     bool CheckParameterNames) {
14396   bool HasInvalidParm = false;
14397   for (ParmVarDecl *Param : Parameters) {
14398     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14399     // function declarator that is part of a function definition of
14400     // that function shall not have incomplete type.
14401     //
14402     // This is also C++ [dcl.fct]p6.
14403     if (!Param->isInvalidDecl() &&
14404         RequireCompleteType(Param->getLocation(), Param->getType(),
14405                             diag::err_typecheck_decl_incomplete_type)) {
14406       Param->setInvalidDecl();
14407       HasInvalidParm = true;
14408     }
14409 
14410     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14411     // declaration of each parameter shall include an identifier.
14412     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14413         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14414       // Diagnose this as an extension in C17 and earlier.
14415       if (!getLangOpts().C2x)
14416         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14417     }
14418 
14419     // C99 6.7.5.3p12:
14420     //   If the function declarator is not part of a definition of that
14421     //   function, parameters may have incomplete type and may use the [*]
14422     //   notation in their sequences of declarator specifiers to specify
14423     //   variable length array types.
14424     QualType PType = Param->getOriginalType();
14425     // FIXME: This diagnostic should point the '[*]' if source-location
14426     // information is added for it.
14427     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14428 
14429     // If the parameter is a c++ class type and it has to be destructed in the
14430     // callee function, declare the destructor so that it can be called by the
14431     // callee function. Do not perform any direct access check on the dtor here.
14432     if (!Param->isInvalidDecl()) {
14433       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14434         if (!ClassDecl->isInvalidDecl() &&
14435             !ClassDecl->hasIrrelevantDestructor() &&
14436             !ClassDecl->isDependentContext() &&
14437             ClassDecl->isParamDestroyedInCallee()) {
14438           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14439           MarkFunctionReferenced(Param->getLocation(), Destructor);
14440           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14441         }
14442       }
14443     }
14444 
14445     // Parameters with the pass_object_size attribute only need to be marked
14446     // constant at function definitions. Because we lack information about
14447     // whether we're on a declaration or definition when we're instantiating the
14448     // attribute, we need to check for constness here.
14449     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14450       if (!Param->getType().isConstQualified())
14451         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14452             << Attr->getSpelling() << 1;
14453 
14454     // Check for parameter names shadowing fields from the class.
14455     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14456       // The owning context for the parameter should be the function, but we
14457       // want to see if this function's declaration context is a record.
14458       DeclContext *DC = Param->getDeclContext();
14459       if (DC && DC->isFunctionOrMethod()) {
14460         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14461           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14462                                      RD, /*DeclIsField*/ false);
14463       }
14464     }
14465   }
14466 
14467   return HasInvalidParm;
14468 }
14469 
14470 Optional<std::pair<CharUnits, CharUnits>>
14471 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14472 
14473 /// Compute the alignment and offset of the base class object given the
14474 /// derived-to-base cast expression and the alignment and offset of the derived
14475 /// class object.
14476 static std::pair<CharUnits, CharUnits>
getDerivedToBaseAlignmentAndOffset(const CastExpr * CE,QualType DerivedType,CharUnits BaseAlignment,CharUnits Offset,ASTContext & Ctx)14477 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14478                                    CharUnits BaseAlignment, CharUnits Offset,
14479                                    ASTContext &Ctx) {
14480   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14481        ++PathI) {
14482     const CXXBaseSpecifier *Base = *PathI;
14483     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14484     if (Base->isVirtual()) {
14485       // The complete object may have a lower alignment than the non-virtual
14486       // alignment of the base, in which case the base may be misaligned. Choose
14487       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14488       // conservative lower bound of the complete object alignment.
14489       CharUnits NonVirtualAlignment =
14490           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14491       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14492       Offset = CharUnits::Zero();
14493     } else {
14494       const ASTRecordLayout &RL =
14495           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14496       Offset += RL.getBaseClassOffset(BaseDecl);
14497     }
14498     DerivedType = Base->getType();
14499   }
14500 
14501   return std::make_pair(BaseAlignment, Offset);
14502 }
14503 
14504 /// Compute the alignment and offset of a binary additive operator.
14505 static Optional<std::pair<CharUnits, CharUnits>>
getAlignmentAndOffsetFromBinAddOrSub(const Expr * PtrE,const Expr * IntE,bool IsSub,ASTContext & Ctx)14506 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14507                                      bool IsSub, ASTContext &Ctx) {
14508   QualType PointeeType = PtrE->getType()->getPointeeType();
14509 
14510   if (!PointeeType->isConstantSizeType())
14511     return llvm::None;
14512 
14513   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14514 
14515   if (!P)
14516     return llvm::None;
14517 
14518   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14519   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14520     CharUnits Offset = EltSize * IdxRes->getExtValue();
14521     if (IsSub)
14522       Offset = -Offset;
14523     return std::make_pair(P->first, P->second + Offset);
14524   }
14525 
14526   // If the integer expression isn't a constant expression, compute the lower
14527   // bound of the alignment using the alignment and offset of the pointer
14528   // expression and the element size.
14529   return std::make_pair(
14530       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14531       CharUnits::Zero());
14532 }
14533 
14534 /// This helper function takes an lvalue expression and returns the alignment of
14535 /// a VarDecl and a constant offset from the VarDecl.
14536 Optional<std::pair<CharUnits, CharUnits>>
getBaseAlignmentAndOffsetFromLValue(const Expr * E,ASTContext & Ctx)14537 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14538   E = E->IgnoreParens();
14539   switch (E->getStmtClass()) {
14540   default:
14541     break;
14542   case Stmt::CStyleCastExprClass:
14543   case Stmt::CXXStaticCastExprClass:
14544   case Stmt::ImplicitCastExprClass: {
14545     auto *CE = cast<CastExpr>(E);
14546     const Expr *From = CE->getSubExpr();
14547     switch (CE->getCastKind()) {
14548     default:
14549       break;
14550     case CK_NoOp:
14551       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14552     case CK_UncheckedDerivedToBase:
14553     case CK_DerivedToBase: {
14554       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14555       if (!P)
14556         break;
14557       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14558                                                 P->second, Ctx);
14559     }
14560     }
14561     break;
14562   }
14563   case Stmt::ArraySubscriptExprClass: {
14564     auto *ASE = cast<ArraySubscriptExpr>(E);
14565     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14566                                                 false, Ctx);
14567   }
14568   case Stmt::DeclRefExprClass: {
14569     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14570       // FIXME: If VD is captured by copy or is an escaping __block variable,
14571       // use the alignment of VD's type.
14572       if (!VD->getType()->isReferenceType())
14573         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14574       if (VD->hasInit())
14575         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14576     }
14577     break;
14578   }
14579   case Stmt::MemberExprClass: {
14580     auto *ME = cast<MemberExpr>(E);
14581     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14582     if (!FD || FD->getType()->isReferenceType() ||
14583         FD->getParent()->isInvalidDecl())
14584       break;
14585     Optional<std::pair<CharUnits, CharUnits>> P;
14586     if (ME->isArrow())
14587       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14588     else
14589       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14590     if (!P)
14591       break;
14592     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14593     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14594     return std::make_pair(P->first,
14595                           P->second + CharUnits::fromQuantity(Offset));
14596   }
14597   case Stmt::UnaryOperatorClass: {
14598     auto *UO = cast<UnaryOperator>(E);
14599     switch (UO->getOpcode()) {
14600     default:
14601       break;
14602     case UO_Deref:
14603       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14604     }
14605     break;
14606   }
14607   case Stmt::BinaryOperatorClass: {
14608     auto *BO = cast<BinaryOperator>(E);
14609     auto Opcode = BO->getOpcode();
14610     switch (Opcode) {
14611     default:
14612       break;
14613     case BO_Comma:
14614       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14615     }
14616     break;
14617   }
14618   }
14619   return llvm::None;
14620 }
14621 
14622 /// This helper function takes a pointer expression and returns the alignment of
14623 /// a VarDecl and a constant offset from the VarDecl.
14624 Optional<std::pair<CharUnits, CharUnits>>
getBaseAlignmentAndOffsetFromPtr(const Expr * E,ASTContext & Ctx)14625 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14626   E = E->IgnoreParens();
14627   switch (E->getStmtClass()) {
14628   default:
14629     break;
14630   case Stmt::CStyleCastExprClass:
14631   case Stmt::CXXStaticCastExprClass:
14632   case Stmt::ImplicitCastExprClass: {
14633     auto *CE = cast<CastExpr>(E);
14634     const Expr *From = CE->getSubExpr();
14635     switch (CE->getCastKind()) {
14636     default:
14637       break;
14638     case CK_NoOp:
14639       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14640     case CK_ArrayToPointerDecay:
14641       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14642     case CK_UncheckedDerivedToBase:
14643     case CK_DerivedToBase: {
14644       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14645       if (!P)
14646         break;
14647       return getDerivedToBaseAlignmentAndOffset(
14648           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14649     }
14650     }
14651     break;
14652   }
14653   case Stmt::CXXThisExprClass: {
14654     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14655     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14656     return std::make_pair(Alignment, CharUnits::Zero());
14657   }
14658   case Stmt::UnaryOperatorClass: {
14659     auto *UO = cast<UnaryOperator>(E);
14660     if (UO->getOpcode() == UO_AddrOf)
14661       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14662     break;
14663   }
14664   case Stmt::BinaryOperatorClass: {
14665     auto *BO = cast<BinaryOperator>(E);
14666     auto Opcode = BO->getOpcode();
14667     switch (Opcode) {
14668     default:
14669       break;
14670     case BO_Add:
14671     case BO_Sub: {
14672       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14673       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14674         std::swap(LHS, RHS);
14675       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14676                                                   Ctx);
14677     }
14678     case BO_Comma:
14679       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14680     }
14681     break;
14682   }
14683   }
14684   return llvm::None;
14685 }
14686 
getPresumedAlignmentOfPointer(const Expr * E,Sema & S)14687 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14688   // See if we can compute the alignment of a VarDecl and an offset from it.
14689   Optional<std::pair<CharUnits, CharUnits>> P =
14690       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14691 
14692   if (P)
14693     return P->first.alignmentAtOffset(P->second);
14694 
14695   // If that failed, return the type's alignment.
14696   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14697 }
14698 
14699 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14700 /// pointer cast increases the alignment requirements.
CheckCastAlign(Expr * Op,QualType T,SourceRange TRange)14701 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14702   // This is actually a lot of work to potentially be doing on every
14703   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14704   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14705     return;
14706 
14707   // Ignore dependent types.
14708   if (T->isDependentType() || Op->getType()->isDependentType())
14709     return;
14710 
14711   // Require that the destination be a pointer type.
14712   const PointerType *DestPtr = T->getAs<PointerType>();
14713   if (!DestPtr) return;
14714 
14715   // If the destination has alignment 1, we're done.
14716   QualType DestPointee = DestPtr->getPointeeType();
14717   if (DestPointee->isIncompleteType()) return;
14718   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14719   if (DestAlign.isOne()) return;
14720 
14721   // Require that the source be a pointer type.
14722   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14723   if (!SrcPtr) return;
14724   QualType SrcPointee = SrcPtr->getPointeeType();
14725 
14726   // Explicitly allow casts from cv void*.  We already implicitly
14727   // allowed casts to cv void*, since they have alignment 1.
14728   // Also allow casts involving incomplete types, which implicitly
14729   // includes 'void'.
14730   if (SrcPointee->isIncompleteType()) return;
14731 
14732   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14733 
14734   if (SrcAlign >= DestAlign) return;
14735 
14736   Diag(TRange.getBegin(), diag::warn_cast_align)
14737     << Op->getType() << T
14738     << static_cast<unsigned>(SrcAlign.getQuantity())
14739     << static_cast<unsigned>(DestAlign.getQuantity())
14740     << TRange << Op->getSourceRange();
14741 }
14742 
14743 /// Check whether this array fits the idiom of a size-one tail padded
14744 /// array member of a struct.
14745 ///
14746 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14747 /// commonly used to emulate flexible arrays in C89 code.
IsTailPaddedMemberArray(Sema & S,const llvm::APInt & Size,const NamedDecl * ND)14748 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14749                                     const NamedDecl *ND) {
14750   if (Size != 1 || !ND) return false;
14751 
14752   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14753   if (!FD) return false;
14754 
14755   // Don't consider sizes resulting from macro expansions or template argument
14756   // substitution to form C89 tail-padded arrays.
14757 
14758   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14759   while (TInfo) {
14760     TypeLoc TL = TInfo->getTypeLoc();
14761     // Look through typedefs.
14762     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14763       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14764       TInfo = TDL->getTypeSourceInfo();
14765       continue;
14766     }
14767     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14768       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14769       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14770         return false;
14771     }
14772     break;
14773   }
14774 
14775   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14776   if (!RD) return false;
14777   if (RD->isUnion()) return false;
14778   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14779     if (!CRD->isStandardLayout()) return false;
14780   }
14781 
14782   // See if this is the last field decl in the record.
14783   const Decl *D = FD;
14784   while ((D = D->getNextDeclInContext()))
14785     if (isa<FieldDecl>(D))
14786       return false;
14787   return true;
14788 }
14789 
CheckArrayAccess(const Expr * BaseExpr,const Expr * IndexExpr,const ArraySubscriptExpr * ASE,bool AllowOnePastEnd,bool IndexNegated)14790 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14791                             const ArraySubscriptExpr *ASE,
14792                             bool AllowOnePastEnd, bool IndexNegated) {
14793   // Already diagnosed by the constant evaluator.
14794   if (isConstantEvaluated())
14795     return;
14796 
14797   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14798   if (IndexExpr->isValueDependent())
14799     return;
14800 
14801   const Type *EffectiveType =
14802       BaseExpr->getType()->getPointeeOrArrayElementType();
14803   BaseExpr = BaseExpr->IgnoreParenCasts();
14804   const ConstantArrayType *ArrayTy =
14805       Context.getAsConstantArrayType(BaseExpr->getType());
14806 
14807   const Type *BaseType =
14808       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14809   bool IsUnboundedArray = (BaseType == nullptr);
14810   if (EffectiveType->isDependentType() ||
14811       (!IsUnboundedArray && BaseType->isDependentType()))
14812     return;
14813 
14814   Expr::EvalResult Result;
14815   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14816     return;
14817 
14818   llvm::APSInt index = Result.Val.getInt();
14819   if (IndexNegated) {
14820     index.setIsUnsigned(false);
14821     index = -index;
14822   }
14823 
14824   const NamedDecl *ND = nullptr;
14825   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14826     ND = DRE->getDecl();
14827   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14828     ND = ME->getMemberDecl();
14829 
14830   if (IsUnboundedArray) {
14831     if (index.isUnsigned() || !index.isNegative()) {
14832       const auto &ASTC = getASTContext();
14833       unsigned AddrBits =
14834           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14835               EffectiveType->getCanonicalTypeInternal()));
14836       if (index.getBitWidth() < AddrBits)
14837         index = index.zext(AddrBits);
14838       Optional<CharUnits> ElemCharUnits =
14839           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14840       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14841       // pointer) bounds-checking isn't meaningful.
14842       if (!ElemCharUnits)
14843         return;
14844       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14845       // If index has more active bits than address space, we already know
14846       // we have a bounds violation to warn about.  Otherwise, compute
14847       // address of (index + 1)th element, and warn about bounds violation
14848       // only if that address exceeds address space.
14849       if (index.getActiveBits() <= AddrBits) {
14850         bool Overflow;
14851         llvm::APInt Product(index);
14852         Product += 1;
14853         Product = Product.umul_ov(ElemBytes, Overflow);
14854         if (!Overflow && Product.getActiveBits() <= AddrBits)
14855           return;
14856       }
14857 
14858       // Need to compute max possible elements in address space, since that
14859       // is included in diag message.
14860       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14861       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14862       MaxElems += 1;
14863       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14864       MaxElems = MaxElems.udiv(ElemBytes);
14865 
14866       unsigned DiagID =
14867           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14868               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14869 
14870       // Diag message shows element size in bits and in "bytes" (platform-
14871       // dependent CharUnits)
14872       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14873                           PDiag(DiagID)
14874                               << toString(index, 10, true) << AddrBits
14875                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14876                               << toString(ElemBytes, 10, false)
14877                               << toString(MaxElems, 10, false)
14878                               << (unsigned)MaxElems.getLimitedValue(~0U)
14879                               << IndexExpr->getSourceRange());
14880 
14881       if (!ND) {
14882         // Try harder to find a NamedDecl to point at in the note.
14883         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14884           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14885         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14886           ND = DRE->getDecl();
14887         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14888           ND = ME->getMemberDecl();
14889       }
14890 
14891       if (ND)
14892         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14893                             PDiag(diag::note_array_declared_here) << ND);
14894     }
14895     return;
14896   }
14897 
14898   if (index.isUnsigned() || !index.isNegative()) {
14899     // It is possible that the type of the base expression after
14900     // IgnoreParenCasts is incomplete, even though the type of the base
14901     // expression before IgnoreParenCasts is complete (see PR39746 for an
14902     // example). In this case we have no information about whether the array
14903     // access exceeds the array bounds. However we can still diagnose an array
14904     // access which precedes the array bounds.
14905     if (BaseType->isIncompleteType())
14906       return;
14907 
14908     llvm::APInt size = ArrayTy->getSize();
14909     if (!size.isStrictlyPositive())
14910       return;
14911 
14912     if (BaseType != EffectiveType) {
14913       // Make sure we're comparing apples to apples when comparing index to size
14914       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14915       uint64_t array_typesize = Context.getTypeSize(BaseType);
14916       // Handle ptrarith_typesize being zero, such as when casting to void*
14917       if (!ptrarith_typesize) ptrarith_typesize = 1;
14918       if (ptrarith_typesize != array_typesize) {
14919         // There's a cast to a different size type involved
14920         uint64_t ratio = array_typesize / ptrarith_typesize;
14921         // TODO: Be smarter about handling cases where array_typesize is not a
14922         // multiple of ptrarith_typesize
14923         if (ptrarith_typesize * ratio == array_typesize)
14924           size *= llvm::APInt(size.getBitWidth(), ratio);
14925       }
14926     }
14927 
14928     if (size.getBitWidth() > index.getBitWidth())
14929       index = index.zext(size.getBitWidth());
14930     else if (size.getBitWidth() < index.getBitWidth())
14931       size = size.zext(index.getBitWidth());
14932 
14933     // For array subscripting the index must be less than size, but for pointer
14934     // arithmetic also allow the index (offset) to be equal to size since
14935     // computing the next address after the end of the array is legal and
14936     // commonly done e.g. in C++ iterators and range-based for loops.
14937     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14938       return;
14939 
14940     // Also don't warn for arrays of size 1 which are members of some
14941     // structure. These are often used to approximate flexible arrays in C89
14942     // code.
14943     if (IsTailPaddedMemberArray(*this, size, ND))
14944       return;
14945 
14946     // Suppress the warning if the subscript expression (as identified by the
14947     // ']' location) and the index expression are both from macro expansions
14948     // within a system header.
14949     if (ASE) {
14950       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14951           ASE->getRBracketLoc());
14952       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14953         SourceLocation IndexLoc =
14954             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14955         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14956           return;
14957       }
14958     }
14959 
14960     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14961                           : diag::warn_ptr_arith_exceeds_bounds;
14962 
14963     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14964                         PDiag(DiagID) << toString(index, 10, true)
14965                                       << toString(size, 10, true)
14966                                       << (unsigned)size.getLimitedValue(~0U)
14967                                       << IndexExpr->getSourceRange());
14968   } else {
14969     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14970     if (!ASE) {
14971       DiagID = diag::warn_ptr_arith_precedes_bounds;
14972       if (index.isNegative()) index = -index;
14973     }
14974 
14975     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14976                         PDiag(DiagID) << toString(index, 10, true)
14977                                       << IndexExpr->getSourceRange());
14978   }
14979 
14980   if (!ND) {
14981     // Try harder to find a NamedDecl to point at in the note.
14982     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14983       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14984     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14985       ND = DRE->getDecl();
14986     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14987       ND = ME->getMemberDecl();
14988   }
14989 
14990   if (ND)
14991     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14992                         PDiag(diag::note_array_declared_here) << ND);
14993 }
14994 
CheckArrayAccess(const Expr * expr)14995 void Sema::CheckArrayAccess(const Expr *expr) {
14996   int AllowOnePastEnd = 0;
14997   while (expr) {
14998     expr = expr->IgnoreParenImpCasts();
14999     switch (expr->getStmtClass()) {
15000       case Stmt::ArraySubscriptExprClass: {
15001         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15002         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15003                          AllowOnePastEnd > 0);
15004         expr = ASE->getBase();
15005         break;
15006       }
15007       case Stmt::MemberExprClass: {
15008         expr = cast<MemberExpr>(expr)->getBase();
15009         break;
15010       }
15011       case Stmt::OMPArraySectionExprClass: {
15012         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15013         if (ASE->getLowerBound())
15014           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15015                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15016         return;
15017       }
15018       case Stmt::UnaryOperatorClass: {
15019         // Only unwrap the * and & unary operators
15020         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15021         expr = UO->getSubExpr();
15022         switch (UO->getOpcode()) {
15023           case UO_AddrOf:
15024             AllowOnePastEnd++;
15025             break;
15026           case UO_Deref:
15027             AllowOnePastEnd--;
15028             break;
15029           default:
15030             return;
15031         }
15032         break;
15033       }
15034       case Stmt::ConditionalOperatorClass: {
15035         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15036         if (const Expr *lhs = cond->getLHS())
15037           CheckArrayAccess(lhs);
15038         if (const Expr *rhs = cond->getRHS())
15039           CheckArrayAccess(rhs);
15040         return;
15041       }
15042       case Stmt::CXXOperatorCallExprClass: {
15043         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15044         for (const auto *Arg : OCE->arguments())
15045           CheckArrayAccess(Arg);
15046         return;
15047       }
15048       default:
15049         return;
15050     }
15051   }
15052 }
15053 
15054 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15055 
15056 namespace {
15057 
15058 struct RetainCycleOwner {
15059   VarDecl *Variable = nullptr;
15060   SourceRange Range;
15061   SourceLocation Loc;
15062   bool Indirect = false;
15063 
15064   RetainCycleOwner() = default;
15065 
setLocsFrom__anona96a15882311::RetainCycleOwner15066   void setLocsFrom(Expr *e) {
15067     Loc = e->getExprLoc();
15068     Range = e->getSourceRange();
15069   }
15070 };
15071 
15072 } // namespace
15073 
15074 /// Consider whether capturing the given variable can possibly lead to
15075 /// a retain cycle.
considerVariable(VarDecl * var,Expr * ref,RetainCycleOwner & owner)15076 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15077   // In ARC, it's captured strongly iff the variable has __strong
15078   // lifetime.  In MRR, it's captured strongly if the variable is
15079   // __block and has an appropriate type.
15080   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15081     return false;
15082 
15083   owner.Variable = var;
15084   if (ref)
15085     owner.setLocsFrom(ref);
15086   return true;
15087 }
15088 
findRetainCycleOwner(Sema & S,Expr * e,RetainCycleOwner & owner)15089 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15090   while (true) {
15091     e = e->IgnoreParens();
15092     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15093       switch (cast->getCastKind()) {
15094       case CK_BitCast:
15095       case CK_LValueBitCast:
15096       case CK_LValueToRValue:
15097       case CK_ARCReclaimReturnedObject:
15098         e = cast->getSubExpr();
15099         continue;
15100 
15101       default:
15102         return false;
15103       }
15104     }
15105 
15106     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15107       ObjCIvarDecl *ivar = ref->getDecl();
15108       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15109         return false;
15110 
15111       // Try to find a retain cycle in the base.
15112       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15113         return false;
15114 
15115       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15116       owner.Indirect = true;
15117       return true;
15118     }
15119 
15120     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15121       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15122       if (!var) return false;
15123       return considerVariable(var, ref, owner);
15124     }
15125 
15126     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15127       if (member->isArrow()) return false;
15128 
15129       // Don't count this as an indirect ownership.
15130       e = member->getBase();
15131       continue;
15132     }
15133 
15134     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15135       // Only pay attention to pseudo-objects on property references.
15136       ObjCPropertyRefExpr *pre
15137         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15138                                               ->IgnoreParens());
15139       if (!pre) return false;
15140       if (pre->isImplicitProperty()) return false;
15141       ObjCPropertyDecl *property = pre->getExplicitProperty();
15142       if (!property->isRetaining() &&
15143           !(property->getPropertyIvarDecl() &&
15144             property->getPropertyIvarDecl()->getType()
15145               .getObjCLifetime() == Qualifiers::OCL_Strong))
15146           return false;
15147 
15148       owner.Indirect = true;
15149       if (pre->isSuperReceiver()) {
15150         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15151         if (!owner.Variable)
15152           return false;
15153         owner.Loc = pre->getLocation();
15154         owner.Range = pre->getSourceRange();
15155         return true;
15156       }
15157       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15158                               ->getSourceExpr());
15159       continue;
15160     }
15161 
15162     // Array ivars?
15163 
15164     return false;
15165   }
15166 }
15167 
15168 namespace {
15169 
15170   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15171     ASTContext &Context;
15172     VarDecl *Variable;
15173     Expr *Capturer = nullptr;
15174     bool VarWillBeReased = false;
15175 
FindCaptureVisitor__anona96a15882411::FindCaptureVisitor15176     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15177         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15178           Context(Context), Variable(variable) {}
15179 
VisitDeclRefExpr__anona96a15882411::FindCaptureVisitor15180     void VisitDeclRefExpr(DeclRefExpr *ref) {
15181       if (ref->getDecl() == Variable && !Capturer)
15182         Capturer = ref;
15183     }
15184 
VisitObjCIvarRefExpr__anona96a15882411::FindCaptureVisitor15185     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15186       if (Capturer) return;
15187       Visit(ref->getBase());
15188       if (Capturer && ref->isFreeIvar())
15189         Capturer = ref;
15190     }
15191 
VisitBlockExpr__anona96a15882411::FindCaptureVisitor15192     void VisitBlockExpr(BlockExpr *block) {
15193       // Look inside nested blocks
15194       if (block->getBlockDecl()->capturesVariable(Variable))
15195         Visit(block->getBlockDecl()->getBody());
15196     }
15197 
VisitOpaqueValueExpr__anona96a15882411::FindCaptureVisitor15198     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15199       if (Capturer) return;
15200       if (OVE->getSourceExpr())
15201         Visit(OVE->getSourceExpr());
15202     }
15203 
VisitBinaryOperator__anona96a15882411::FindCaptureVisitor15204     void VisitBinaryOperator(BinaryOperator *BinOp) {
15205       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15206         return;
15207       Expr *LHS = BinOp->getLHS();
15208       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15209         if (DRE->getDecl() != Variable)
15210           return;
15211         if (Expr *RHS = BinOp->getRHS()) {
15212           RHS = RHS->IgnoreParenCasts();
15213           Optional<llvm::APSInt> Value;
15214           VarWillBeReased =
15215               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15216                *Value == 0);
15217         }
15218       }
15219     }
15220   };
15221 
15222 } // namespace
15223 
15224 /// Check whether the given argument is a block which captures a
15225 /// variable.
findCapturingExpr(Sema & S,Expr * e,RetainCycleOwner & owner)15226 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15227   assert(owner.Variable && owner.Loc.isValid());
15228 
15229   e = e->IgnoreParenCasts();
15230 
15231   // Look through [^{...} copy] and Block_copy(^{...}).
15232   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15233     Selector Cmd = ME->getSelector();
15234     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15235       e = ME->getInstanceReceiver();
15236       if (!e)
15237         return nullptr;
15238       e = e->IgnoreParenCasts();
15239     }
15240   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15241     if (CE->getNumArgs() == 1) {
15242       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15243       if (Fn) {
15244         const IdentifierInfo *FnI = Fn->getIdentifier();
15245         if (FnI && FnI->isStr("_Block_copy")) {
15246           e = CE->getArg(0)->IgnoreParenCasts();
15247         }
15248       }
15249     }
15250   }
15251 
15252   BlockExpr *block = dyn_cast<BlockExpr>(e);
15253   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15254     return nullptr;
15255 
15256   FindCaptureVisitor visitor(S.Context, owner.Variable);
15257   visitor.Visit(block->getBlockDecl()->getBody());
15258   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15259 }
15260 
diagnoseRetainCycle(Sema & S,Expr * capturer,RetainCycleOwner & owner)15261 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15262                                 RetainCycleOwner &owner) {
15263   assert(capturer);
15264   assert(owner.Variable && owner.Loc.isValid());
15265 
15266   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15267     << owner.Variable << capturer->getSourceRange();
15268   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15269     << owner.Indirect << owner.Range;
15270 }
15271 
15272 /// Check for a keyword selector that starts with the word 'add' or
15273 /// 'set'.
isSetterLikeSelector(Selector sel)15274 static bool isSetterLikeSelector(Selector sel) {
15275   if (sel.isUnarySelector()) return false;
15276 
15277   StringRef str = sel.getNameForSlot(0);
15278   while (!str.empty() && str.front() == '_') str = str.substr(1);
15279   if (str.startswith("set"))
15280     str = str.substr(3);
15281   else if (str.startswith("add")) {
15282     // Specially allow 'addOperationWithBlock:'.
15283     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15284       return false;
15285     str = str.substr(3);
15286   }
15287   else
15288     return false;
15289 
15290   if (str.empty()) return true;
15291   return !isLowercase(str.front());
15292 }
15293 
GetNSMutableArrayArgumentIndex(Sema & S,ObjCMessageExpr * Message)15294 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15295                                                     ObjCMessageExpr *Message) {
15296   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15297                                                 Message->getReceiverInterface(),
15298                                                 NSAPI::ClassId_NSMutableArray);
15299   if (!IsMutableArray) {
15300     return None;
15301   }
15302 
15303   Selector Sel = Message->getSelector();
15304 
15305   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15306     S.NSAPIObj->getNSArrayMethodKind(Sel);
15307   if (!MKOpt) {
15308     return None;
15309   }
15310 
15311   NSAPI::NSArrayMethodKind MK = *MKOpt;
15312 
15313   switch (MK) {
15314     case NSAPI::NSMutableArr_addObject:
15315     case NSAPI::NSMutableArr_insertObjectAtIndex:
15316     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15317       return 0;
15318     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15319       return 1;
15320 
15321     default:
15322       return None;
15323   }
15324 
15325   return None;
15326 }
15327 
15328 static
GetNSMutableDictionaryArgumentIndex(Sema & S,ObjCMessageExpr * Message)15329 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15330                                                   ObjCMessageExpr *Message) {
15331   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15332                                             Message->getReceiverInterface(),
15333                                             NSAPI::ClassId_NSMutableDictionary);
15334   if (!IsMutableDictionary) {
15335     return None;
15336   }
15337 
15338   Selector Sel = Message->getSelector();
15339 
15340   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15341     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15342   if (!MKOpt) {
15343     return None;
15344   }
15345 
15346   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15347 
15348   switch (MK) {
15349     case NSAPI::NSMutableDict_setObjectForKey:
15350     case NSAPI::NSMutableDict_setValueForKey:
15351     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15352       return 0;
15353 
15354     default:
15355       return None;
15356   }
15357 
15358   return None;
15359 }
15360 
GetNSSetArgumentIndex(Sema & S,ObjCMessageExpr * Message)15361 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15362   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15363                                                 Message->getReceiverInterface(),
15364                                                 NSAPI::ClassId_NSMutableSet);
15365 
15366   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15367                                             Message->getReceiverInterface(),
15368                                             NSAPI::ClassId_NSMutableOrderedSet);
15369   if (!IsMutableSet && !IsMutableOrderedSet) {
15370     return None;
15371   }
15372 
15373   Selector Sel = Message->getSelector();
15374 
15375   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15376   if (!MKOpt) {
15377     return None;
15378   }
15379 
15380   NSAPI::NSSetMethodKind MK = *MKOpt;
15381 
15382   switch (MK) {
15383     case NSAPI::NSMutableSet_addObject:
15384     case NSAPI::NSOrderedSet_setObjectAtIndex:
15385     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15386     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15387       return 0;
15388     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15389       return 1;
15390   }
15391 
15392   return None;
15393 }
15394 
CheckObjCCircularContainer(ObjCMessageExpr * Message)15395 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15396   if (!Message->isInstanceMessage()) {
15397     return;
15398   }
15399 
15400   Optional<int> ArgOpt;
15401 
15402   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15403       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15404       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15405     return;
15406   }
15407 
15408   int ArgIndex = *ArgOpt;
15409 
15410   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15411   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15412     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15413   }
15414 
15415   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15416     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15417       if (ArgRE->isObjCSelfExpr()) {
15418         Diag(Message->getSourceRange().getBegin(),
15419              diag::warn_objc_circular_container)
15420           << ArgRE->getDecl() << StringRef("'super'");
15421       }
15422     }
15423   } else {
15424     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15425 
15426     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15427       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15428     }
15429 
15430     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15431       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15432         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15433           ValueDecl *Decl = ReceiverRE->getDecl();
15434           Diag(Message->getSourceRange().getBegin(),
15435                diag::warn_objc_circular_container)
15436             << Decl << Decl;
15437           if (!ArgRE->isObjCSelfExpr()) {
15438             Diag(Decl->getLocation(),
15439                  diag::note_objc_circular_container_declared_here)
15440               << Decl;
15441           }
15442         }
15443       }
15444     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15445       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15446         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15447           ObjCIvarDecl *Decl = IvarRE->getDecl();
15448           Diag(Message->getSourceRange().getBegin(),
15449                diag::warn_objc_circular_container)
15450             << Decl << Decl;
15451           Diag(Decl->getLocation(),
15452                diag::note_objc_circular_container_declared_here)
15453             << Decl;
15454         }
15455       }
15456     }
15457   }
15458 }
15459 
15460 /// Check a message send to see if it's likely to cause a retain cycle.
checkRetainCycles(ObjCMessageExpr * msg)15461 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15462   // Only check instance methods whose selector looks like a setter.
15463   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15464     return;
15465 
15466   // Try to find a variable that the receiver is strongly owned by.
15467   RetainCycleOwner owner;
15468   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15469     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15470       return;
15471   } else {
15472     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15473     owner.Variable = getCurMethodDecl()->getSelfDecl();
15474     owner.Loc = msg->getSuperLoc();
15475     owner.Range = msg->getSuperLoc();
15476   }
15477 
15478   // Check whether the receiver is captured by any of the arguments.
15479   const ObjCMethodDecl *MD = msg->getMethodDecl();
15480   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15481     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15482       // noescape blocks should not be retained by the method.
15483       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15484         continue;
15485       return diagnoseRetainCycle(*this, capturer, owner);
15486     }
15487   }
15488 }
15489 
15490 /// Check a property assign to see if it's likely to cause a retain cycle.
checkRetainCycles(Expr * receiver,Expr * argument)15491 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15492   RetainCycleOwner owner;
15493   if (!findRetainCycleOwner(*this, receiver, owner))
15494     return;
15495 
15496   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15497     diagnoseRetainCycle(*this, capturer, owner);
15498 }
15499 
checkRetainCycles(VarDecl * Var,Expr * Init)15500 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15501   RetainCycleOwner Owner;
15502   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15503     return;
15504 
15505   // Because we don't have an expression for the variable, we have to set the
15506   // location explicitly here.
15507   Owner.Loc = Var->getLocation();
15508   Owner.Range = Var->getSourceRange();
15509 
15510   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15511     diagnoseRetainCycle(*this, Capturer, Owner);
15512 }
15513 
checkUnsafeAssignLiteral(Sema & S,SourceLocation Loc,Expr * RHS,bool isProperty)15514 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15515                                      Expr *RHS, bool isProperty) {
15516   // Check if RHS is an Objective-C object literal, which also can get
15517   // immediately zapped in a weak reference.  Note that we explicitly
15518   // allow ObjCStringLiterals, since those are designed to never really die.
15519   RHS = RHS->IgnoreParenImpCasts();
15520 
15521   // This enum needs to match with the 'select' in
15522   // warn_objc_arc_literal_assign (off-by-1).
15523   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15524   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15525     return false;
15526 
15527   S.Diag(Loc, diag::warn_arc_literal_assign)
15528     << (unsigned) Kind
15529     << (isProperty ? 0 : 1)
15530     << RHS->getSourceRange();
15531 
15532   return true;
15533 }
15534 
checkUnsafeAssignObject(Sema & S,SourceLocation Loc,Qualifiers::ObjCLifetime LT,Expr * RHS,bool isProperty)15535 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15536                                     Qualifiers::ObjCLifetime LT,
15537                                     Expr *RHS, bool isProperty) {
15538   // Strip off any implicit cast added to get to the one ARC-specific.
15539   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15540     if (cast->getCastKind() == CK_ARCConsumeObject) {
15541       S.Diag(Loc, diag::warn_arc_retained_assign)
15542         << (LT == Qualifiers::OCL_ExplicitNone)
15543         << (isProperty ? 0 : 1)
15544         << RHS->getSourceRange();
15545       return true;
15546     }
15547     RHS = cast->getSubExpr();
15548   }
15549 
15550   if (LT == Qualifiers::OCL_Weak &&
15551       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15552     return true;
15553 
15554   return false;
15555 }
15556 
checkUnsafeAssigns(SourceLocation Loc,QualType LHS,Expr * RHS)15557 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15558                               QualType LHS, Expr *RHS) {
15559   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15560 
15561   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15562     return false;
15563 
15564   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15565     return true;
15566 
15567   return false;
15568 }
15569 
checkUnsafeExprAssigns(SourceLocation Loc,Expr * LHS,Expr * RHS)15570 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15571                               Expr *LHS, Expr *RHS) {
15572   QualType LHSType;
15573   // PropertyRef on LHS type need be directly obtained from
15574   // its declaration as it has a PseudoType.
15575   ObjCPropertyRefExpr *PRE
15576     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15577   if (PRE && !PRE->isImplicitProperty()) {
15578     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15579     if (PD)
15580       LHSType = PD->getType();
15581   }
15582 
15583   if (LHSType.isNull())
15584     LHSType = LHS->getType();
15585 
15586   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15587 
15588   if (LT == Qualifiers::OCL_Weak) {
15589     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15590       getCurFunction()->markSafeWeakUse(LHS);
15591   }
15592 
15593   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15594     return;
15595 
15596   // FIXME. Check for other life times.
15597   if (LT != Qualifiers::OCL_None)
15598     return;
15599 
15600   if (PRE) {
15601     if (PRE->isImplicitProperty())
15602       return;
15603     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15604     if (!PD)
15605       return;
15606 
15607     unsigned Attributes = PD->getPropertyAttributes();
15608     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15609       // when 'assign' attribute was not explicitly specified
15610       // by user, ignore it and rely on property type itself
15611       // for lifetime info.
15612       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15613       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15614           LHSType->isObjCRetainableType())
15615         return;
15616 
15617       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15618         if (cast->getCastKind() == CK_ARCConsumeObject) {
15619           Diag(Loc, diag::warn_arc_retained_property_assign)
15620           << RHS->getSourceRange();
15621           return;
15622         }
15623         RHS = cast->getSubExpr();
15624       }
15625     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15626       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15627         return;
15628     }
15629   }
15630 }
15631 
15632 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15633 
ShouldDiagnoseEmptyStmtBody(const SourceManager & SourceMgr,SourceLocation StmtLoc,const NullStmt * Body)15634 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15635                                         SourceLocation StmtLoc,
15636                                         const NullStmt *Body) {
15637   // Do not warn if the body is a macro that expands to nothing, e.g:
15638   //
15639   // #define CALL(x)
15640   // if (condition)
15641   //   CALL(0);
15642   if (Body->hasLeadingEmptyMacro())
15643     return false;
15644 
15645   // Get line numbers of statement and body.
15646   bool StmtLineInvalid;
15647   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15648                                                       &StmtLineInvalid);
15649   if (StmtLineInvalid)
15650     return false;
15651 
15652   bool BodyLineInvalid;
15653   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15654                                                       &BodyLineInvalid);
15655   if (BodyLineInvalid)
15656     return false;
15657 
15658   // Warn if null statement and body are on the same line.
15659   if (StmtLine != BodyLine)
15660     return false;
15661 
15662   return true;
15663 }
15664 
DiagnoseEmptyStmtBody(SourceLocation StmtLoc,const Stmt * Body,unsigned DiagID)15665 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15666                                  const Stmt *Body,
15667                                  unsigned DiagID) {
15668   // Since this is a syntactic check, don't emit diagnostic for template
15669   // instantiations, this just adds noise.
15670   if (CurrentInstantiationScope)
15671     return;
15672 
15673   // The body should be a null statement.
15674   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15675   if (!NBody)
15676     return;
15677 
15678   // Do the usual checks.
15679   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15680     return;
15681 
15682   Diag(NBody->getSemiLoc(), DiagID);
15683   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15684 }
15685 
DiagnoseEmptyLoopBody(const Stmt * S,const Stmt * PossibleBody)15686 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15687                                  const Stmt *PossibleBody) {
15688   assert(!CurrentInstantiationScope); // Ensured by caller
15689 
15690   SourceLocation StmtLoc;
15691   const Stmt *Body;
15692   unsigned DiagID;
15693   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15694     StmtLoc = FS->getRParenLoc();
15695     Body = FS->getBody();
15696     DiagID = diag::warn_empty_for_body;
15697   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15698     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15699     Body = WS->getBody();
15700     DiagID = diag::warn_empty_while_body;
15701   } else
15702     return; // Neither `for' nor `while'.
15703 
15704   // The body should be a null statement.
15705   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15706   if (!NBody)
15707     return;
15708 
15709   // Skip expensive checks if diagnostic is disabled.
15710   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15711     return;
15712 
15713   // Do the usual checks.
15714   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15715     return;
15716 
15717   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15718   // noise level low, emit diagnostics only if for/while is followed by a
15719   // CompoundStmt, e.g.:
15720   //    for (int i = 0; i < n; i++);
15721   //    {
15722   //      a(i);
15723   //    }
15724   // or if for/while is followed by a statement with more indentation
15725   // than for/while itself:
15726   //    for (int i = 0; i < n; i++);
15727   //      a(i);
15728   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15729   if (!ProbableTypo) {
15730     bool BodyColInvalid;
15731     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15732         PossibleBody->getBeginLoc(), &BodyColInvalid);
15733     if (BodyColInvalid)
15734       return;
15735 
15736     bool StmtColInvalid;
15737     unsigned StmtCol =
15738         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15739     if (StmtColInvalid)
15740       return;
15741 
15742     if (BodyCol > StmtCol)
15743       ProbableTypo = true;
15744   }
15745 
15746   if (ProbableTypo) {
15747     Diag(NBody->getSemiLoc(), DiagID);
15748     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15749   }
15750 }
15751 
15752 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15753 
15754 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
DiagnoseSelfMove(const Expr * LHSExpr,const Expr * RHSExpr,SourceLocation OpLoc)15755 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15756                              SourceLocation OpLoc) {
15757   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15758     return;
15759 
15760   if (inTemplateInstantiation())
15761     return;
15762 
15763   // Strip parens and casts away.
15764   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15765   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15766 
15767   // Check for a call expression
15768   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15769   if (!CE || CE->getNumArgs() != 1)
15770     return;
15771 
15772   // Check for a call to std::move
15773   if (!CE->isCallToStdMove())
15774     return;
15775 
15776   // Get argument from std::move
15777   RHSExpr = CE->getArg(0);
15778 
15779   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15780   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15781 
15782   // Two DeclRefExpr's, check that the decls are the same.
15783   if (LHSDeclRef && RHSDeclRef) {
15784     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15785       return;
15786     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15787         RHSDeclRef->getDecl()->getCanonicalDecl())
15788       return;
15789 
15790     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15791                                         << LHSExpr->getSourceRange()
15792                                         << RHSExpr->getSourceRange();
15793     return;
15794   }
15795 
15796   // Member variables require a different approach to check for self moves.
15797   // MemberExpr's are the same if every nested MemberExpr refers to the same
15798   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15799   // the base Expr's are CXXThisExpr's.
15800   const Expr *LHSBase = LHSExpr;
15801   const Expr *RHSBase = RHSExpr;
15802   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15803   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15804   if (!LHSME || !RHSME)
15805     return;
15806 
15807   while (LHSME && RHSME) {
15808     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15809         RHSME->getMemberDecl()->getCanonicalDecl())
15810       return;
15811 
15812     LHSBase = LHSME->getBase();
15813     RHSBase = RHSME->getBase();
15814     LHSME = dyn_cast<MemberExpr>(LHSBase);
15815     RHSME = dyn_cast<MemberExpr>(RHSBase);
15816   }
15817 
15818   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15819   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15820   if (LHSDeclRef && RHSDeclRef) {
15821     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15822       return;
15823     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15824         RHSDeclRef->getDecl()->getCanonicalDecl())
15825       return;
15826 
15827     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15828                                         << LHSExpr->getSourceRange()
15829                                         << RHSExpr->getSourceRange();
15830     return;
15831   }
15832 
15833   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15834     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15835                                         << LHSExpr->getSourceRange()
15836                                         << RHSExpr->getSourceRange();
15837 }
15838 
15839 //===--- Layout compatibility ----------------------------------------------//
15840 
15841 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15842 
15843 /// Check if two enumeration types are layout-compatible.
isLayoutCompatible(ASTContext & C,EnumDecl * ED1,EnumDecl * ED2)15844 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15845   // C++11 [dcl.enum] p8:
15846   // Two enumeration types are layout-compatible if they have the same
15847   // underlying type.
15848   return ED1->isComplete() && ED2->isComplete() &&
15849          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15850 }
15851 
15852 /// Check if two fields are layout-compatible.
isLayoutCompatible(ASTContext & C,FieldDecl * Field1,FieldDecl * Field2)15853 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15854                                FieldDecl *Field2) {
15855   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15856     return false;
15857 
15858   if (Field1->isBitField() != Field2->isBitField())
15859     return false;
15860 
15861   if (Field1->isBitField()) {
15862     // Make sure that the bit-fields are the same length.
15863     unsigned Bits1 = Field1->getBitWidthValue(C);
15864     unsigned Bits2 = Field2->getBitWidthValue(C);
15865 
15866     if (Bits1 != Bits2)
15867       return false;
15868   }
15869 
15870   return true;
15871 }
15872 
15873 /// Check if two standard-layout structs are layout-compatible.
15874 /// (C++11 [class.mem] p17)
isLayoutCompatibleStruct(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)15875 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15876                                      RecordDecl *RD2) {
15877   // If both records are C++ classes, check that base classes match.
15878   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15879     // If one of records is a CXXRecordDecl we are in C++ mode,
15880     // thus the other one is a CXXRecordDecl, too.
15881     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15882     // Check number of base classes.
15883     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15884       return false;
15885 
15886     // Check the base classes.
15887     for (CXXRecordDecl::base_class_const_iterator
15888                Base1 = D1CXX->bases_begin(),
15889            BaseEnd1 = D1CXX->bases_end(),
15890               Base2 = D2CXX->bases_begin();
15891          Base1 != BaseEnd1;
15892          ++Base1, ++Base2) {
15893       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15894         return false;
15895     }
15896   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15897     // If only RD2 is a C++ class, it should have zero base classes.
15898     if (D2CXX->getNumBases() > 0)
15899       return false;
15900   }
15901 
15902   // Check the fields.
15903   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15904                              Field2End = RD2->field_end(),
15905                              Field1 = RD1->field_begin(),
15906                              Field1End = RD1->field_end();
15907   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15908     if (!isLayoutCompatible(C, *Field1, *Field2))
15909       return false;
15910   }
15911   if (Field1 != Field1End || Field2 != Field2End)
15912     return false;
15913 
15914   return true;
15915 }
15916 
15917 /// Check if two standard-layout unions are layout-compatible.
15918 /// (C++11 [class.mem] p18)
isLayoutCompatibleUnion(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)15919 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15920                                     RecordDecl *RD2) {
15921   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15922   for (auto *Field2 : RD2->fields())
15923     UnmatchedFields.insert(Field2);
15924 
15925   for (auto *Field1 : RD1->fields()) {
15926     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15927         I = UnmatchedFields.begin(),
15928         E = UnmatchedFields.end();
15929 
15930     for ( ; I != E; ++I) {
15931       if (isLayoutCompatible(C, Field1, *I)) {
15932         bool Result = UnmatchedFields.erase(*I);
15933         (void) Result;
15934         assert(Result);
15935         break;
15936       }
15937     }
15938     if (I == E)
15939       return false;
15940   }
15941 
15942   return UnmatchedFields.empty();
15943 }
15944 
isLayoutCompatible(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)15945 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15946                                RecordDecl *RD2) {
15947   if (RD1->isUnion() != RD2->isUnion())
15948     return false;
15949 
15950   if (RD1->isUnion())
15951     return isLayoutCompatibleUnion(C, RD1, RD2);
15952   else
15953     return isLayoutCompatibleStruct(C, RD1, RD2);
15954 }
15955 
15956 /// Check if two types are layout-compatible in C++11 sense.
isLayoutCompatible(ASTContext & C,QualType T1,QualType T2)15957 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15958   if (T1.isNull() || T2.isNull())
15959     return false;
15960 
15961   // C++11 [basic.types] p11:
15962   // If two types T1 and T2 are the same type, then T1 and T2 are
15963   // layout-compatible types.
15964   if (C.hasSameType(T1, T2))
15965     return true;
15966 
15967   T1 = T1.getCanonicalType().getUnqualifiedType();
15968   T2 = T2.getCanonicalType().getUnqualifiedType();
15969 
15970   const Type::TypeClass TC1 = T1->getTypeClass();
15971   const Type::TypeClass TC2 = T2->getTypeClass();
15972 
15973   if (TC1 != TC2)
15974     return false;
15975 
15976   if (TC1 == Type::Enum) {
15977     return isLayoutCompatible(C,
15978                               cast<EnumType>(T1)->getDecl(),
15979                               cast<EnumType>(T2)->getDecl());
15980   } else if (TC1 == Type::Record) {
15981     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15982       return false;
15983 
15984     return isLayoutCompatible(C,
15985                               cast<RecordType>(T1)->getDecl(),
15986                               cast<RecordType>(T2)->getDecl());
15987   }
15988 
15989   return false;
15990 }
15991 
15992 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15993 
15994 /// Given a type tag expression find the type tag itself.
15995 ///
15996 /// \param TypeExpr Type tag expression, as it appears in user's code.
15997 ///
15998 /// \param VD Declaration of an identifier that appears in a type tag.
15999 ///
16000 /// \param MagicValue Type tag magic value.
16001 ///
16002 /// \param isConstantEvaluated wether the evalaution should be performed in
16003 
16004 /// constant context.
FindTypeTagExpr(const Expr * TypeExpr,const ASTContext & Ctx,const ValueDecl ** VD,uint64_t * MagicValue,bool isConstantEvaluated)16005 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16006                             const ValueDecl **VD, uint64_t *MagicValue,
16007                             bool isConstantEvaluated) {
16008   while(true) {
16009     if (!TypeExpr)
16010       return false;
16011 
16012     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16013 
16014     switch (TypeExpr->getStmtClass()) {
16015     case Stmt::UnaryOperatorClass: {
16016       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16017       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16018         TypeExpr = UO->getSubExpr();
16019         continue;
16020       }
16021       return false;
16022     }
16023 
16024     case Stmt::DeclRefExprClass: {
16025       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16026       *VD = DRE->getDecl();
16027       return true;
16028     }
16029 
16030     case Stmt::IntegerLiteralClass: {
16031       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16032       llvm::APInt MagicValueAPInt = IL->getValue();
16033       if (MagicValueAPInt.getActiveBits() <= 64) {
16034         *MagicValue = MagicValueAPInt.getZExtValue();
16035         return true;
16036       } else
16037         return false;
16038     }
16039 
16040     case Stmt::BinaryConditionalOperatorClass:
16041     case Stmt::ConditionalOperatorClass: {
16042       const AbstractConditionalOperator *ACO =
16043           cast<AbstractConditionalOperator>(TypeExpr);
16044       bool Result;
16045       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16046                                                      isConstantEvaluated)) {
16047         if (Result)
16048           TypeExpr = ACO->getTrueExpr();
16049         else
16050           TypeExpr = ACO->getFalseExpr();
16051         continue;
16052       }
16053       return false;
16054     }
16055 
16056     case Stmt::BinaryOperatorClass: {
16057       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16058       if (BO->getOpcode() == BO_Comma) {
16059         TypeExpr = BO->getRHS();
16060         continue;
16061       }
16062       return false;
16063     }
16064 
16065     default:
16066       return false;
16067     }
16068   }
16069 }
16070 
16071 /// Retrieve the C type corresponding to type tag TypeExpr.
16072 ///
16073 /// \param TypeExpr Expression that specifies a type tag.
16074 ///
16075 /// \param MagicValues Registered magic values.
16076 ///
16077 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16078 ///        kind.
16079 ///
16080 /// \param TypeInfo Information about the corresponding C type.
16081 ///
16082 /// \param isConstantEvaluated wether the evalaution should be performed in
16083 /// constant context.
16084 ///
16085 /// \returns true if the corresponding C type was found.
GetMatchingCType(const IdentifierInfo * ArgumentKind,const Expr * TypeExpr,const ASTContext & Ctx,const llvm::DenseMap<Sema::TypeTagMagicValue,Sema::TypeTagData> * MagicValues,bool & FoundWrongKind,Sema::TypeTagData & TypeInfo,bool isConstantEvaluated)16086 static bool GetMatchingCType(
16087     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16088     const ASTContext &Ctx,
16089     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16090         *MagicValues,
16091     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16092     bool isConstantEvaluated) {
16093   FoundWrongKind = false;
16094 
16095   // Variable declaration that has type_tag_for_datatype attribute.
16096   const ValueDecl *VD = nullptr;
16097 
16098   uint64_t MagicValue;
16099 
16100   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16101     return false;
16102 
16103   if (VD) {
16104     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16105       if (I->getArgumentKind() != ArgumentKind) {
16106         FoundWrongKind = true;
16107         return false;
16108       }
16109       TypeInfo.Type = I->getMatchingCType();
16110       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16111       TypeInfo.MustBeNull = I->getMustBeNull();
16112       return true;
16113     }
16114     return false;
16115   }
16116 
16117   if (!MagicValues)
16118     return false;
16119 
16120   llvm::DenseMap<Sema::TypeTagMagicValue,
16121                  Sema::TypeTagData>::const_iterator I =
16122       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16123   if (I == MagicValues->end())
16124     return false;
16125 
16126   TypeInfo = I->second;
16127   return true;
16128 }
16129 
RegisterTypeTagForDatatype(const IdentifierInfo * ArgumentKind,uint64_t MagicValue,QualType Type,bool LayoutCompatible,bool MustBeNull)16130 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16131                                       uint64_t MagicValue, QualType Type,
16132                                       bool LayoutCompatible,
16133                                       bool MustBeNull) {
16134   if (!TypeTagForDatatypeMagicValues)
16135     TypeTagForDatatypeMagicValues.reset(
16136         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16137 
16138   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16139   (*TypeTagForDatatypeMagicValues)[Magic] =
16140       TypeTagData(Type, LayoutCompatible, MustBeNull);
16141 }
16142 
IsSameCharType(QualType T1,QualType T2)16143 static bool IsSameCharType(QualType T1, QualType T2) {
16144   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16145   if (!BT1)
16146     return false;
16147 
16148   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16149   if (!BT2)
16150     return false;
16151 
16152   BuiltinType::Kind T1Kind = BT1->getKind();
16153   BuiltinType::Kind T2Kind = BT2->getKind();
16154 
16155   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16156          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16157          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16158          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16159 }
16160 
CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr * Attr,const ArrayRef<const Expr * > ExprArgs,SourceLocation CallSiteLoc)16161 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16162                                     const ArrayRef<const Expr *> ExprArgs,
16163                                     SourceLocation CallSiteLoc) {
16164   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16165   bool IsPointerAttr = Attr->getIsPointer();
16166 
16167   // Retrieve the argument representing the 'type_tag'.
16168   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16169   if (TypeTagIdxAST >= ExprArgs.size()) {
16170     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16171         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16172     return;
16173   }
16174   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16175   bool FoundWrongKind;
16176   TypeTagData TypeInfo;
16177   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16178                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16179                         TypeInfo, isConstantEvaluated())) {
16180     if (FoundWrongKind)
16181       Diag(TypeTagExpr->getExprLoc(),
16182            diag::warn_type_tag_for_datatype_wrong_kind)
16183         << TypeTagExpr->getSourceRange();
16184     return;
16185   }
16186 
16187   // Retrieve the argument representing the 'arg_idx'.
16188   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16189   if (ArgumentIdxAST >= ExprArgs.size()) {
16190     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16191         << 1 << Attr->getArgumentIdx().getSourceIndex();
16192     return;
16193   }
16194   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16195   if (IsPointerAttr) {
16196     // Skip implicit cast of pointer to `void *' (as a function argument).
16197     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16198       if (ICE->getType()->isVoidPointerType() &&
16199           ICE->getCastKind() == CK_BitCast)
16200         ArgumentExpr = ICE->getSubExpr();
16201   }
16202   QualType ArgumentType = ArgumentExpr->getType();
16203 
16204   // Passing a `void*' pointer shouldn't trigger a warning.
16205   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16206     return;
16207 
16208   if (TypeInfo.MustBeNull) {
16209     // Type tag with matching void type requires a null pointer.
16210     if (!ArgumentExpr->isNullPointerConstant(Context,
16211                                              Expr::NPC_ValueDependentIsNotNull)) {
16212       Diag(ArgumentExpr->getExprLoc(),
16213            diag::warn_type_safety_null_pointer_required)
16214           << ArgumentKind->getName()
16215           << ArgumentExpr->getSourceRange()
16216           << TypeTagExpr->getSourceRange();
16217     }
16218     return;
16219   }
16220 
16221   QualType RequiredType = TypeInfo.Type;
16222   if (IsPointerAttr)
16223     RequiredType = Context.getPointerType(RequiredType);
16224 
16225   bool mismatch = false;
16226   if (!TypeInfo.LayoutCompatible) {
16227     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16228 
16229     // C++11 [basic.fundamental] p1:
16230     // Plain char, signed char, and unsigned char are three distinct types.
16231     //
16232     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16233     // char' depending on the current char signedness mode.
16234     if (mismatch)
16235       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16236                                            RequiredType->getPointeeType())) ||
16237           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16238         mismatch = false;
16239   } else
16240     if (IsPointerAttr)
16241       mismatch = !isLayoutCompatible(Context,
16242                                      ArgumentType->getPointeeType(),
16243                                      RequiredType->getPointeeType());
16244     else
16245       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16246 
16247   if (mismatch)
16248     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16249         << ArgumentType << ArgumentKind
16250         << TypeInfo.LayoutCompatible << RequiredType
16251         << ArgumentExpr->getSourceRange()
16252         << TypeTagExpr->getSourceRange();
16253 }
16254 
AddPotentialMisalignedMembers(Expr * E,RecordDecl * RD,ValueDecl * MD,CharUnits Alignment)16255 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16256                                          CharUnits Alignment) {
16257   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16258 }
16259 
DiagnoseMisalignedMembers()16260 void Sema::DiagnoseMisalignedMembers() {
16261   for (MisalignedMember &m : MisalignedMembers) {
16262     const NamedDecl *ND = m.RD;
16263     if (ND->getName().empty()) {
16264       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16265         ND = TD;
16266     }
16267     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16268         << m.MD << ND << m.E->getSourceRange();
16269   }
16270   MisalignedMembers.clear();
16271 }
16272 
DiscardMisalignedMemberAddress(const Type * T,Expr * E)16273 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16274   E = E->IgnoreParens();
16275   if (!T->isPointerType() && !T->isIntegerType())
16276     return;
16277   if (isa<UnaryOperator>(E) &&
16278       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16279     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16280     if (isa<MemberExpr>(Op)) {
16281       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16282       if (MA != MisalignedMembers.end() &&
16283           (T->isIntegerType() ||
16284            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16285                                    Context.getTypeAlignInChars(
16286                                        T->getPointeeType()) <= MA->Alignment))))
16287         MisalignedMembers.erase(MA);
16288     }
16289   }
16290 }
16291 
RefersToMemberWithReducedAlignment(Expr * E,llvm::function_ref<void (Expr *,RecordDecl *,FieldDecl *,CharUnits)> Action)16292 void Sema::RefersToMemberWithReducedAlignment(
16293     Expr *E,
16294     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16295         Action) {
16296   const auto *ME = dyn_cast<MemberExpr>(E);
16297   if (!ME)
16298     return;
16299 
16300   // No need to check expressions with an __unaligned-qualified type.
16301   if (E->getType().getQualifiers().hasUnaligned())
16302     return;
16303 
16304   // For a chain of MemberExpr like "a.b.c.d" this list
16305   // will keep FieldDecl's like [d, c, b].
16306   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16307   const MemberExpr *TopME = nullptr;
16308   bool AnyIsPacked = false;
16309   do {
16310     QualType BaseType = ME->getBase()->getType();
16311     if (BaseType->isDependentType())
16312       return;
16313     if (ME->isArrow())
16314       BaseType = BaseType->getPointeeType();
16315     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16316     if (RD->isInvalidDecl())
16317       return;
16318 
16319     ValueDecl *MD = ME->getMemberDecl();
16320     auto *FD = dyn_cast<FieldDecl>(MD);
16321     // We do not care about non-data members.
16322     if (!FD || FD->isInvalidDecl())
16323       return;
16324 
16325     AnyIsPacked =
16326         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16327     ReverseMemberChain.push_back(FD);
16328 
16329     TopME = ME;
16330     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16331   } while (ME);
16332   assert(TopME && "We did not compute a topmost MemberExpr!");
16333 
16334   // Not the scope of this diagnostic.
16335   if (!AnyIsPacked)
16336     return;
16337 
16338   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16339   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16340   // TODO: The innermost base of the member expression may be too complicated.
16341   // For now, just disregard these cases. This is left for future
16342   // improvement.
16343   if (!DRE && !isa<CXXThisExpr>(TopBase))
16344       return;
16345 
16346   // Alignment expected by the whole expression.
16347   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16348 
16349   // No need to do anything else with this case.
16350   if (ExpectedAlignment.isOne())
16351     return;
16352 
16353   // Synthesize offset of the whole access.
16354   CharUnits Offset;
16355   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16356        I++) {
16357     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16358   }
16359 
16360   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16361   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16362       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16363 
16364   // The base expression of the innermost MemberExpr may give
16365   // stronger guarantees than the class containing the member.
16366   if (DRE && !TopME->isArrow()) {
16367     const ValueDecl *VD = DRE->getDecl();
16368     if (!VD->getType()->isReferenceType())
16369       CompleteObjectAlignment =
16370           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16371   }
16372 
16373   // Check if the synthesized offset fulfills the alignment.
16374   if (Offset % ExpectedAlignment != 0 ||
16375       // It may fulfill the offset it but the effective alignment may still be
16376       // lower than the expected expression alignment.
16377       CompleteObjectAlignment < ExpectedAlignment) {
16378     // If this happens, we want to determine a sensible culprit of this.
16379     // Intuitively, watching the chain of member expressions from right to
16380     // left, we start with the required alignment (as required by the field
16381     // type) but some packed attribute in that chain has reduced the alignment.
16382     // It may happen that another packed structure increases it again. But if
16383     // we are here such increase has not been enough. So pointing the first
16384     // FieldDecl that either is packed or else its RecordDecl is,
16385     // seems reasonable.
16386     FieldDecl *FD = nullptr;
16387     CharUnits Alignment;
16388     for (FieldDecl *FDI : ReverseMemberChain) {
16389       if (FDI->hasAttr<PackedAttr>() ||
16390           FDI->getParent()->hasAttr<PackedAttr>()) {
16391         FD = FDI;
16392         Alignment = std::min(
16393             Context.getTypeAlignInChars(FD->getType()),
16394             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16395         break;
16396       }
16397     }
16398     assert(FD && "We did not find a packed FieldDecl!");
16399     Action(E, FD->getParent(), FD, Alignment);
16400   }
16401 }
16402 
CheckAddressOfPackedMember(Expr * rhs)16403 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16404   using namespace std::placeholders;
16405 
16406   RefersToMemberWithReducedAlignment(
16407       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16408                      _2, _3, _4));
16409 }
16410 
SemaBuiltinMatrixTranspose(CallExpr * TheCall,ExprResult CallResult)16411 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16412                                             ExprResult CallResult) {
16413   if (checkArgCount(*this, TheCall, 1))
16414     return ExprError();
16415 
16416   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16417   if (MatrixArg.isInvalid())
16418     return MatrixArg;
16419   Expr *Matrix = MatrixArg.get();
16420 
16421   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16422   if (!MType) {
16423     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16424     return ExprError();
16425   }
16426 
16427   // Create returned matrix type by swapping rows and columns of the argument
16428   // matrix type.
16429   QualType ResultType = Context.getConstantMatrixType(
16430       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16431 
16432   // Change the return type to the type of the returned matrix.
16433   TheCall->setType(ResultType);
16434 
16435   // Update call argument to use the possibly converted matrix argument.
16436   TheCall->setArg(0, Matrix);
16437   return CallResult;
16438 }
16439 
16440 // Get and verify the matrix dimensions.
16441 static llvm::Optional<unsigned>
getAndVerifyMatrixDimension(Expr * Expr,StringRef Name,Sema & S)16442 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16443   SourceLocation ErrorPos;
16444   Optional<llvm::APSInt> Value =
16445       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16446   if (!Value) {
16447     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16448         << Name;
16449     return {};
16450   }
16451   uint64_t Dim = Value->getZExtValue();
16452   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16453     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16454         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16455     return {};
16456   }
16457   return Dim;
16458 }
16459 
SemaBuiltinMatrixColumnMajorLoad(CallExpr * TheCall,ExprResult CallResult)16460 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16461                                                   ExprResult CallResult) {
16462   if (!getLangOpts().MatrixTypes) {
16463     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16464     return ExprError();
16465   }
16466 
16467   if (checkArgCount(*this, TheCall, 4))
16468     return ExprError();
16469 
16470   unsigned PtrArgIdx = 0;
16471   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16472   Expr *RowsExpr = TheCall->getArg(1);
16473   Expr *ColumnsExpr = TheCall->getArg(2);
16474   Expr *StrideExpr = TheCall->getArg(3);
16475 
16476   bool ArgError = false;
16477 
16478   // Check pointer argument.
16479   {
16480     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16481     if (PtrConv.isInvalid())
16482       return PtrConv;
16483     PtrExpr = PtrConv.get();
16484     TheCall->setArg(0, PtrExpr);
16485     if (PtrExpr->isTypeDependent()) {
16486       TheCall->setType(Context.DependentTy);
16487       return TheCall;
16488     }
16489   }
16490 
16491   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16492   QualType ElementTy;
16493   if (!PtrTy) {
16494     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16495         << PtrArgIdx + 1;
16496     ArgError = true;
16497   } else {
16498     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16499 
16500     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16501       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16502           << PtrArgIdx + 1;
16503       ArgError = true;
16504     }
16505   }
16506 
16507   // Apply default Lvalue conversions and convert the expression to size_t.
16508   auto ApplyArgumentConversions = [this](Expr *E) {
16509     ExprResult Conv = DefaultLvalueConversion(E);
16510     if (Conv.isInvalid())
16511       return Conv;
16512 
16513     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16514   };
16515 
16516   // Apply conversion to row and column expressions.
16517   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16518   if (!RowsConv.isInvalid()) {
16519     RowsExpr = RowsConv.get();
16520     TheCall->setArg(1, RowsExpr);
16521   } else
16522     RowsExpr = nullptr;
16523 
16524   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16525   if (!ColumnsConv.isInvalid()) {
16526     ColumnsExpr = ColumnsConv.get();
16527     TheCall->setArg(2, ColumnsExpr);
16528   } else
16529     ColumnsExpr = nullptr;
16530 
16531   // If any any part of the result matrix type is still pending, just use
16532   // Context.DependentTy, until all parts are resolved.
16533   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16534       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16535     TheCall->setType(Context.DependentTy);
16536     return CallResult;
16537   }
16538 
16539   // Check row and column dimenions.
16540   llvm::Optional<unsigned> MaybeRows;
16541   if (RowsExpr)
16542     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16543 
16544   llvm::Optional<unsigned> MaybeColumns;
16545   if (ColumnsExpr)
16546     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16547 
16548   // Check stride argument.
16549   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16550   if (StrideConv.isInvalid())
16551     return ExprError();
16552   StrideExpr = StrideConv.get();
16553   TheCall->setArg(3, StrideExpr);
16554 
16555   if (MaybeRows) {
16556     if (Optional<llvm::APSInt> Value =
16557             StrideExpr->getIntegerConstantExpr(Context)) {
16558       uint64_t Stride = Value->getZExtValue();
16559       if (Stride < *MaybeRows) {
16560         Diag(StrideExpr->getBeginLoc(),
16561              diag::err_builtin_matrix_stride_too_small);
16562         ArgError = true;
16563       }
16564     }
16565   }
16566 
16567   if (ArgError || !MaybeRows || !MaybeColumns)
16568     return ExprError();
16569 
16570   TheCall->setType(
16571       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16572   return CallResult;
16573 }
16574 
SemaBuiltinMatrixColumnMajorStore(CallExpr * TheCall,ExprResult CallResult)16575 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16576                                                    ExprResult CallResult) {
16577   if (checkArgCount(*this, TheCall, 3))
16578     return ExprError();
16579 
16580   unsigned PtrArgIdx = 1;
16581   Expr *MatrixExpr = TheCall->getArg(0);
16582   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16583   Expr *StrideExpr = TheCall->getArg(2);
16584 
16585   bool ArgError = false;
16586 
16587   {
16588     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16589     if (MatrixConv.isInvalid())
16590       return MatrixConv;
16591     MatrixExpr = MatrixConv.get();
16592     TheCall->setArg(0, MatrixExpr);
16593   }
16594   if (MatrixExpr->isTypeDependent()) {
16595     TheCall->setType(Context.DependentTy);
16596     return TheCall;
16597   }
16598 
16599   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16600   if (!MatrixTy) {
16601     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16602     ArgError = true;
16603   }
16604 
16605   {
16606     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16607     if (PtrConv.isInvalid())
16608       return PtrConv;
16609     PtrExpr = PtrConv.get();
16610     TheCall->setArg(1, PtrExpr);
16611     if (PtrExpr->isTypeDependent()) {
16612       TheCall->setType(Context.DependentTy);
16613       return TheCall;
16614     }
16615   }
16616 
16617   // Check pointer argument.
16618   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16619   if (!PtrTy) {
16620     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16621         << PtrArgIdx + 1;
16622     ArgError = true;
16623   } else {
16624     QualType ElementTy = PtrTy->getPointeeType();
16625     if (ElementTy.isConstQualified()) {
16626       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16627       ArgError = true;
16628     }
16629     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16630     if (MatrixTy &&
16631         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16632       Diag(PtrExpr->getBeginLoc(),
16633            diag::err_builtin_matrix_pointer_arg_mismatch)
16634           << ElementTy << MatrixTy->getElementType();
16635       ArgError = true;
16636     }
16637   }
16638 
16639   // Apply default Lvalue conversions and convert the stride expression to
16640   // size_t.
16641   {
16642     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16643     if (StrideConv.isInvalid())
16644       return StrideConv;
16645 
16646     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16647     if (StrideConv.isInvalid())
16648       return StrideConv;
16649     StrideExpr = StrideConv.get();
16650     TheCall->setArg(2, StrideExpr);
16651   }
16652 
16653   // Check stride argument.
16654   if (MatrixTy) {
16655     if (Optional<llvm::APSInt> Value =
16656             StrideExpr->getIntegerConstantExpr(Context)) {
16657       uint64_t Stride = Value->getZExtValue();
16658       if (Stride < MatrixTy->getNumRows()) {
16659         Diag(StrideExpr->getBeginLoc(),
16660              diag::err_builtin_matrix_stride_too_small);
16661         ArgError = true;
16662       }
16663     }
16664   }
16665 
16666   if (ArgError)
16667     return ExprError();
16668 
16669   return CallResult;
16670 }
16671 
16672 /// \brief Enforce the bounds of a TCB
16673 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16674 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16675 /// and enforce_tcb_leaf attributes.
CheckTCBEnforcement(const CallExpr * TheCall,const FunctionDecl * Callee)16676 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16677                                const FunctionDecl *Callee) {
16678   const FunctionDecl *Caller = getCurFunctionDecl();
16679 
16680   // Calls to builtins are not enforced.
16681   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16682       Callee->getBuiltinID() != 0)
16683     return;
16684 
16685   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16686   // all TCBs the callee is a part of.
16687   llvm::StringSet<> CalleeTCBs;
16688   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16689            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16690   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16691            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16692 
16693   // Go through the TCBs the caller is a part of and emit warnings if Caller
16694   // is in a TCB that the Callee is not.
16695   for_each(
16696       Caller->specific_attrs<EnforceTCBAttr>(),
16697       [&](const auto *A) {
16698         StringRef CallerTCB = A->getTCBName();
16699         if (CalleeTCBs.count(CallerTCB) == 0) {
16700           this->Diag(TheCall->getExprLoc(),
16701                      diag::warn_tcb_enforcement_violation) << Callee
16702                                                            << CallerTCB;
16703         }
16704       });
16705 }
16706