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 <cstddef>
95 #include <cstdint>
96 #include <functional>
97 #include <limits>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 
102 using namespace clang;
103 using namespace sema;
104 
105 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
106                                                     unsigned ByteNo) const {
107   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
108                                Context.getTargetInfo());
109 }
110 
111 /// Checks that a call expression's argument count is the desired number.
112 /// This is useful when doing custom type-checking.  Returns true on error.
113 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
114   unsigned argCount = call->getNumArgs();
115   if (argCount == desiredArgCount) return false;
116 
117   if (argCount < desiredArgCount)
118     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
119            << 0 /*function call*/ << desiredArgCount << argCount
120            << call->getSourceRange();
121 
122   // Highlight all the excess arguments.
123   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
124                     call->getArg(argCount - 1)->getEndLoc());
125 
126   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
127     << 0 /*function call*/ << desiredArgCount << argCount
128     << call->getArg(1)->getSourceRange();
129 }
130 
131 /// Check that the first argument to __builtin_annotation is an integer
132 /// and the second argument is a non-wide string literal.
133 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
134   if (checkArgCount(S, TheCall, 2))
135     return true;
136 
137   // First argument should be an integer.
138   Expr *ValArg = TheCall->getArg(0);
139   QualType Ty = ValArg->getType();
140   if (!Ty->isIntegerType()) {
141     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
142         << ValArg->getSourceRange();
143     return true;
144   }
145 
146   // Second argument should be a constant string.
147   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
148   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
149   if (!Literal || !Literal->isAscii()) {
150     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
151         << StrArg->getSourceRange();
152     return true;
153   }
154 
155   TheCall->setType(Ty);
156   return false;
157 }
158 
159 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
160   // We need at least one argument.
161   if (TheCall->getNumArgs() < 1) {
162     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
163         << 0 << 1 << TheCall->getNumArgs()
164         << TheCall->getCallee()->getSourceRange();
165     return true;
166   }
167 
168   // All arguments should be wide string literals.
169   for (Expr *Arg : TheCall->arguments()) {
170     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
171     if (!Literal || !Literal->isWide()) {
172       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
173           << Arg->getSourceRange();
174       return true;
175     }
176   }
177 
178   return false;
179 }
180 
181 /// Check that the argument to __builtin_addressof is a glvalue, and set the
182 /// result type to the corresponding pointer type.
183 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
184   if (checkArgCount(S, TheCall, 1))
185     return true;
186 
187   ExprResult Arg(TheCall->getArg(0));
188   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
189   if (ResultType.isNull())
190     return true;
191 
192   TheCall->setArg(0, Arg.get());
193   TheCall->setType(ResultType);
194   return false;
195 }
196 
197 /// Check the number of arguments and set the result type to
198 /// the argument type.
199 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
200   if (checkArgCount(S, TheCall, 1))
201     return true;
202 
203   TheCall->setType(TheCall->getArg(0)->getType());
204   return false;
205 }
206 
207 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
208 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
209 /// type (but not a function pointer) and that the alignment is a power-of-two.
210 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
211   if (checkArgCount(S, TheCall, 2))
212     return true;
213 
214   clang::Expr *Source = TheCall->getArg(0);
215   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
216 
217   auto IsValidIntegerType = [](QualType Ty) {
218     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
219   };
220   QualType SrcTy = Source->getType();
221   // We should also be able to use it with arrays (but not functions!).
222   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
223     SrcTy = S.Context.getDecayedType(SrcTy);
224   }
225   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
226       SrcTy->isFunctionPointerType()) {
227     // FIXME: this is not quite the right error message since we don't allow
228     // floating point types, or member pointers.
229     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
230         << SrcTy;
231     return true;
232   }
233 
234   clang::Expr *AlignOp = TheCall->getArg(1);
235   if (!IsValidIntegerType(AlignOp->getType())) {
236     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
237         << AlignOp->getType();
238     return true;
239   }
240   Expr::EvalResult AlignResult;
241   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
242   // We can't check validity of alignment if it is value dependent.
243   if (!AlignOp->isValueDependent() &&
244       AlignOp->EvaluateAsInt(AlignResult, S.Context,
245                              Expr::SE_AllowSideEffects)) {
246     llvm::APSInt AlignValue = AlignResult.Val.getInt();
247     llvm::APSInt MaxValue(
248         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
249     if (AlignValue < 1) {
250       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
251       return true;
252     }
253     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
254       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
255           << MaxValue.toString(10);
256       return true;
257     }
258     if (!AlignValue.isPowerOf2()) {
259       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
260       return true;
261     }
262     if (AlignValue == 1) {
263       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
264           << IsBooleanAlignBuiltin;
265     }
266   }
267 
268   ExprResult SrcArg = S.PerformCopyInitialization(
269       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
270       SourceLocation(), Source);
271   if (SrcArg.isInvalid())
272     return true;
273   TheCall->setArg(0, SrcArg.get());
274   ExprResult AlignArg =
275       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
276                                       S.Context, AlignOp->getType(), false),
277                                   SourceLocation(), AlignOp);
278   if (AlignArg.isInvalid())
279     return true;
280   TheCall->setArg(1, AlignArg.get());
281   // For align_up/align_down, the return type is the same as the (potentially
282   // decayed) argument type including qualifiers. For is_aligned(), the result
283   // is always bool.
284   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
285   return false;
286 }
287 
288 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
289                                 unsigned BuiltinID) {
290   if (checkArgCount(S, TheCall, 3))
291     return true;
292 
293   // First two arguments should be integers.
294   for (unsigned I = 0; I < 2; ++I) {
295     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
296     if (Arg.isInvalid()) return true;
297     TheCall->setArg(I, Arg.get());
298 
299     QualType Ty = Arg.get()->getType();
300     if (!Ty->isIntegerType()) {
301       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
302           << Ty << Arg.get()->getSourceRange();
303       return true;
304     }
305   }
306 
307   // Third argument should be a pointer to a non-const integer.
308   // IRGen correctly handles volatile, restrict, and address spaces, and
309   // the other qualifiers aren't possible.
310   {
311     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
312     if (Arg.isInvalid()) return true;
313     TheCall->setArg(2, Arg.get());
314 
315     QualType Ty = Arg.get()->getType();
316     const auto *PtrTy = Ty->getAs<PointerType>();
317     if (!PtrTy ||
318         !PtrTy->getPointeeType()->isIntegerType() ||
319         PtrTy->getPointeeType().isConstQualified()) {
320       S.Diag(Arg.get()->getBeginLoc(),
321              diag::err_overflow_builtin_must_be_ptr_int)
322         << Ty << Arg.get()->getSourceRange();
323       return true;
324     }
325   }
326 
327   // Disallow signed ExtIntType args larger than 128 bits to mul function until
328   // we improve backend support.
329   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
330     for (unsigned I = 0; I < 3; ++I) {
331       const auto Arg = TheCall->getArg(I);
332       // Third argument will be a pointer.
333       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
334       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
335           S.getASTContext().getIntWidth(Ty) > 128)
336         return S.Diag(Arg->getBeginLoc(),
337                       diag::err_overflow_builtin_ext_int_max_size)
338                << 128;
339     }
340   }
341 
342   return false;
343 }
344 
345 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
346   if (checkArgCount(S, BuiltinCall, 2))
347     return true;
348 
349   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
350   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
351   Expr *Call = BuiltinCall->getArg(0);
352   Expr *Chain = BuiltinCall->getArg(1);
353 
354   if (Call->getStmtClass() != Stmt::CallExprClass) {
355     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
356         << Call->getSourceRange();
357     return true;
358   }
359 
360   auto CE = cast<CallExpr>(Call);
361   if (CE->getCallee()->getType()->isBlockPointerType()) {
362     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
363         << Call->getSourceRange();
364     return true;
365   }
366 
367   const Decl *TargetDecl = CE->getCalleeDecl();
368   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
369     if (FD->getBuiltinID()) {
370       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
371           << Call->getSourceRange();
372       return true;
373     }
374 
375   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
376     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
377         << Call->getSourceRange();
378     return true;
379   }
380 
381   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
382   if (ChainResult.isInvalid())
383     return true;
384   if (!ChainResult.get()->getType()->isPointerType()) {
385     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
386         << Chain->getSourceRange();
387     return true;
388   }
389 
390   QualType ReturnTy = CE->getCallReturnType(S.Context);
391   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
392   QualType BuiltinTy = S.Context.getFunctionType(
393       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
394   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
395 
396   Builtin =
397       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
398 
399   BuiltinCall->setType(CE->getType());
400   BuiltinCall->setValueKind(CE->getValueKind());
401   BuiltinCall->setObjectKind(CE->getObjectKind());
402   BuiltinCall->setCallee(Builtin);
403   BuiltinCall->setArg(1, ChainResult.get());
404 
405   return false;
406 }
407 
408 namespace {
409 
410 class EstimateSizeFormatHandler
411     : public analyze_format_string::FormatStringHandler {
412   size_t Size;
413 
414 public:
415   EstimateSizeFormatHandler(StringRef Format)
416       : Size(std::min(Format.find(0), Format.size()) +
417              1 /* null byte always written by sprintf */) {}
418 
419   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
420                              const char *, unsigned SpecifierLen) override {
421 
422     const size_t FieldWidth = computeFieldWidth(FS);
423     const size_t Precision = computePrecision(FS);
424 
425     // The actual format.
426     switch (FS.getConversionSpecifier().getKind()) {
427     // Just a char.
428     case analyze_format_string::ConversionSpecifier::cArg:
429     case analyze_format_string::ConversionSpecifier::CArg:
430       Size += std::max(FieldWidth, (size_t)1);
431       break;
432     // Just an integer.
433     case analyze_format_string::ConversionSpecifier::dArg:
434     case analyze_format_string::ConversionSpecifier::DArg:
435     case analyze_format_string::ConversionSpecifier::iArg:
436     case analyze_format_string::ConversionSpecifier::oArg:
437     case analyze_format_string::ConversionSpecifier::OArg:
438     case analyze_format_string::ConversionSpecifier::uArg:
439     case analyze_format_string::ConversionSpecifier::UArg:
440     case analyze_format_string::ConversionSpecifier::xArg:
441     case analyze_format_string::ConversionSpecifier::XArg:
442       Size += std::max(FieldWidth, Precision);
443       break;
444 
445     // %g style conversion switches between %f or %e style dynamically.
446     // %f always takes less space, so default to it.
447     case analyze_format_string::ConversionSpecifier::gArg:
448     case analyze_format_string::ConversionSpecifier::GArg:
449 
450     // Floating point number in the form '[+]ddd.ddd'.
451     case analyze_format_string::ConversionSpecifier::fArg:
452     case analyze_format_string::ConversionSpecifier::FArg:
453       Size += std::max(FieldWidth, 1 /* integer part */ +
454                                        (Precision ? 1 + Precision
455                                                   : 0) /* period + decimal */);
456       break;
457 
458     // Floating point number in the form '[-]d.ddde[+-]dd'.
459     case analyze_format_string::ConversionSpecifier::eArg:
460     case analyze_format_string::ConversionSpecifier::EArg:
461       Size +=
462           std::max(FieldWidth,
463                    1 /* integer part */ +
464                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
465                        1 /* e or E letter */ + 2 /* exponent */);
466       break;
467 
468     // Floating point number in the form '[-]0xh.hhhhp±dd'.
469     case analyze_format_string::ConversionSpecifier::aArg:
470     case analyze_format_string::ConversionSpecifier::AArg:
471       Size +=
472           std::max(FieldWidth,
473                    2 /* 0x */ + 1 /* integer part */ +
474                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
475                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
476       break;
477 
478     // Just a string.
479     case analyze_format_string::ConversionSpecifier::sArg:
480     case analyze_format_string::ConversionSpecifier::SArg:
481       Size += FieldWidth;
482       break;
483 
484     // Just a pointer in the form '0xddd'.
485     case analyze_format_string::ConversionSpecifier::pArg:
486       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
487       break;
488 
489     // A plain percent.
490     case analyze_format_string::ConversionSpecifier::PercentArg:
491       Size += 1;
492       break;
493 
494     default:
495       break;
496     }
497 
498     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
499 
500     if (FS.hasAlternativeForm()) {
501       switch (FS.getConversionSpecifier().getKind()) {
502       default:
503         break;
504       // Force a leading '0'.
505       case analyze_format_string::ConversionSpecifier::oArg:
506         Size += 1;
507         break;
508       // Force a leading '0x'.
509       case analyze_format_string::ConversionSpecifier::xArg:
510       case analyze_format_string::ConversionSpecifier::XArg:
511         Size += 2;
512         break;
513       // Force a period '.' before decimal, even if precision is 0.
514       case analyze_format_string::ConversionSpecifier::aArg:
515       case analyze_format_string::ConversionSpecifier::AArg:
516       case analyze_format_string::ConversionSpecifier::eArg:
517       case analyze_format_string::ConversionSpecifier::EArg:
518       case analyze_format_string::ConversionSpecifier::fArg:
519       case analyze_format_string::ConversionSpecifier::FArg:
520       case analyze_format_string::ConversionSpecifier::gArg:
521       case analyze_format_string::ConversionSpecifier::GArg:
522         Size += (Precision ? 0 : 1);
523         break;
524       }
525     }
526     assert(SpecifierLen <= Size && "no underflow");
527     Size -= SpecifierLen;
528     return true;
529   }
530 
531   size_t getSizeLowerBound() const { return Size; }
532 
533 private:
534   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
535     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
536     size_t FieldWidth = 0;
537     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
538       FieldWidth = FW.getConstantAmount();
539     return FieldWidth;
540   }
541 
542   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
543     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
544     size_t Precision = 0;
545 
546     // See man 3 printf for default precision value based on the specifier.
547     switch (FW.getHowSpecified()) {
548     case analyze_format_string::OptionalAmount::NotSpecified:
549       switch (FS.getConversionSpecifier().getKind()) {
550       default:
551         break;
552       case analyze_format_string::ConversionSpecifier::dArg: // %d
553       case analyze_format_string::ConversionSpecifier::DArg: // %D
554       case analyze_format_string::ConversionSpecifier::iArg: // %i
555         Precision = 1;
556         break;
557       case analyze_format_string::ConversionSpecifier::oArg: // %d
558       case analyze_format_string::ConversionSpecifier::OArg: // %D
559       case analyze_format_string::ConversionSpecifier::uArg: // %d
560       case analyze_format_string::ConversionSpecifier::UArg: // %D
561       case analyze_format_string::ConversionSpecifier::xArg: // %d
562       case analyze_format_string::ConversionSpecifier::XArg: // %D
563         Precision = 1;
564         break;
565       case analyze_format_string::ConversionSpecifier::fArg: // %f
566       case analyze_format_string::ConversionSpecifier::FArg: // %F
567       case analyze_format_string::ConversionSpecifier::eArg: // %e
568       case analyze_format_string::ConversionSpecifier::EArg: // %E
569       case analyze_format_string::ConversionSpecifier::gArg: // %g
570       case analyze_format_string::ConversionSpecifier::GArg: // %G
571         Precision = 6;
572         break;
573       case analyze_format_string::ConversionSpecifier::pArg: // %d
574         Precision = 1;
575         break;
576       }
577       break;
578     case analyze_format_string::OptionalAmount::Constant:
579       Precision = FW.getConstantAmount();
580       break;
581     default:
582       break;
583     }
584     return Precision;
585   }
586 };
587 
588 } // namespace
589 
590 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
591 /// __builtin_*_chk function, then use the object size argument specified in the
592 /// source. Otherwise, infer the object size using __builtin_object_size.
593 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
594                                                CallExpr *TheCall) {
595   // FIXME: There are some more useful checks we could be doing here:
596   //  - Evaluate strlen of strcpy arguments, use as object size.
597 
598   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
599       isConstantEvaluated())
600     return;
601 
602   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
603   if (!BuiltinID)
604     return;
605 
606   const TargetInfo &TI = getASTContext().getTargetInfo();
607   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
608 
609   unsigned DiagID = 0;
610   bool IsChkVariant = false;
611   Optional<llvm::APSInt> UsedSize;
612   unsigned SizeIndex, ObjectIndex;
613   switch (BuiltinID) {
614   default:
615     return;
616   case Builtin::BIsprintf:
617   case Builtin::BI__builtin___sprintf_chk: {
618     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
619     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
620 
621     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
622 
623       if (!Format->isAscii() && !Format->isUTF8())
624         return;
625 
626       StringRef FormatStrRef = Format->getString();
627       EstimateSizeFormatHandler H(FormatStrRef);
628       const char *FormatBytes = FormatStrRef.data();
629       const ConstantArrayType *T =
630           Context.getAsConstantArrayType(Format->getType());
631       assert(T && "String literal not of constant array type!");
632       size_t TypeSize = T->getSize().getZExtValue();
633 
634       // In case there's a null byte somewhere.
635       size_t StrLen =
636           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
637       if (!analyze_format_string::ParsePrintfString(
638               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
639               Context.getTargetInfo(), false)) {
640         DiagID = diag::warn_fortify_source_format_overflow;
641         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
642                        .extOrTrunc(SizeTypeWidth);
643         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
644           IsChkVariant = true;
645           ObjectIndex = 2;
646         } else {
647           IsChkVariant = false;
648           ObjectIndex = 0;
649         }
650         break;
651       }
652     }
653     return;
654   }
655   case Builtin::BI__builtin___memcpy_chk:
656   case Builtin::BI__builtin___memmove_chk:
657   case Builtin::BI__builtin___memset_chk:
658   case Builtin::BI__builtin___strlcat_chk:
659   case Builtin::BI__builtin___strlcpy_chk:
660   case Builtin::BI__builtin___strncat_chk:
661   case Builtin::BI__builtin___strncpy_chk:
662   case Builtin::BI__builtin___stpncpy_chk:
663   case Builtin::BI__builtin___memccpy_chk:
664   case Builtin::BI__builtin___mempcpy_chk: {
665     DiagID = diag::warn_builtin_chk_overflow;
666     IsChkVariant = true;
667     SizeIndex = TheCall->getNumArgs() - 2;
668     ObjectIndex = TheCall->getNumArgs() - 1;
669     break;
670   }
671 
672   case Builtin::BI__builtin___snprintf_chk:
673   case Builtin::BI__builtin___vsnprintf_chk: {
674     DiagID = diag::warn_builtin_chk_overflow;
675     IsChkVariant = true;
676     SizeIndex = 1;
677     ObjectIndex = 3;
678     break;
679   }
680 
681   case Builtin::BIstrncat:
682   case Builtin::BI__builtin_strncat:
683   case Builtin::BIstrncpy:
684   case Builtin::BI__builtin_strncpy:
685   case Builtin::BIstpncpy:
686   case Builtin::BI__builtin_stpncpy: {
687     // Whether these functions overflow depends on the runtime strlen of the
688     // string, not just the buffer size, so emitting the "always overflow"
689     // diagnostic isn't quite right. We should still diagnose passing a buffer
690     // size larger than the destination buffer though; this is a runtime abort
691     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
692     DiagID = diag::warn_fortify_source_size_mismatch;
693     SizeIndex = TheCall->getNumArgs() - 1;
694     ObjectIndex = 0;
695     break;
696   }
697 
698   case Builtin::BImemcpy:
699   case Builtin::BI__builtin_memcpy:
700   case Builtin::BImemmove:
701   case Builtin::BI__builtin_memmove:
702   case Builtin::BImemset:
703   case Builtin::BI__builtin_memset:
704   case Builtin::BImempcpy:
705   case Builtin::BI__builtin_mempcpy: {
706     DiagID = diag::warn_fortify_source_overflow;
707     SizeIndex = TheCall->getNumArgs() - 1;
708     ObjectIndex = 0;
709     break;
710   }
711   case Builtin::BIsnprintf:
712   case Builtin::BI__builtin_snprintf:
713   case Builtin::BIvsnprintf:
714   case Builtin::BI__builtin_vsnprintf: {
715     DiagID = diag::warn_fortify_source_size_mismatch;
716     SizeIndex = 1;
717     ObjectIndex = 0;
718     break;
719   }
720   }
721 
722   llvm::APSInt ObjectSize;
723   // For __builtin___*_chk, the object size is explicitly provided by the caller
724   // (usually using __builtin_object_size). Use that value to check this call.
725   if (IsChkVariant) {
726     Expr::EvalResult Result;
727     Expr *SizeArg = TheCall->getArg(ObjectIndex);
728     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
729       return;
730     ObjectSize = Result.Val.getInt();
731 
732   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
733   } else {
734     // If the parameter has a pass_object_size attribute, then we should use its
735     // (potentially) more strict checking mode. Otherwise, conservatively assume
736     // type 0.
737     int BOSType = 0;
738     if (const auto *POS =
739             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
740       BOSType = POS->getType();
741 
742     Expr *ObjArg = TheCall->getArg(ObjectIndex);
743     uint64_t Result;
744     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
745       return;
746     // Get the object size in the target's size_t width.
747     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
748   }
749 
750   // Evaluate the number of bytes of the object that this call will use.
751   if (!UsedSize) {
752     Expr::EvalResult Result;
753     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
754     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
755       return;
756     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
757   }
758 
759   if (UsedSize.getValue().ule(ObjectSize))
760     return;
761 
762   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
763   // Skim off the details of whichever builtin was called to produce a better
764   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
765   if (IsChkVariant) {
766     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
767     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
768   } else if (FunctionName.startswith("__builtin_")) {
769     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
770   }
771 
772   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
773                       PDiag(DiagID)
774                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
775                           << UsedSize.getValue().toString(/*Radix=*/10));
776 }
777 
778 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
779                                      Scope::ScopeFlags NeededScopeFlags,
780                                      unsigned DiagID) {
781   // Scopes aren't available during instantiation. Fortunately, builtin
782   // functions cannot be template args so they cannot be formed through template
783   // instantiation. Therefore checking once during the parse is sufficient.
784   if (SemaRef.inTemplateInstantiation())
785     return false;
786 
787   Scope *S = SemaRef.getCurScope();
788   while (S && !S->isSEHExceptScope())
789     S = S->getParent();
790   if (!S || !(S->getFlags() & NeededScopeFlags)) {
791     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
792     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
793         << DRE->getDecl()->getIdentifier();
794     return true;
795   }
796 
797   return false;
798 }
799 
800 static inline bool isBlockPointer(Expr *Arg) {
801   return Arg->getType()->isBlockPointerType();
802 }
803 
804 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
805 /// void*, which is a requirement of device side enqueue.
806 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
807   const BlockPointerType *BPT =
808       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
809   ArrayRef<QualType> Params =
810       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
811   unsigned ArgCounter = 0;
812   bool IllegalParams = false;
813   // Iterate through the block parameters until either one is found that is not
814   // a local void*, or the block is valid.
815   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
816        I != E; ++I, ++ArgCounter) {
817     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
818         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
819             LangAS::opencl_local) {
820       // Get the location of the error. If a block literal has been passed
821       // (BlockExpr) then we can point straight to the offending argument,
822       // else we just point to the variable reference.
823       SourceLocation ErrorLoc;
824       if (isa<BlockExpr>(BlockArg)) {
825         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
826         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
827       } else if (isa<DeclRefExpr>(BlockArg)) {
828         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
829       }
830       S.Diag(ErrorLoc,
831              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
832       IllegalParams = true;
833     }
834   }
835 
836   return IllegalParams;
837 }
838 
839 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
840   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
841     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
842         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
843     return true;
844   }
845   return false;
846 }
847 
848 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
849   if (checkArgCount(S, TheCall, 2))
850     return true;
851 
852   if (checkOpenCLSubgroupExt(S, TheCall))
853     return true;
854 
855   // First argument is an ndrange_t type.
856   Expr *NDRangeArg = TheCall->getArg(0);
857   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
858     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
859         << TheCall->getDirectCallee() << "'ndrange_t'";
860     return true;
861   }
862 
863   Expr *BlockArg = TheCall->getArg(1);
864   if (!isBlockPointer(BlockArg)) {
865     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
866         << TheCall->getDirectCallee() << "block";
867     return true;
868   }
869   return checkOpenCLBlockArgs(S, BlockArg);
870 }
871 
872 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
873 /// get_kernel_work_group_size
874 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
875 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
876   if (checkArgCount(S, TheCall, 1))
877     return true;
878 
879   Expr *BlockArg = TheCall->getArg(0);
880   if (!isBlockPointer(BlockArg)) {
881     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
882         << TheCall->getDirectCallee() << "block";
883     return true;
884   }
885   return checkOpenCLBlockArgs(S, BlockArg);
886 }
887 
888 /// Diagnose integer type and any valid implicit conversion to it.
889 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
890                                       const QualType &IntType);
891 
892 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
893                                             unsigned Start, unsigned End) {
894   bool IllegalParams = false;
895   for (unsigned I = Start; I <= End; ++I)
896     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
897                                               S.Context.getSizeType());
898   return IllegalParams;
899 }
900 
901 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
902 /// 'local void*' parameter of passed block.
903 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
904                                            Expr *BlockArg,
905                                            unsigned NumNonVarArgs) {
906   const BlockPointerType *BPT =
907       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
908   unsigned NumBlockParams =
909       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
910   unsigned TotalNumArgs = TheCall->getNumArgs();
911 
912   // For each argument passed to the block, a corresponding uint needs to
913   // be passed to describe the size of the local memory.
914   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
915     S.Diag(TheCall->getBeginLoc(),
916            diag::err_opencl_enqueue_kernel_local_size_args);
917     return true;
918   }
919 
920   // Check that the sizes of the local memory are specified by integers.
921   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
922                                          TotalNumArgs - 1);
923 }
924 
925 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
926 /// overload formats specified in Table 6.13.17.1.
927 /// int enqueue_kernel(queue_t queue,
928 ///                    kernel_enqueue_flags_t flags,
929 ///                    const ndrange_t ndrange,
930 ///                    void (^block)(void))
931 /// int enqueue_kernel(queue_t queue,
932 ///                    kernel_enqueue_flags_t flags,
933 ///                    const ndrange_t ndrange,
934 ///                    uint num_events_in_wait_list,
935 ///                    clk_event_t *event_wait_list,
936 ///                    clk_event_t *event_ret,
937 ///                    void (^block)(void))
938 /// int enqueue_kernel(queue_t queue,
939 ///                    kernel_enqueue_flags_t flags,
940 ///                    const ndrange_t ndrange,
941 ///                    void (^block)(local void*, ...),
942 ///                    uint size0, ...)
943 /// int enqueue_kernel(queue_t queue,
944 ///                    kernel_enqueue_flags_t flags,
945 ///                    const ndrange_t ndrange,
946 ///                    uint num_events_in_wait_list,
947 ///                    clk_event_t *event_wait_list,
948 ///                    clk_event_t *event_ret,
949 ///                    void (^block)(local void*, ...),
950 ///                    uint size0, ...)
951 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
952   unsigned NumArgs = TheCall->getNumArgs();
953 
954   if (NumArgs < 4) {
955     S.Diag(TheCall->getBeginLoc(),
956            diag::err_typecheck_call_too_few_args_at_least)
957         << 0 << 4 << NumArgs;
958     return true;
959   }
960 
961   Expr *Arg0 = TheCall->getArg(0);
962   Expr *Arg1 = TheCall->getArg(1);
963   Expr *Arg2 = TheCall->getArg(2);
964   Expr *Arg3 = TheCall->getArg(3);
965 
966   // First argument always needs to be a queue_t type.
967   if (!Arg0->getType()->isQueueT()) {
968     S.Diag(TheCall->getArg(0)->getBeginLoc(),
969            diag::err_opencl_builtin_expected_type)
970         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
971     return true;
972   }
973 
974   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
975   if (!Arg1->getType()->isIntegerType()) {
976     S.Diag(TheCall->getArg(1)->getBeginLoc(),
977            diag::err_opencl_builtin_expected_type)
978         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
979     return true;
980   }
981 
982   // Third argument is always an ndrange_t type.
983   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
984     S.Diag(TheCall->getArg(2)->getBeginLoc(),
985            diag::err_opencl_builtin_expected_type)
986         << TheCall->getDirectCallee() << "'ndrange_t'";
987     return true;
988   }
989 
990   // With four arguments, there is only one form that the function could be
991   // called in: no events and no variable arguments.
992   if (NumArgs == 4) {
993     // check that the last argument is the right block type.
994     if (!isBlockPointer(Arg3)) {
995       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
996           << TheCall->getDirectCallee() << "block";
997       return true;
998     }
999     // we have a block type, check the prototype
1000     const BlockPointerType *BPT =
1001         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1002     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1003       S.Diag(Arg3->getBeginLoc(),
1004              diag::err_opencl_enqueue_kernel_blocks_no_args);
1005       return true;
1006     }
1007     return false;
1008   }
1009   // we can have block + varargs.
1010   if (isBlockPointer(Arg3))
1011     return (checkOpenCLBlockArgs(S, Arg3) ||
1012             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1013   // last two cases with either exactly 7 args or 7 args and varargs.
1014   if (NumArgs >= 7) {
1015     // check common block argument.
1016     Expr *Arg6 = TheCall->getArg(6);
1017     if (!isBlockPointer(Arg6)) {
1018       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1019           << TheCall->getDirectCallee() << "block";
1020       return true;
1021     }
1022     if (checkOpenCLBlockArgs(S, Arg6))
1023       return true;
1024 
1025     // Forth argument has to be any integer type.
1026     if (!Arg3->getType()->isIntegerType()) {
1027       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1028              diag::err_opencl_builtin_expected_type)
1029           << TheCall->getDirectCallee() << "integer";
1030       return true;
1031     }
1032     // check remaining common arguments.
1033     Expr *Arg4 = TheCall->getArg(4);
1034     Expr *Arg5 = TheCall->getArg(5);
1035 
1036     // Fifth argument is always passed as a pointer to clk_event_t.
1037     if (!Arg4->isNullPointerConstant(S.Context,
1038                                      Expr::NPC_ValueDependentIsNotNull) &&
1039         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1040       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1041              diag::err_opencl_builtin_expected_type)
1042           << TheCall->getDirectCallee()
1043           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1044       return true;
1045     }
1046 
1047     // Sixth argument is always passed as a pointer to clk_event_t.
1048     if (!Arg5->isNullPointerConstant(S.Context,
1049                                      Expr::NPC_ValueDependentIsNotNull) &&
1050         !(Arg5->getType()->isPointerType() &&
1051           Arg5->getType()->getPointeeType()->isClkEventT())) {
1052       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1053              diag::err_opencl_builtin_expected_type)
1054           << TheCall->getDirectCallee()
1055           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1056       return true;
1057     }
1058 
1059     if (NumArgs == 7)
1060       return false;
1061 
1062     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1063   }
1064 
1065   // None of the specific case has been detected, give generic error
1066   S.Diag(TheCall->getBeginLoc(),
1067          diag::err_opencl_enqueue_kernel_incorrect_args);
1068   return true;
1069 }
1070 
1071 /// Returns OpenCL access qual.
1072 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1073     return D->getAttr<OpenCLAccessAttr>();
1074 }
1075 
1076 /// Returns true if pipe element type is different from the pointer.
1077 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1078   const Expr *Arg0 = Call->getArg(0);
1079   // First argument type should always be pipe.
1080   if (!Arg0->getType()->isPipeType()) {
1081     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1082         << Call->getDirectCallee() << Arg0->getSourceRange();
1083     return true;
1084   }
1085   OpenCLAccessAttr *AccessQual =
1086       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1087   // Validates the access qualifier is compatible with the call.
1088   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1089   // read_only and write_only, and assumed to be read_only if no qualifier is
1090   // specified.
1091   switch (Call->getDirectCallee()->getBuiltinID()) {
1092   case Builtin::BIread_pipe:
1093   case Builtin::BIreserve_read_pipe:
1094   case Builtin::BIcommit_read_pipe:
1095   case Builtin::BIwork_group_reserve_read_pipe:
1096   case Builtin::BIsub_group_reserve_read_pipe:
1097   case Builtin::BIwork_group_commit_read_pipe:
1098   case Builtin::BIsub_group_commit_read_pipe:
1099     if (!(!AccessQual || AccessQual->isReadOnly())) {
1100       S.Diag(Arg0->getBeginLoc(),
1101              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1102           << "read_only" << Arg0->getSourceRange();
1103       return true;
1104     }
1105     break;
1106   case Builtin::BIwrite_pipe:
1107   case Builtin::BIreserve_write_pipe:
1108   case Builtin::BIcommit_write_pipe:
1109   case Builtin::BIwork_group_reserve_write_pipe:
1110   case Builtin::BIsub_group_reserve_write_pipe:
1111   case Builtin::BIwork_group_commit_write_pipe:
1112   case Builtin::BIsub_group_commit_write_pipe:
1113     if (!(AccessQual && AccessQual->isWriteOnly())) {
1114       S.Diag(Arg0->getBeginLoc(),
1115              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1116           << "write_only" << Arg0->getSourceRange();
1117       return true;
1118     }
1119     break;
1120   default:
1121     break;
1122   }
1123   return false;
1124 }
1125 
1126 /// Returns true if pipe element type is different from the pointer.
1127 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1128   const Expr *Arg0 = Call->getArg(0);
1129   const Expr *ArgIdx = Call->getArg(Idx);
1130   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1131   const QualType EltTy = PipeTy->getElementType();
1132   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1133   // The Idx argument should be a pointer and the type of the pointer and
1134   // the type of pipe element should also be the same.
1135   if (!ArgTy ||
1136       !S.Context.hasSameType(
1137           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1138     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1139         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1140         << ArgIdx->getType() << ArgIdx->getSourceRange();
1141     return true;
1142   }
1143   return false;
1144 }
1145 
1146 // Performs semantic analysis for the read/write_pipe call.
1147 // \param S Reference to the semantic analyzer.
1148 // \param Call A pointer to the builtin call.
1149 // \return True if a semantic error has been found, false otherwise.
1150 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1151   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1152   // functions have two forms.
1153   switch (Call->getNumArgs()) {
1154   case 2:
1155     if (checkOpenCLPipeArg(S, Call))
1156       return true;
1157     // The call with 2 arguments should be
1158     // read/write_pipe(pipe T, T*).
1159     // Check packet type T.
1160     if (checkOpenCLPipePacketType(S, Call, 1))
1161       return true;
1162     break;
1163 
1164   case 4: {
1165     if (checkOpenCLPipeArg(S, Call))
1166       return true;
1167     // The call with 4 arguments should be
1168     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1169     // Check reserve_id_t.
1170     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1171       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1172           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1173           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1174       return true;
1175     }
1176 
1177     // Check the index.
1178     const Expr *Arg2 = Call->getArg(2);
1179     if (!Arg2->getType()->isIntegerType() &&
1180         !Arg2->getType()->isUnsignedIntegerType()) {
1181       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1182           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1183           << Arg2->getType() << Arg2->getSourceRange();
1184       return true;
1185     }
1186 
1187     // Check packet type T.
1188     if (checkOpenCLPipePacketType(S, Call, 3))
1189       return true;
1190   } break;
1191   default:
1192     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1193         << Call->getDirectCallee() << Call->getSourceRange();
1194     return true;
1195   }
1196 
1197   return false;
1198 }
1199 
1200 // Performs a semantic analysis on the {work_group_/sub_group_
1201 //        /_}reserve_{read/write}_pipe
1202 // \param S Reference to the semantic analyzer.
1203 // \param Call The call to the builtin function to be analyzed.
1204 // \return True if a semantic error was found, false otherwise.
1205 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1206   if (checkArgCount(S, Call, 2))
1207     return true;
1208 
1209   if (checkOpenCLPipeArg(S, Call))
1210     return true;
1211 
1212   // Check the reserve size.
1213   if (!Call->getArg(1)->getType()->isIntegerType() &&
1214       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1215     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1216         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1217         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1218     return true;
1219   }
1220 
1221   // Since return type of reserve_read/write_pipe built-in function is
1222   // reserve_id_t, which is not defined in the builtin def file , we used int
1223   // as return type and need to override the return type of these functions.
1224   Call->setType(S.Context.OCLReserveIDTy);
1225 
1226   return false;
1227 }
1228 
1229 // Performs a semantic analysis on {work_group_/sub_group_
1230 //        /_}commit_{read/write}_pipe
1231 // \param S Reference to the semantic analyzer.
1232 // \param Call The call to the builtin function to be analyzed.
1233 // \return True if a semantic error was found, false otherwise.
1234 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1235   if (checkArgCount(S, Call, 2))
1236     return true;
1237 
1238   if (checkOpenCLPipeArg(S, Call))
1239     return true;
1240 
1241   // Check reserve_id_t.
1242   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1243     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1244         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1245         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1246     return true;
1247   }
1248 
1249   return false;
1250 }
1251 
1252 // Performs a semantic analysis on the call to built-in Pipe
1253 //        Query Functions.
1254 // \param S Reference to the semantic analyzer.
1255 // \param Call The call to the builtin function to be analyzed.
1256 // \return True if a semantic error was found, false otherwise.
1257 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1258   if (checkArgCount(S, Call, 1))
1259     return true;
1260 
1261   if (!Call->getArg(0)->getType()->isPipeType()) {
1262     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1263         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1264     return true;
1265   }
1266 
1267   return false;
1268 }
1269 
1270 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1271 // Performs semantic analysis for the to_global/local/private call.
1272 // \param S Reference to the semantic analyzer.
1273 // \param BuiltinID ID of the builtin function.
1274 // \param Call A pointer to the builtin call.
1275 // \return True if a semantic error has been found, false otherwise.
1276 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1277                                     CallExpr *Call) {
1278   if (checkArgCount(S, Call, 1))
1279     return true;
1280 
1281   auto RT = Call->getArg(0)->getType();
1282   if (!RT->isPointerType() || RT->getPointeeType()
1283       .getAddressSpace() == LangAS::opencl_constant) {
1284     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1285         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1286     return true;
1287   }
1288 
1289   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1290     S.Diag(Call->getArg(0)->getBeginLoc(),
1291            diag::warn_opencl_generic_address_space_arg)
1292         << Call->getDirectCallee()->getNameInfo().getAsString()
1293         << Call->getArg(0)->getSourceRange();
1294   }
1295 
1296   RT = RT->getPointeeType();
1297   auto Qual = RT.getQualifiers();
1298   switch (BuiltinID) {
1299   case Builtin::BIto_global:
1300     Qual.setAddressSpace(LangAS::opencl_global);
1301     break;
1302   case Builtin::BIto_local:
1303     Qual.setAddressSpace(LangAS::opencl_local);
1304     break;
1305   case Builtin::BIto_private:
1306     Qual.setAddressSpace(LangAS::opencl_private);
1307     break;
1308   default:
1309     llvm_unreachable("Invalid builtin function");
1310   }
1311   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1312       RT.getUnqualifiedType(), Qual)));
1313 
1314   return false;
1315 }
1316 
1317 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1318   if (checkArgCount(S, TheCall, 1))
1319     return ExprError();
1320 
1321   // Compute __builtin_launder's parameter type from the argument.
1322   // The parameter type is:
1323   //  * The type of the argument if it's not an array or function type,
1324   //  Otherwise,
1325   //  * The decayed argument type.
1326   QualType ParamTy = [&]() {
1327     QualType ArgTy = TheCall->getArg(0)->getType();
1328     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1329       return S.Context.getPointerType(Ty->getElementType());
1330     if (ArgTy->isFunctionType()) {
1331       return S.Context.getPointerType(ArgTy);
1332     }
1333     return ArgTy;
1334   }();
1335 
1336   TheCall->setType(ParamTy);
1337 
1338   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1339     if (!ParamTy->isPointerType())
1340       return 0;
1341     if (ParamTy->isFunctionPointerType())
1342       return 1;
1343     if (ParamTy->isVoidPointerType())
1344       return 2;
1345     return llvm::Optional<unsigned>{};
1346   }();
1347   if (DiagSelect.hasValue()) {
1348     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1349         << DiagSelect.getValue() << TheCall->getSourceRange();
1350     return ExprError();
1351   }
1352 
1353   // We either have an incomplete class type, or we have a class template
1354   // whose instantiation has not been forced. Example:
1355   //
1356   //   template <class T> struct Foo { T value; };
1357   //   Foo<int> *p = nullptr;
1358   //   auto *d = __builtin_launder(p);
1359   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1360                             diag::err_incomplete_type))
1361     return ExprError();
1362 
1363   assert(ParamTy->getPointeeType()->isObjectType() &&
1364          "Unhandled non-object pointer case");
1365 
1366   InitializedEntity Entity =
1367       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1368   ExprResult Arg =
1369       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1370   if (Arg.isInvalid())
1371     return ExprError();
1372   TheCall->setArg(0, Arg.get());
1373 
1374   return TheCall;
1375 }
1376 
1377 // Emit an error and return true if the current architecture is not in the list
1378 // of supported architectures.
1379 static bool
1380 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1381                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1382   llvm::Triple::ArchType CurArch =
1383       S.getASTContext().getTargetInfo().getTriple().getArch();
1384   if (llvm::is_contained(SupportedArchs, CurArch))
1385     return false;
1386   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1387       << TheCall->getSourceRange();
1388   return true;
1389 }
1390 
1391 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1392                                  SourceLocation CallSiteLoc);
1393 
1394 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1395                                       CallExpr *TheCall) {
1396   switch (TI.getTriple().getArch()) {
1397   default:
1398     // Some builtins don't require additional checking, so just consider these
1399     // acceptable.
1400     return false;
1401   case llvm::Triple::arm:
1402   case llvm::Triple::armeb:
1403   case llvm::Triple::thumb:
1404   case llvm::Triple::thumbeb:
1405     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1406   case llvm::Triple::aarch64:
1407   case llvm::Triple::aarch64_32:
1408   case llvm::Triple::aarch64_be:
1409     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1410   case llvm::Triple::bpfeb:
1411   case llvm::Triple::bpfel:
1412     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1413   case llvm::Triple::hexagon:
1414     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1415   case llvm::Triple::mips:
1416   case llvm::Triple::mipsel:
1417   case llvm::Triple::mips64:
1418   case llvm::Triple::mips64el:
1419     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1420   case llvm::Triple::systemz:
1421     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1422   case llvm::Triple::x86:
1423   case llvm::Triple::x86_64:
1424     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::ppc:
1426   case llvm::Triple::ppcle:
1427   case llvm::Triple::ppc64:
1428   case llvm::Triple::ppc64le:
1429     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1430   case llvm::Triple::amdgcn:
1431     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1432   case llvm::Triple::riscv32:
1433   case llvm::Triple::riscv64:
1434     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   }
1436 }
1437 
1438 ExprResult
1439 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1440                                CallExpr *TheCall) {
1441   ExprResult TheCallResult(TheCall);
1442 
1443   // Find out if any arguments are required to be integer constant expressions.
1444   unsigned ICEArguments = 0;
1445   ASTContext::GetBuiltinTypeError Error;
1446   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1447   if (Error != ASTContext::GE_None)
1448     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1449 
1450   // If any arguments are required to be ICE's, check and diagnose.
1451   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1452     // Skip arguments not required to be ICE's.
1453     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1454 
1455     llvm::APSInt Result;
1456     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1457       return true;
1458     ICEArguments &= ~(1 << ArgNo);
1459   }
1460 
1461   switch (BuiltinID) {
1462   case Builtin::BI__builtin___CFStringMakeConstantString:
1463     assert(TheCall->getNumArgs() == 1 &&
1464            "Wrong # arguments to builtin CFStringMakeConstantString");
1465     if (CheckObjCString(TheCall->getArg(0)))
1466       return ExprError();
1467     break;
1468   case Builtin::BI__builtin_ms_va_start:
1469   case Builtin::BI__builtin_stdarg_start:
1470   case Builtin::BI__builtin_va_start:
1471     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1472       return ExprError();
1473     break;
1474   case Builtin::BI__va_start: {
1475     switch (Context.getTargetInfo().getTriple().getArch()) {
1476     case llvm::Triple::aarch64:
1477     case llvm::Triple::arm:
1478     case llvm::Triple::thumb:
1479       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1480         return ExprError();
1481       break;
1482     default:
1483       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1484         return ExprError();
1485       break;
1486     }
1487     break;
1488   }
1489 
1490   // The acquire, release, and no fence variants are ARM and AArch64 only.
1491   case Builtin::BI_interlockedbittestandset_acq:
1492   case Builtin::BI_interlockedbittestandset_rel:
1493   case Builtin::BI_interlockedbittestandset_nf:
1494   case Builtin::BI_interlockedbittestandreset_acq:
1495   case Builtin::BI_interlockedbittestandreset_rel:
1496   case Builtin::BI_interlockedbittestandreset_nf:
1497     if (CheckBuiltinTargetSupport(
1498             *this, BuiltinID, TheCall,
1499             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1500       return ExprError();
1501     break;
1502 
1503   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1504   case Builtin::BI_bittest64:
1505   case Builtin::BI_bittestandcomplement64:
1506   case Builtin::BI_bittestandreset64:
1507   case Builtin::BI_bittestandset64:
1508   case Builtin::BI_interlockedbittestandreset64:
1509   case Builtin::BI_interlockedbittestandset64:
1510     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1511                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1512                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1513       return ExprError();
1514     break;
1515 
1516   case Builtin::BI__builtin_isgreater:
1517   case Builtin::BI__builtin_isgreaterequal:
1518   case Builtin::BI__builtin_isless:
1519   case Builtin::BI__builtin_islessequal:
1520   case Builtin::BI__builtin_islessgreater:
1521   case Builtin::BI__builtin_isunordered:
1522     if (SemaBuiltinUnorderedCompare(TheCall))
1523       return ExprError();
1524     break;
1525   case Builtin::BI__builtin_fpclassify:
1526     if (SemaBuiltinFPClassification(TheCall, 6))
1527       return ExprError();
1528     break;
1529   case Builtin::BI__builtin_isfinite:
1530   case Builtin::BI__builtin_isinf:
1531   case Builtin::BI__builtin_isinf_sign:
1532   case Builtin::BI__builtin_isnan:
1533   case Builtin::BI__builtin_isnormal:
1534   case Builtin::BI__builtin_signbit:
1535   case Builtin::BI__builtin_signbitf:
1536   case Builtin::BI__builtin_signbitl:
1537     if (SemaBuiltinFPClassification(TheCall, 1))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_shufflevector:
1541     return SemaBuiltinShuffleVector(TheCall);
1542     // TheCall will be freed by the smart pointer here, but that's fine, since
1543     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1544   case Builtin::BI__builtin_prefetch:
1545     if (SemaBuiltinPrefetch(TheCall))
1546       return ExprError();
1547     break;
1548   case Builtin::BI__builtin_alloca_with_align:
1549     if (SemaBuiltinAllocaWithAlign(TheCall))
1550       return ExprError();
1551     LLVM_FALLTHROUGH;
1552   case Builtin::BI__builtin_alloca:
1553     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1554         << TheCall->getDirectCallee();
1555     break;
1556   case Builtin::BI__assume:
1557   case Builtin::BI__builtin_assume:
1558     if (SemaBuiltinAssume(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__builtin_assume_aligned:
1562     if (SemaBuiltinAssumeAligned(TheCall))
1563       return ExprError();
1564     break;
1565   case Builtin::BI__builtin_dynamic_object_size:
1566   case Builtin::BI__builtin_object_size:
1567     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_longjmp:
1571     if (SemaBuiltinLongjmp(TheCall))
1572       return ExprError();
1573     break;
1574   case Builtin::BI__builtin_setjmp:
1575     if (SemaBuiltinSetjmp(TheCall))
1576       return ExprError();
1577     break;
1578   case Builtin::BI__builtin_classify_type:
1579     if (checkArgCount(*this, TheCall, 1)) return true;
1580     TheCall->setType(Context.IntTy);
1581     break;
1582   case Builtin::BI__builtin_complex:
1583     if (SemaBuiltinComplex(TheCall))
1584       return ExprError();
1585     break;
1586   case Builtin::BI__builtin_constant_p: {
1587     if (checkArgCount(*this, TheCall, 1)) return true;
1588     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1589     if (Arg.isInvalid()) return true;
1590     TheCall->setArg(0, Arg.get());
1591     TheCall->setType(Context.IntTy);
1592     break;
1593   }
1594   case Builtin::BI__builtin_launder:
1595     return SemaBuiltinLaunder(*this, TheCall);
1596   case Builtin::BI__sync_fetch_and_add:
1597   case Builtin::BI__sync_fetch_and_add_1:
1598   case Builtin::BI__sync_fetch_and_add_2:
1599   case Builtin::BI__sync_fetch_and_add_4:
1600   case Builtin::BI__sync_fetch_and_add_8:
1601   case Builtin::BI__sync_fetch_and_add_16:
1602   case Builtin::BI__sync_fetch_and_sub:
1603   case Builtin::BI__sync_fetch_and_sub_1:
1604   case Builtin::BI__sync_fetch_and_sub_2:
1605   case Builtin::BI__sync_fetch_and_sub_4:
1606   case Builtin::BI__sync_fetch_and_sub_8:
1607   case Builtin::BI__sync_fetch_and_sub_16:
1608   case Builtin::BI__sync_fetch_and_or:
1609   case Builtin::BI__sync_fetch_and_or_1:
1610   case Builtin::BI__sync_fetch_and_or_2:
1611   case Builtin::BI__sync_fetch_and_or_4:
1612   case Builtin::BI__sync_fetch_and_or_8:
1613   case Builtin::BI__sync_fetch_and_or_16:
1614   case Builtin::BI__sync_fetch_and_and:
1615   case Builtin::BI__sync_fetch_and_and_1:
1616   case Builtin::BI__sync_fetch_and_and_2:
1617   case Builtin::BI__sync_fetch_and_and_4:
1618   case Builtin::BI__sync_fetch_and_and_8:
1619   case Builtin::BI__sync_fetch_and_and_16:
1620   case Builtin::BI__sync_fetch_and_xor:
1621   case Builtin::BI__sync_fetch_and_xor_1:
1622   case Builtin::BI__sync_fetch_and_xor_2:
1623   case Builtin::BI__sync_fetch_and_xor_4:
1624   case Builtin::BI__sync_fetch_and_xor_8:
1625   case Builtin::BI__sync_fetch_and_xor_16:
1626   case Builtin::BI__sync_fetch_and_nand:
1627   case Builtin::BI__sync_fetch_and_nand_1:
1628   case Builtin::BI__sync_fetch_and_nand_2:
1629   case Builtin::BI__sync_fetch_and_nand_4:
1630   case Builtin::BI__sync_fetch_and_nand_8:
1631   case Builtin::BI__sync_fetch_and_nand_16:
1632   case Builtin::BI__sync_add_and_fetch:
1633   case Builtin::BI__sync_add_and_fetch_1:
1634   case Builtin::BI__sync_add_and_fetch_2:
1635   case Builtin::BI__sync_add_and_fetch_4:
1636   case Builtin::BI__sync_add_and_fetch_8:
1637   case Builtin::BI__sync_add_and_fetch_16:
1638   case Builtin::BI__sync_sub_and_fetch:
1639   case Builtin::BI__sync_sub_and_fetch_1:
1640   case Builtin::BI__sync_sub_and_fetch_2:
1641   case Builtin::BI__sync_sub_and_fetch_4:
1642   case Builtin::BI__sync_sub_and_fetch_8:
1643   case Builtin::BI__sync_sub_and_fetch_16:
1644   case Builtin::BI__sync_and_and_fetch:
1645   case Builtin::BI__sync_and_and_fetch_1:
1646   case Builtin::BI__sync_and_and_fetch_2:
1647   case Builtin::BI__sync_and_and_fetch_4:
1648   case Builtin::BI__sync_and_and_fetch_8:
1649   case Builtin::BI__sync_and_and_fetch_16:
1650   case Builtin::BI__sync_or_and_fetch:
1651   case Builtin::BI__sync_or_and_fetch_1:
1652   case Builtin::BI__sync_or_and_fetch_2:
1653   case Builtin::BI__sync_or_and_fetch_4:
1654   case Builtin::BI__sync_or_and_fetch_8:
1655   case Builtin::BI__sync_or_and_fetch_16:
1656   case Builtin::BI__sync_xor_and_fetch:
1657   case Builtin::BI__sync_xor_and_fetch_1:
1658   case Builtin::BI__sync_xor_and_fetch_2:
1659   case Builtin::BI__sync_xor_and_fetch_4:
1660   case Builtin::BI__sync_xor_and_fetch_8:
1661   case Builtin::BI__sync_xor_and_fetch_16:
1662   case Builtin::BI__sync_nand_and_fetch:
1663   case Builtin::BI__sync_nand_and_fetch_1:
1664   case Builtin::BI__sync_nand_and_fetch_2:
1665   case Builtin::BI__sync_nand_and_fetch_4:
1666   case Builtin::BI__sync_nand_and_fetch_8:
1667   case Builtin::BI__sync_nand_and_fetch_16:
1668   case Builtin::BI__sync_val_compare_and_swap:
1669   case Builtin::BI__sync_val_compare_and_swap_1:
1670   case Builtin::BI__sync_val_compare_and_swap_2:
1671   case Builtin::BI__sync_val_compare_and_swap_4:
1672   case Builtin::BI__sync_val_compare_and_swap_8:
1673   case Builtin::BI__sync_val_compare_and_swap_16:
1674   case Builtin::BI__sync_bool_compare_and_swap:
1675   case Builtin::BI__sync_bool_compare_and_swap_1:
1676   case Builtin::BI__sync_bool_compare_and_swap_2:
1677   case Builtin::BI__sync_bool_compare_and_swap_4:
1678   case Builtin::BI__sync_bool_compare_and_swap_8:
1679   case Builtin::BI__sync_bool_compare_and_swap_16:
1680   case Builtin::BI__sync_lock_test_and_set:
1681   case Builtin::BI__sync_lock_test_and_set_1:
1682   case Builtin::BI__sync_lock_test_and_set_2:
1683   case Builtin::BI__sync_lock_test_and_set_4:
1684   case Builtin::BI__sync_lock_test_and_set_8:
1685   case Builtin::BI__sync_lock_test_and_set_16:
1686   case Builtin::BI__sync_lock_release:
1687   case Builtin::BI__sync_lock_release_1:
1688   case Builtin::BI__sync_lock_release_2:
1689   case Builtin::BI__sync_lock_release_4:
1690   case Builtin::BI__sync_lock_release_8:
1691   case Builtin::BI__sync_lock_release_16:
1692   case Builtin::BI__sync_swap:
1693   case Builtin::BI__sync_swap_1:
1694   case Builtin::BI__sync_swap_2:
1695   case Builtin::BI__sync_swap_4:
1696   case Builtin::BI__sync_swap_8:
1697   case Builtin::BI__sync_swap_16:
1698     return SemaBuiltinAtomicOverloaded(TheCallResult);
1699   case Builtin::BI__sync_synchronize:
1700     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1701         << TheCall->getCallee()->getSourceRange();
1702     break;
1703   case Builtin::BI__builtin_nontemporal_load:
1704   case Builtin::BI__builtin_nontemporal_store:
1705     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1706   case Builtin::BI__builtin_memcpy_inline: {
1707     clang::Expr *SizeOp = TheCall->getArg(2);
1708     // We warn about copying to or from `nullptr` pointers when `size` is
1709     // greater than 0. When `size` is value dependent we cannot evaluate its
1710     // value so we bail out.
1711     if (SizeOp->isValueDependent())
1712       break;
1713     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1714       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1715       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1716     }
1717     break;
1718   }
1719 #define BUILTIN(ID, TYPE, ATTRS)
1720 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1721   case Builtin::BI##ID: \
1722     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1723 #include "clang/Basic/Builtins.def"
1724   case Builtin::BI__annotation:
1725     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1726       return ExprError();
1727     break;
1728   case Builtin::BI__builtin_annotation:
1729     if (SemaBuiltinAnnotation(*this, TheCall))
1730       return ExprError();
1731     break;
1732   case Builtin::BI__builtin_addressof:
1733     if (SemaBuiltinAddressof(*this, TheCall))
1734       return ExprError();
1735     break;
1736   case Builtin::BI__builtin_is_aligned:
1737   case Builtin::BI__builtin_align_up:
1738   case Builtin::BI__builtin_align_down:
1739     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1740       return ExprError();
1741     break;
1742   case Builtin::BI__builtin_add_overflow:
1743   case Builtin::BI__builtin_sub_overflow:
1744   case Builtin::BI__builtin_mul_overflow:
1745     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1746       return ExprError();
1747     break;
1748   case Builtin::BI__builtin_operator_new:
1749   case Builtin::BI__builtin_operator_delete: {
1750     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1751     ExprResult Res =
1752         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1753     if (Res.isInvalid())
1754       CorrectDelayedTyposInExpr(TheCallResult.get());
1755     return Res;
1756   }
1757   case Builtin::BI__builtin_dump_struct: {
1758     // We first want to ensure we are called with 2 arguments
1759     if (checkArgCount(*this, TheCall, 2))
1760       return ExprError();
1761     // Ensure that the first argument is of type 'struct XX *'
1762     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1763     const QualType PtrArgType = PtrArg->getType();
1764     if (!PtrArgType->isPointerType() ||
1765         !PtrArgType->getPointeeType()->isRecordType()) {
1766       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1767           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1768           << "structure pointer";
1769       return ExprError();
1770     }
1771 
1772     // Ensure that the second argument is of type 'FunctionType'
1773     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1774     const QualType FnPtrArgType = FnPtrArg->getType();
1775     if (!FnPtrArgType->isPointerType()) {
1776       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1777           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1778           << FnPtrArgType << "'int (*)(const char *, ...)'";
1779       return ExprError();
1780     }
1781 
1782     const auto *FuncType =
1783         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1784 
1785     if (!FuncType) {
1786       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1787           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1788           << FnPtrArgType << "'int (*)(const char *, ...)'";
1789       return ExprError();
1790     }
1791 
1792     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1793       if (!FT->getNumParams()) {
1794         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1795             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1796             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1797         return ExprError();
1798       }
1799       QualType PT = FT->getParamType(0);
1800       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1801           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1802           !PT->getPointeeType().isConstQualified()) {
1803         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1804             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1805             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1806         return ExprError();
1807       }
1808     }
1809 
1810     TheCall->setType(Context.IntTy);
1811     break;
1812   }
1813   case Builtin::BI__builtin_expect_with_probability: {
1814     // We first want to ensure we are called with 3 arguments
1815     if (checkArgCount(*this, TheCall, 3))
1816       return ExprError();
1817     // then check probability is constant float in range [0.0, 1.0]
1818     const Expr *ProbArg = TheCall->getArg(2);
1819     SmallVector<PartialDiagnosticAt, 8> Notes;
1820     Expr::EvalResult Eval;
1821     Eval.Diag = &Notes;
1822     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1823         !Eval.Val.isFloat()) {
1824       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1825           << ProbArg->getSourceRange();
1826       for (const PartialDiagnosticAt &PDiag : Notes)
1827         Diag(PDiag.first, PDiag.second);
1828       return ExprError();
1829     }
1830     llvm::APFloat Probability = Eval.Val.getFloat();
1831     bool LoseInfo = false;
1832     Probability.convert(llvm::APFloat::IEEEdouble(),
1833                         llvm::RoundingMode::Dynamic, &LoseInfo);
1834     if (!(Probability >= llvm::APFloat(0.0) &&
1835           Probability <= llvm::APFloat(1.0))) {
1836       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1837           << ProbArg->getSourceRange();
1838       return ExprError();
1839     }
1840     break;
1841   }
1842   case Builtin::BI__builtin_preserve_access_index:
1843     if (SemaBuiltinPreserveAI(*this, TheCall))
1844       return ExprError();
1845     break;
1846   case Builtin::BI__builtin_call_with_static_chain:
1847     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1848       return ExprError();
1849     break;
1850   case Builtin::BI__exception_code:
1851   case Builtin::BI_exception_code:
1852     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1853                                  diag::err_seh___except_block))
1854       return ExprError();
1855     break;
1856   case Builtin::BI__exception_info:
1857   case Builtin::BI_exception_info:
1858     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1859                                  diag::err_seh___except_filter))
1860       return ExprError();
1861     break;
1862   case Builtin::BI__GetExceptionInfo:
1863     if (checkArgCount(*this, TheCall, 1))
1864       return ExprError();
1865 
1866     if (CheckCXXThrowOperand(
1867             TheCall->getBeginLoc(),
1868             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1869             TheCall))
1870       return ExprError();
1871 
1872     TheCall->setType(Context.VoidPtrTy);
1873     break;
1874   // OpenCL v2.0, s6.13.16 - Pipe functions
1875   case Builtin::BIread_pipe:
1876   case Builtin::BIwrite_pipe:
1877     // Since those two functions are declared with var args, we need a semantic
1878     // check for the argument.
1879     if (SemaBuiltinRWPipe(*this, TheCall))
1880       return ExprError();
1881     break;
1882   case Builtin::BIreserve_read_pipe:
1883   case Builtin::BIreserve_write_pipe:
1884   case Builtin::BIwork_group_reserve_read_pipe:
1885   case Builtin::BIwork_group_reserve_write_pipe:
1886     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1887       return ExprError();
1888     break;
1889   case Builtin::BIsub_group_reserve_read_pipe:
1890   case Builtin::BIsub_group_reserve_write_pipe:
1891     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1892         SemaBuiltinReserveRWPipe(*this, TheCall))
1893       return ExprError();
1894     break;
1895   case Builtin::BIcommit_read_pipe:
1896   case Builtin::BIcommit_write_pipe:
1897   case Builtin::BIwork_group_commit_read_pipe:
1898   case Builtin::BIwork_group_commit_write_pipe:
1899     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1900       return ExprError();
1901     break;
1902   case Builtin::BIsub_group_commit_read_pipe:
1903   case Builtin::BIsub_group_commit_write_pipe:
1904     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1905         SemaBuiltinCommitRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIget_pipe_num_packets:
1909   case Builtin::BIget_pipe_max_packets:
1910     if (SemaBuiltinPipePackets(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIto_global:
1914   case Builtin::BIto_local:
1915   case Builtin::BIto_private:
1916     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1917       return ExprError();
1918     break;
1919   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1920   case Builtin::BIenqueue_kernel:
1921     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_work_group_size:
1925   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1926     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1930   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1931     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BI__builtin_os_log_format:
1935     Cleanup.setExprNeedsCleanups(true);
1936     LLVM_FALLTHROUGH;
1937   case Builtin::BI__builtin_os_log_format_buffer_size:
1938     if (SemaBuiltinOSLogFormat(TheCall))
1939       return ExprError();
1940     break;
1941   case Builtin::BI__builtin_frame_address:
1942   case Builtin::BI__builtin_return_address: {
1943     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1944       return ExprError();
1945 
1946     // -Wframe-address warning if non-zero passed to builtin
1947     // return/frame address.
1948     Expr::EvalResult Result;
1949     if (!TheCall->getArg(0)->isValueDependent() &&
1950         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1951         Result.Val.getInt() != 0)
1952       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1953           << ((BuiltinID == Builtin::BI__builtin_return_address)
1954                   ? "__builtin_return_address"
1955                   : "__builtin_frame_address")
1956           << TheCall->getSourceRange();
1957     break;
1958   }
1959 
1960   case Builtin::BI__builtin_matrix_transpose:
1961     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1962 
1963   case Builtin::BI__builtin_matrix_column_major_load:
1964     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1965 
1966   case Builtin::BI__builtin_matrix_column_major_store:
1967     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1968   }
1969 
1970   // Since the target specific builtins for each arch overlap, only check those
1971   // of the arch we are compiling for.
1972   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1973     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1974       assert(Context.getAuxTargetInfo() &&
1975              "Aux Target Builtin, but not an aux target?");
1976 
1977       if (CheckTSBuiltinFunctionCall(
1978               *Context.getAuxTargetInfo(),
1979               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1980         return ExprError();
1981     } else {
1982       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1983                                      TheCall))
1984         return ExprError();
1985     }
1986   }
1987 
1988   return TheCallResult;
1989 }
1990 
1991 // Get the valid immediate range for the specified NEON type code.
1992 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1993   NeonTypeFlags Type(t);
1994   int IsQuad = ForceQuad ? true : Type.isQuad();
1995   switch (Type.getEltType()) {
1996   case NeonTypeFlags::Int8:
1997   case NeonTypeFlags::Poly8:
1998     return shift ? 7 : (8 << IsQuad) - 1;
1999   case NeonTypeFlags::Int16:
2000   case NeonTypeFlags::Poly16:
2001     return shift ? 15 : (4 << IsQuad) - 1;
2002   case NeonTypeFlags::Int32:
2003     return shift ? 31 : (2 << IsQuad) - 1;
2004   case NeonTypeFlags::Int64:
2005   case NeonTypeFlags::Poly64:
2006     return shift ? 63 : (1 << IsQuad) - 1;
2007   case NeonTypeFlags::Poly128:
2008     return shift ? 127 : (1 << IsQuad) - 1;
2009   case NeonTypeFlags::Float16:
2010     assert(!shift && "cannot shift float types!");
2011     return (4 << IsQuad) - 1;
2012   case NeonTypeFlags::Float32:
2013     assert(!shift && "cannot shift float types!");
2014     return (2 << IsQuad) - 1;
2015   case NeonTypeFlags::Float64:
2016     assert(!shift && "cannot shift float types!");
2017     return (1 << IsQuad) - 1;
2018   case NeonTypeFlags::BFloat16:
2019     assert(!shift && "cannot shift float types!");
2020     return (4 << IsQuad) - 1;
2021   }
2022   llvm_unreachable("Invalid NeonTypeFlag!");
2023 }
2024 
2025 /// getNeonEltType - Return the QualType corresponding to the elements of
2026 /// the vector type specified by the NeonTypeFlags.  This is used to check
2027 /// the pointer arguments for Neon load/store intrinsics.
2028 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2029                                bool IsPolyUnsigned, bool IsInt64Long) {
2030   switch (Flags.getEltType()) {
2031   case NeonTypeFlags::Int8:
2032     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2033   case NeonTypeFlags::Int16:
2034     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2035   case NeonTypeFlags::Int32:
2036     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2037   case NeonTypeFlags::Int64:
2038     if (IsInt64Long)
2039       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2040     else
2041       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2042                                 : Context.LongLongTy;
2043   case NeonTypeFlags::Poly8:
2044     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2045   case NeonTypeFlags::Poly16:
2046     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2047   case NeonTypeFlags::Poly64:
2048     if (IsInt64Long)
2049       return Context.UnsignedLongTy;
2050     else
2051       return Context.UnsignedLongLongTy;
2052   case NeonTypeFlags::Poly128:
2053     break;
2054   case NeonTypeFlags::Float16:
2055     return Context.HalfTy;
2056   case NeonTypeFlags::Float32:
2057     return Context.FloatTy;
2058   case NeonTypeFlags::Float64:
2059     return Context.DoubleTy;
2060   case NeonTypeFlags::BFloat16:
2061     return Context.BFloat16Ty;
2062   }
2063   llvm_unreachable("Invalid NeonTypeFlag!");
2064 }
2065 
2066 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2067   // Range check SVE intrinsics that take immediate values.
2068   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2069 
2070   switch (BuiltinID) {
2071   default:
2072     return false;
2073 #define GET_SVE_IMMEDIATE_CHECK
2074 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2075 #undef GET_SVE_IMMEDIATE_CHECK
2076   }
2077 
2078   // Perform all the immediate checks for this builtin call.
2079   bool HasError = false;
2080   for (auto &I : ImmChecks) {
2081     int ArgNum, CheckTy, ElementSizeInBits;
2082     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2083 
2084     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2085 
2086     // Function that checks whether the operand (ArgNum) is an immediate
2087     // that is one of the predefined values.
2088     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2089                                    int ErrDiag) -> bool {
2090       // We can't check the value of a dependent argument.
2091       Expr *Arg = TheCall->getArg(ArgNum);
2092       if (Arg->isTypeDependent() || Arg->isValueDependent())
2093         return false;
2094 
2095       // Check constant-ness first.
2096       llvm::APSInt Imm;
2097       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2098         return true;
2099 
2100       if (!CheckImm(Imm.getSExtValue()))
2101         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2102       return false;
2103     };
2104 
2105     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2106     case SVETypeFlags::ImmCheck0_31:
2107       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2108         HasError = true;
2109       break;
2110     case SVETypeFlags::ImmCheck0_13:
2111       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2112         HasError = true;
2113       break;
2114     case SVETypeFlags::ImmCheck1_16:
2115       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2116         HasError = true;
2117       break;
2118     case SVETypeFlags::ImmCheck0_7:
2119       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2120         HasError = true;
2121       break;
2122     case SVETypeFlags::ImmCheckExtract:
2123       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2124                                       (2048 / ElementSizeInBits) - 1))
2125         HasError = true;
2126       break;
2127     case SVETypeFlags::ImmCheckShiftRight:
2128       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2129         HasError = true;
2130       break;
2131     case SVETypeFlags::ImmCheckShiftRightNarrow:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2133                                       ElementSizeInBits / 2))
2134         HasError = true;
2135       break;
2136     case SVETypeFlags::ImmCheckShiftLeft:
2137       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2138                                       ElementSizeInBits - 1))
2139         HasError = true;
2140       break;
2141     case SVETypeFlags::ImmCheckLaneIndex:
2142       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2143                                       (128 / (1 * ElementSizeInBits)) - 1))
2144         HasError = true;
2145       break;
2146     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2147       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2148                                       (128 / (2 * ElementSizeInBits)) - 1))
2149         HasError = true;
2150       break;
2151     case SVETypeFlags::ImmCheckLaneIndexDot:
2152       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2153                                       (128 / (4 * ElementSizeInBits)) - 1))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckComplexRot90_270:
2157       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2158                               diag::err_rotation_argument_to_cadd))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckComplexRotAll90:
2162       if (CheckImmediateInSet(
2163               [](int64_t V) {
2164                 return V == 0 || V == 90 || V == 180 || V == 270;
2165               },
2166               diag::err_rotation_argument_to_cmla))
2167         HasError = true;
2168       break;
2169     case SVETypeFlags::ImmCheck0_1:
2170       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2171         HasError = true;
2172       break;
2173     case SVETypeFlags::ImmCheck0_2:
2174       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2175         HasError = true;
2176       break;
2177     case SVETypeFlags::ImmCheck0_3:
2178       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2179         HasError = true;
2180       break;
2181     }
2182   }
2183 
2184   return HasError;
2185 }
2186 
2187 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2188                                         unsigned BuiltinID, CallExpr *TheCall) {
2189   llvm::APSInt Result;
2190   uint64_t mask = 0;
2191   unsigned TV = 0;
2192   int PtrArgNum = -1;
2193   bool HasConstPtr = false;
2194   switch (BuiltinID) {
2195 #define GET_NEON_OVERLOAD_CHECK
2196 #include "clang/Basic/arm_neon.inc"
2197 #include "clang/Basic/arm_fp16.inc"
2198 #undef GET_NEON_OVERLOAD_CHECK
2199   }
2200 
2201   // For NEON intrinsics which are overloaded on vector element type, validate
2202   // the immediate which specifies which variant to emit.
2203   unsigned ImmArg = TheCall->getNumArgs()-1;
2204   if (mask) {
2205     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2206       return true;
2207 
2208     TV = Result.getLimitedValue(64);
2209     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2210       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2211              << TheCall->getArg(ImmArg)->getSourceRange();
2212   }
2213 
2214   if (PtrArgNum >= 0) {
2215     // Check that pointer arguments have the specified type.
2216     Expr *Arg = TheCall->getArg(PtrArgNum);
2217     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2218       Arg = ICE->getSubExpr();
2219     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2220     QualType RHSTy = RHS.get()->getType();
2221 
2222     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2223     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2224                           Arch == llvm::Triple::aarch64_32 ||
2225                           Arch == llvm::Triple::aarch64_be;
2226     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2227     QualType EltTy =
2228         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2229     if (HasConstPtr)
2230       EltTy = EltTy.withConst();
2231     QualType LHSTy = Context.getPointerType(EltTy);
2232     AssignConvertType ConvTy;
2233     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2234     if (RHS.isInvalid())
2235       return true;
2236     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2237                                  RHS.get(), AA_Assigning))
2238       return true;
2239   }
2240 
2241   // For NEON intrinsics which take an immediate value as part of the
2242   // instruction, range check them here.
2243   unsigned i = 0, l = 0, u = 0;
2244   switch (BuiltinID) {
2245   default:
2246     return false;
2247   #define GET_NEON_IMMEDIATE_CHECK
2248   #include "clang/Basic/arm_neon.inc"
2249   #include "clang/Basic/arm_fp16.inc"
2250   #undef GET_NEON_IMMEDIATE_CHECK
2251   }
2252 
2253   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2254 }
2255 
2256 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2257   switch (BuiltinID) {
2258   default:
2259     return false;
2260   #include "clang/Basic/arm_mve_builtin_sema.inc"
2261   }
2262 }
2263 
2264 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2265                                        CallExpr *TheCall) {
2266   bool Err = false;
2267   switch (BuiltinID) {
2268   default:
2269     return false;
2270 #include "clang/Basic/arm_cde_builtin_sema.inc"
2271   }
2272 
2273   if (Err)
2274     return true;
2275 
2276   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2277 }
2278 
2279 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2280                                         const Expr *CoprocArg, bool WantCDE) {
2281   if (isConstantEvaluated())
2282     return false;
2283 
2284   // We can't check the value of a dependent argument.
2285   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2286     return false;
2287 
2288   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2289   int64_t CoprocNo = CoprocNoAP.getExtValue();
2290   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2291 
2292   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2293   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2294 
2295   if (IsCDECoproc != WantCDE)
2296     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2297            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2298 
2299   return false;
2300 }
2301 
2302 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2303                                         unsigned MaxWidth) {
2304   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2305           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2306           BuiltinID == ARM::BI__builtin_arm_strex ||
2307           BuiltinID == ARM::BI__builtin_arm_stlex ||
2308           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2309           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2310           BuiltinID == AArch64::BI__builtin_arm_strex ||
2311           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2312          "unexpected ARM builtin");
2313   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2314                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2315                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2316                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2317 
2318   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2319 
2320   // Ensure that we have the proper number of arguments.
2321   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2322     return true;
2323 
2324   // Inspect the pointer argument of the atomic builtin.  This should always be
2325   // a pointer type, whose element is an integral scalar or pointer type.
2326   // Because it is a pointer type, we don't have to worry about any implicit
2327   // casts here.
2328   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2329   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2330   if (PointerArgRes.isInvalid())
2331     return true;
2332   PointerArg = PointerArgRes.get();
2333 
2334   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2335   if (!pointerType) {
2336     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2337         << PointerArg->getType() << PointerArg->getSourceRange();
2338     return true;
2339   }
2340 
2341   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2342   // task is to insert the appropriate casts into the AST. First work out just
2343   // what the appropriate type is.
2344   QualType ValType = pointerType->getPointeeType();
2345   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2346   if (IsLdrex)
2347     AddrType.addConst();
2348 
2349   // Issue a warning if the cast is dodgy.
2350   CastKind CastNeeded = CK_NoOp;
2351   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2352     CastNeeded = CK_BitCast;
2353     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2354         << PointerArg->getType() << Context.getPointerType(AddrType)
2355         << AA_Passing << PointerArg->getSourceRange();
2356   }
2357 
2358   // Finally, do the cast and replace the argument with the corrected version.
2359   AddrType = Context.getPointerType(AddrType);
2360   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2361   if (PointerArgRes.isInvalid())
2362     return true;
2363   PointerArg = PointerArgRes.get();
2364 
2365   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2366 
2367   // In general, we allow ints, floats and pointers to be loaded and stored.
2368   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2369       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2370     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2371         << PointerArg->getType() << PointerArg->getSourceRange();
2372     return true;
2373   }
2374 
2375   // But ARM doesn't have instructions to deal with 128-bit versions.
2376   if (Context.getTypeSize(ValType) > MaxWidth) {
2377     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2378     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2379         << PointerArg->getType() << PointerArg->getSourceRange();
2380     return true;
2381   }
2382 
2383   switch (ValType.getObjCLifetime()) {
2384   case Qualifiers::OCL_None:
2385   case Qualifiers::OCL_ExplicitNone:
2386     // okay
2387     break;
2388 
2389   case Qualifiers::OCL_Weak:
2390   case Qualifiers::OCL_Strong:
2391   case Qualifiers::OCL_Autoreleasing:
2392     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2393         << ValType << PointerArg->getSourceRange();
2394     return true;
2395   }
2396 
2397   if (IsLdrex) {
2398     TheCall->setType(ValType);
2399     return false;
2400   }
2401 
2402   // Initialize the argument to be stored.
2403   ExprResult ValArg = TheCall->getArg(0);
2404   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2405       Context, ValType, /*consume*/ false);
2406   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2407   if (ValArg.isInvalid())
2408     return true;
2409   TheCall->setArg(0, ValArg.get());
2410 
2411   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2412   // but the custom checker bypasses all default analysis.
2413   TheCall->setType(Context.IntTy);
2414   return false;
2415 }
2416 
2417 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2418                                        CallExpr *TheCall) {
2419   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2420       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2421       BuiltinID == ARM::BI__builtin_arm_strex ||
2422       BuiltinID == ARM::BI__builtin_arm_stlex) {
2423     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2424   }
2425 
2426   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2427     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2428       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2429   }
2430 
2431   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2432       BuiltinID == ARM::BI__builtin_arm_wsr64)
2433     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2434 
2435   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2436       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2437       BuiltinID == ARM::BI__builtin_arm_wsr ||
2438       BuiltinID == ARM::BI__builtin_arm_wsrp)
2439     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2440 
2441   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2442     return true;
2443   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2444     return true;
2445   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2446     return true;
2447 
2448   // For intrinsics which take an immediate value as part of the instruction,
2449   // range check them here.
2450   // FIXME: VFP Intrinsics should error if VFP not present.
2451   switch (BuiltinID) {
2452   default: return false;
2453   case ARM::BI__builtin_arm_ssat:
2454     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2455   case ARM::BI__builtin_arm_usat:
2456     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2457   case ARM::BI__builtin_arm_ssat16:
2458     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2459   case ARM::BI__builtin_arm_usat16:
2460     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2461   case ARM::BI__builtin_arm_vcvtr_f:
2462   case ARM::BI__builtin_arm_vcvtr_d:
2463     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2464   case ARM::BI__builtin_arm_dmb:
2465   case ARM::BI__builtin_arm_dsb:
2466   case ARM::BI__builtin_arm_isb:
2467   case ARM::BI__builtin_arm_dbg:
2468     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2469   case ARM::BI__builtin_arm_cdp:
2470   case ARM::BI__builtin_arm_cdp2:
2471   case ARM::BI__builtin_arm_mcr:
2472   case ARM::BI__builtin_arm_mcr2:
2473   case ARM::BI__builtin_arm_mrc:
2474   case ARM::BI__builtin_arm_mrc2:
2475   case ARM::BI__builtin_arm_mcrr:
2476   case ARM::BI__builtin_arm_mcrr2:
2477   case ARM::BI__builtin_arm_mrrc:
2478   case ARM::BI__builtin_arm_mrrc2:
2479   case ARM::BI__builtin_arm_ldc:
2480   case ARM::BI__builtin_arm_ldcl:
2481   case ARM::BI__builtin_arm_ldc2:
2482   case ARM::BI__builtin_arm_ldc2l:
2483   case ARM::BI__builtin_arm_stc:
2484   case ARM::BI__builtin_arm_stcl:
2485   case ARM::BI__builtin_arm_stc2:
2486   case ARM::BI__builtin_arm_stc2l:
2487     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2488            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2489                                         /*WantCDE*/ false);
2490   }
2491 }
2492 
2493 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2494                                            unsigned BuiltinID,
2495                                            CallExpr *TheCall) {
2496   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2497       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2498       BuiltinID == AArch64::BI__builtin_arm_strex ||
2499       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2500     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2501   }
2502 
2503   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2504     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2505       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2506       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2507       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2508   }
2509 
2510   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2511       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2512     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2513 
2514   // Memory Tagging Extensions (MTE) Intrinsics
2515   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2516       BuiltinID == AArch64::BI__builtin_arm_addg ||
2517       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2518       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2519       BuiltinID == AArch64::BI__builtin_arm_stg ||
2520       BuiltinID == AArch64::BI__builtin_arm_subp) {
2521     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2522   }
2523 
2524   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2525       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2526       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2527       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2528     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2529 
2530   // Only check the valid encoding range. Any constant in this range would be
2531   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2532   // an exception for incorrect registers. This matches MSVC behavior.
2533   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2534       BuiltinID == AArch64::BI_WriteStatusReg)
2535     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2536 
2537   if (BuiltinID == AArch64::BI__getReg)
2538     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2539 
2540   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2541     return true;
2542 
2543   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2544     return true;
2545 
2546   // For intrinsics which take an immediate value as part of the instruction,
2547   // range check them here.
2548   unsigned i = 0, l = 0, u = 0;
2549   switch (BuiltinID) {
2550   default: return false;
2551   case AArch64::BI__builtin_arm_dmb:
2552   case AArch64::BI__builtin_arm_dsb:
2553   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2554   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2555   }
2556 
2557   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2558 }
2559 
2560 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2561   if (Arg->getType()->getAsPlaceholderType())
2562     return false;
2563 
2564   // The first argument needs to be a record field access.
2565   // If it is an array element access, we delay decision
2566   // to BPF backend to check whether the access is a
2567   // field access or not.
2568   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2569           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2570           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2571 }
2572 
2573 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2574                             QualType VectorTy, QualType EltTy) {
2575   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2576   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2577     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2578         << Call->getSourceRange() << VectorEltTy << EltTy;
2579     return false;
2580   }
2581   return true;
2582 }
2583 
2584 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2585   QualType ArgType = Arg->getType();
2586   if (ArgType->getAsPlaceholderType())
2587     return false;
2588 
2589   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2590   // format:
2591   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2592   //   2. <type> var;
2593   //      __builtin_preserve_type_info(var, flag);
2594   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2595       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2596     return false;
2597 
2598   // Typedef type.
2599   if (ArgType->getAs<TypedefType>())
2600     return true;
2601 
2602   // Record type or Enum type.
2603   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2604   if (const auto *RT = Ty->getAs<RecordType>()) {
2605     if (!RT->getDecl()->getDeclName().isEmpty())
2606       return true;
2607   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2608     if (!ET->getDecl()->getDeclName().isEmpty())
2609       return true;
2610   }
2611 
2612   return false;
2613 }
2614 
2615 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2616   QualType ArgType = Arg->getType();
2617   if (ArgType->getAsPlaceholderType())
2618     return false;
2619 
2620   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2621   // format:
2622   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2623   //                                 flag);
2624   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2625   if (!UO)
2626     return false;
2627 
2628   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2629   if (!CE)
2630     return false;
2631   if (CE->getCastKind() != CK_IntegralToPointer &&
2632       CE->getCastKind() != CK_NullToPointer)
2633     return false;
2634 
2635   // The integer must be from an EnumConstantDecl.
2636   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2637   if (!DR)
2638     return false;
2639 
2640   const EnumConstantDecl *Enumerator =
2641       dyn_cast<EnumConstantDecl>(DR->getDecl());
2642   if (!Enumerator)
2643     return false;
2644 
2645   // The type must be EnumType.
2646   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2647   const auto *ET = Ty->getAs<EnumType>();
2648   if (!ET)
2649     return false;
2650 
2651   // The enum value must be supported.
2652   for (auto *EDI : ET->getDecl()->enumerators()) {
2653     if (EDI == Enumerator)
2654       return true;
2655   }
2656 
2657   return false;
2658 }
2659 
2660 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2661                                        CallExpr *TheCall) {
2662   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2663           BuiltinID == BPF::BI__builtin_btf_type_id ||
2664           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2665           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2666          "unexpected BPF builtin");
2667 
2668   if (checkArgCount(*this, TheCall, 2))
2669     return true;
2670 
2671   // The second argument needs to be a constant int
2672   Expr *Arg = TheCall->getArg(1);
2673   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2674   diag::kind kind;
2675   if (!Value) {
2676     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2677       kind = diag::err_preserve_field_info_not_const;
2678     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2679       kind = diag::err_btf_type_id_not_const;
2680     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2681       kind = diag::err_preserve_type_info_not_const;
2682     else
2683       kind = diag::err_preserve_enum_value_not_const;
2684     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2685     return true;
2686   }
2687 
2688   // The first argument
2689   Arg = TheCall->getArg(0);
2690   bool InvalidArg = false;
2691   bool ReturnUnsignedInt = true;
2692   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2693     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2694       InvalidArg = true;
2695       kind = diag::err_preserve_field_info_not_field;
2696     }
2697   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2698     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2699       InvalidArg = true;
2700       kind = diag::err_preserve_type_info_invalid;
2701     }
2702   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2703     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2704       InvalidArg = true;
2705       kind = diag::err_preserve_enum_value_invalid;
2706     }
2707     ReturnUnsignedInt = false;
2708   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2709     ReturnUnsignedInt = false;
2710   }
2711 
2712   if (InvalidArg) {
2713     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2714     return true;
2715   }
2716 
2717   if (ReturnUnsignedInt)
2718     TheCall->setType(Context.UnsignedIntTy);
2719   else
2720     TheCall->setType(Context.UnsignedLongTy);
2721   return false;
2722 }
2723 
2724 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2725   struct ArgInfo {
2726     uint8_t OpNum;
2727     bool IsSigned;
2728     uint8_t BitWidth;
2729     uint8_t Align;
2730   };
2731   struct BuiltinInfo {
2732     unsigned BuiltinID;
2733     ArgInfo Infos[2];
2734   };
2735 
2736   static BuiltinInfo Infos[] = {
2737     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2738     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2739     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2740     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2741     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2742     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2743     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2744     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2745     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2746     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2747     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2748 
2749     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2752     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2753     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2754     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2759     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2760 
2761     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2813                                                       {{ 1, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2821                                                       {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2828                                                        { 2, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2830                                                        { 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2832                                                        { 3, false, 5,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2834                                                        { 3, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2851                                                       {{ 2, false, 4,  0 },
2852                                                        { 3, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2854                                                       {{ 2, false, 4,  0 },
2855                                                        { 3, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2857                                                       {{ 2, false, 4,  0 },
2858                                                        { 3, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2860                                                       {{ 2, false, 4,  0 },
2861                                                        { 3, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2873                                                        { 2, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2875                                                        { 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2885                                                       {{ 1, false, 4,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2888                                                       {{ 1, false, 4,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2909                                                       {{ 3, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2914                                                       {{ 3, false, 1,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2919                                                       {{ 3, false, 1,  0 }} },
2920   };
2921 
2922   // Use a dynamically initialized static to sort the table exactly once on
2923   // first run.
2924   static const bool SortOnce =
2925       (llvm::sort(Infos,
2926                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2927                    return LHS.BuiltinID < RHS.BuiltinID;
2928                  }),
2929        true);
2930   (void)SortOnce;
2931 
2932   const BuiltinInfo *F = llvm::partition_point(
2933       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2934   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2935     return false;
2936 
2937   bool Error = false;
2938 
2939   for (const ArgInfo &A : F->Infos) {
2940     // Ignore empty ArgInfo elements.
2941     if (A.BitWidth == 0)
2942       continue;
2943 
2944     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2945     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2946     if (!A.Align) {
2947       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2948     } else {
2949       unsigned M = 1 << A.Align;
2950       Min *= M;
2951       Max *= M;
2952       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2953                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2954     }
2955   }
2956   return Error;
2957 }
2958 
2959 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2960                                            CallExpr *TheCall) {
2961   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2962 }
2963 
2964 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2965                                         unsigned BuiltinID, CallExpr *TheCall) {
2966   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2967          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2968 }
2969 
2970 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2971                                CallExpr *TheCall) {
2972 
2973   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2974       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2975     if (!TI.hasFeature("dsp"))
2976       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2977   }
2978 
2979   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2980       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2981     if (!TI.hasFeature("dspr2"))
2982       return Diag(TheCall->getBeginLoc(),
2983                   diag::err_mips_builtin_requires_dspr2);
2984   }
2985 
2986   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2987       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2988     if (!TI.hasFeature("msa"))
2989       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2990   }
2991 
2992   return false;
2993 }
2994 
2995 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2996 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2997 // ordering for DSP is unspecified. MSA is ordered by the data format used
2998 // by the underlying instruction i.e., df/m, df/n and then by size.
2999 //
3000 // FIXME: The size tests here should instead be tablegen'd along with the
3001 //        definitions from include/clang/Basic/BuiltinsMips.def.
3002 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3003 //        be too.
3004 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3005   unsigned i = 0, l = 0, u = 0, m = 0;
3006   switch (BuiltinID) {
3007   default: return false;
3008   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3009   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3010   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3011   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3012   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3013   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3014   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3015   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3016   // df/m field.
3017   // These intrinsics take an unsigned 3 bit immediate.
3018   case Mips::BI__builtin_msa_bclri_b:
3019   case Mips::BI__builtin_msa_bnegi_b:
3020   case Mips::BI__builtin_msa_bseti_b:
3021   case Mips::BI__builtin_msa_sat_s_b:
3022   case Mips::BI__builtin_msa_sat_u_b:
3023   case Mips::BI__builtin_msa_slli_b:
3024   case Mips::BI__builtin_msa_srai_b:
3025   case Mips::BI__builtin_msa_srari_b:
3026   case Mips::BI__builtin_msa_srli_b:
3027   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3028   case Mips::BI__builtin_msa_binsli_b:
3029   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3030   // These intrinsics take an unsigned 4 bit immediate.
3031   case Mips::BI__builtin_msa_bclri_h:
3032   case Mips::BI__builtin_msa_bnegi_h:
3033   case Mips::BI__builtin_msa_bseti_h:
3034   case Mips::BI__builtin_msa_sat_s_h:
3035   case Mips::BI__builtin_msa_sat_u_h:
3036   case Mips::BI__builtin_msa_slli_h:
3037   case Mips::BI__builtin_msa_srai_h:
3038   case Mips::BI__builtin_msa_srari_h:
3039   case Mips::BI__builtin_msa_srli_h:
3040   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3041   case Mips::BI__builtin_msa_binsli_h:
3042   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3043   // These intrinsics take an unsigned 5 bit immediate.
3044   // The first block of intrinsics actually have an unsigned 5 bit field,
3045   // not a df/n field.
3046   case Mips::BI__builtin_msa_cfcmsa:
3047   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3048   case Mips::BI__builtin_msa_clei_u_b:
3049   case Mips::BI__builtin_msa_clei_u_h:
3050   case Mips::BI__builtin_msa_clei_u_w:
3051   case Mips::BI__builtin_msa_clei_u_d:
3052   case Mips::BI__builtin_msa_clti_u_b:
3053   case Mips::BI__builtin_msa_clti_u_h:
3054   case Mips::BI__builtin_msa_clti_u_w:
3055   case Mips::BI__builtin_msa_clti_u_d:
3056   case Mips::BI__builtin_msa_maxi_u_b:
3057   case Mips::BI__builtin_msa_maxi_u_h:
3058   case Mips::BI__builtin_msa_maxi_u_w:
3059   case Mips::BI__builtin_msa_maxi_u_d:
3060   case Mips::BI__builtin_msa_mini_u_b:
3061   case Mips::BI__builtin_msa_mini_u_h:
3062   case Mips::BI__builtin_msa_mini_u_w:
3063   case Mips::BI__builtin_msa_mini_u_d:
3064   case Mips::BI__builtin_msa_addvi_b:
3065   case Mips::BI__builtin_msa_addvi_h:
3066   case Mips::BI__builtin_msa_addvi_w:
3067   case Mips::BI__builtin_msa_addvi_d:
3068   case Mips::BI__builtin_msa_bclri_w:
3069   case Mips::BI__builtin_msa_bnegi_w:
3070   case Mips::BI__builtin_msa_bseti_w:
3071   case Mips::BI__builtin_msa_sat_s_w:
3072   case Mips::BI__builtin_msa_sat_u_w:
3073   case Mips::BI__builtin_msa_slli_w:
3074   case Mips::BI__builtin_msa_srai_w:
3075   case Mips::BI__builtin_msa_srari_w:
3076   case Mips::BI__builtin_msa_srli_w:
3077   case Mips::BI__builtin_msa_srlri_w:
3078   case Mips::BI__builtin_msa_subvi_b:
3079   case Mips::BI__builtin_msa_subvi_h:
3080   case Mips::BI__builtin_msa_subvi_w:
3081   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3082   case Mips::BI__builtin_msa_binsli_w:
3083   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3084   // These intrinsics take an unsigned 6 bit immediate.
3085   case Mips::BI__builtin_msa_bclri_d:
3086   case Mips::BI__builtin_msa_bnegi_d:
3087   case Mips::BI__builtin_msa_bseti_d:
3088   case Mips::BI__builtin_msa_sat_s_d:
3089   case Mips::BI__builtin_msa_sat_u_d:
3090   case Mips::BI__builtin_msa_slli_d:
3091   case Mips::BI__builtin_msa_srai_d:
3092   case Mips::BI__builtin_msa_srari_d:
3093   case Mips::BI__builtin_msa_srli_d:
3094   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3095   case Mips::BI__builtin_msa_binsli_d:
3096   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3097   // These intrinsics take a signed 5 bit immediate.
3098   case Mips::BI__builtin_msa_ceqi_b:
3099   case Mips::BI__builtin_msa_ceqi_h:
3100   case Mips::BI__builtin_msa_ceqi_w:
3101   case Mips::BI__builtin_msa_ceqi_d:
3102   case Mips::BI__builtin_msa_clti_s_b:
3103   case Mips::BI__builtin_msa_clti_s_h:
3104   case Mips::BI__builtin_msa_clti_s_w:
3105   case Mips::BI__builtin_msa_clti_s_d:
3106   case Mips::BI__builtin_msa_clei_s_b:
3107   case Mips::BI__builtin_msa_clei_s_h:
3108   case Mips::BI__builtin_msa_clei_s_w:
3109   case Mips::BI__builtin_msa_clei_s_d:
3110   case Mips::BI__builtin_msa_maxi_s_b:
3111   case Mips::BI__builtin_msa_maxi_s_h:
3112   case Mips::BI__builtin_msa_maxi_s_w:
3113   case Mips::BI__builtin_msa_maxi_s_d:
3114   case Mips::BI__builtin_msa_mini_s_b:
3115   case Mips::BI__builtin_msa_mini_s_h:
3116   case Mips::BI__builtin_msa_mini_s_w:
3117   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3118   // These intrinsics take an unsigned 8 bit immediate.
3119   case Mips::BI__builtin_msa_andi_b:
3120   case Mips::BI__builtin_msa_nori_b:
3121   case Mips::BI__builtin_msa_ori_b:
3122   case Mips::BI__builtin_msa_shf_b:
3123   case Mips::BI__builtin_msa_shf_h:
3124   case Mips::BI__builtin_msa_shf_w:
3125   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3126   case Mips::BI__builtin_msa_bseli_b:
3127   case Mips::BI__builtin_msa_bmnzi_b:
3128   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3129   // df/n format
3130   // These intrinsics take an unsigned 4 bit immediate.
3131   case Mips::BI__builtin_msa_copy_s_b:
3132   case Mips::BI__builtin_msa_copy_u_b:
3133   case Mips::BI__builtin_msa_insve_b:
3134   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3135   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3136   // These intrinsics take an unsigned 3 bit immediate.
3137   case Mips::BI__builtin_msa_copy_s_h:
3138   case Mips::BI__builtin_msa_copy_u_h:
3139   case Mips::BI__builtin_msa_insve_h:
3140   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3141   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3142   // These intrinsics take an unsigned 2 bit immediate.
3143   case Mips::BI__builtin_msa_copy_s_w:
3144   case Mips::BI__builtin_msa_copy_u_w:
3145   case Mips::BI__builtin_msa_insve_w:
3146   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3147   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3148   // These intrinsics take an unsigned 1 bit immediate.
3149   case Mips::BI__builtin_msa_copy_s_d:
3150   case Mips::BI__builtin_msa_copy_u_d:
3151   case Mips::BI__builtin_msa_insve_d:
3152   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3153   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3154   // Memory offsets and immediate loads.
3155   // These intrinsics take a signed 10 bit immediate.
3156   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3157   case Mips::BI__builtin_msa_ldi_h:
3158   case Mips::BI__builtin_msa_ldi_w:
3159   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3160   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3161   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3162   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3163   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3164   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3165   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3166   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3167   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3168   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3169   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3170   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3171   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3172   }
3173 
3174   if (!m)
3175     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3176 
3177   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3178          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3179 }
3180 
3181 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3182 /// advancing the pointer over the consumed characters. The decoded type is
3183 /// returned. If the decoded type represents a constant integer with a
3184 /// constraint on its value then Mask is set to that value. The type descriptors
3185 /// used in Str are specific to PPC MMA builtins and are documented in the file
3186 /// defining the PPC builtins.
3187 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3188                                         unsigned &Mask) {
3189   bool RequireICE = false;
3190   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3191   switch (*Str++) {
3192   case 'V':
3193     return Context.getVectorType(Context.UnsignedCharTy, 16,
3194                                  VectorType::VectorKind::AltiVecVector);
3195   case 'i': {
3196     char *End;
3197     unsigned size = strtoul(Str, &End, 10);
3198     assert(End != Str && "Missing constant parameter constraint");
3199     Str = End;
3200     Mask = size;
3201     return Context.IntTy;
3202   }
3203   case 'W': {
3204     char *End;
3205     unsigned size = strtoul(Str, &End, 10);
3206     assert(End != Str && "Missing PowerPC MMA type size");
3207     Str = End;
3208     QualType Type;
3209     switch (size) {
3210   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3211     case size: Type = Context.Id##Ty; break;
3212   #include "clang/Basic/PPCTypes.def"
3213     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3214     }
3215     bool CheckVectorArgs = false;
3216     while (!CheckVectorArgs) {
3217       switch (*Str++) {
3218       case '*':
3219         Type = Context.getPointerType(Type);
3220         break;
3221       case 'C':
3222         Type = Type.withConst();
3223         break;
3224       default:
3225         CheckVectorArgs = true;
3226         --Str;
3227         break;
3228       }
3229     }
3230     return Type;
3231   }
3232   default:
3233     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3234   }
3235 }
3236 
3237 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3238                                        CallExpr *TheCall) {
3239   unsigned i = 0, l = 0, u = 0;
3240   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3241                       BuiltinID == PPC::BI__builtin_divdeu ||
3242                       BuiltinID == PPC::BI__builtin_bpermd;
3243   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3244   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3245                        BuiltinID == PPC::BI__builtin_divweu ||
3246                        BuiltinID == PPC::BI__builtin_divde ||
3247                        BuiltinID == PPC::BI__builtin_divdeu;
3248 
3249   if (Is64BitBltin && !IsTarget64Bit)
3250     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3251            << TheCall->getSourceRange();
3252 
3253   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3254       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3255     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3256            << TheCall->getSourceRange();
3257 
3258   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3259     if (!TI.hasFeature("vsx"))
3260       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3261              << TheCall->getSourceRange();
3262     return false;
3263   };
3264 
3265   switch (BuiltinID) {
3266   default: return false;
3267   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3268   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3269     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3270            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3271   case PPC::BI__builtin_altivec_dss:
3272     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3273   case PPC::BI__builtin_tbegin:
3274   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3275   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3276   case PPC::BI__builtin_tabortwc:
3277   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3278   case PPC::BI__builtin_tabortwci:
3279   case PPC::BI__builtin_tabortdci:
3280     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3281            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3282   case PPC::BI__builtin_altivec_dst:
3283   case PPC::BI__builtin_altivec_dstt:
3284   case PPC::BI__builtin_altivec_dstst:
3285   case PPC::BI__builtin_altivec_dststt:
3286     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3287   case PPC::BI__builtin_vsx_xxpermdi:
3288   case PPC::BI__builtin_vsx_xxsldwi:
3289     return SemaBuiltinVSX(TheCall);
3290   case PPC::BI__builtin_unpack_vector_int128:
3291     return SemaVSXCheck(TheCall) ||
3292            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3293   case PPC::BI__builtin_pack_vector_int128:
3294     return SemaVSXCheck(TheCall);
3295   case PPC::BI__builtin_altivec_vgnb:
3296      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3297   case PPC::BI__builtin_altivec_vec_replace_elt:
3298   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3299     QualType VecTy = TheCall->getArg(0)->getType();
3300     QualType EltTy = TheCall->getArg(1)->getType();
3301     unsigned Width = Context.getIntWidth(EltTy);
3302     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3303            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3304   }
3305   case PPC::BI__builtin_vsx_xxeval:
3306      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3307   case PPC::BI__builtin_altivec_vsldbi:
3308      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3309   case PPC::BI__builtin_altivec_vsrdbi:
3310      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3311   case PPC::BI__builtin_vsx_xxpermx:
3312      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3313 #define CUSTOM_BUILTIN(Name, Types, Acc) \
3314   case PPC::BI__builtin_##Name: \
3315     return SemaBuiltinPPCMMACall(TheCall, Types);
3316 #include "clang/Basic/BuiltinsPPC.def"
3317   }
3318   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3319 }
3320 
3321 // Check if the given type is a non-pointer PPC MMA type. This function is used
3322 // in Sema to prevent invalid uses of restricted PPC MMA types.
3323 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3324   if (Type->isPointerType() || Type->isArrayType())
3325     return false;
3326 
3327   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3328 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3329   if (false
3330 #include "clang/Basic/PPCTypes.def"
3331      ) {
3332     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3333     return true;
3334   }
3335   return false;
3336 }
3337 
3338 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3339                                           CallExpr *TheCall) {
3340   // position of memory order and scope arguments in the builtin
3341   unsigned OrderIndex, ScopeIndex;
3342   switch (BuiltinID) {
3343   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3344   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3345   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3346   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3347     OrderIndex = 2;
3348     ScopeIndex = 3;
3349     break;
3350   case AMDGPU::BI__builtin_amdgcn_fence:
3351     OrderIndex = 0;
3352     ScopeIndex = 1;
3353     break;
3354   default:
3355     return false;
3356   }
3357 
3358   ExprResult Arg = TheCall->getArg(OrderIndex);
3359   auto ArgExpr = Arg.get();
3360   Expr::EvalResult ArgResult;
3361 
3362   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3363     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3364            << ArgExpr->getType();
3365   int ord = ArgResult.Val.getInt().getZExtValue();
3366 
3367   // Check valididty of memory ordering as per C11 / C++11's memody model.
3368   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3369   case llvm::AtomicOrderingCABI::acquire:
3370   case llvm::AtomicOrderingCABI::release:
3371   case llvm::AtomicOrderingCABI::acq_rel:
3372   case llvm::AtomicOrderingCABI::seq_cst:
3373     break;
3374   default: {
3375     return Diag(ArgExpr->getBeginLoc(),
3376                 diag::warn_atomic_op_has_invalid_memory_order)
3377            << ArgExpr->getSourceRange();
3378   }
3379   }
3380 
3381   Arg = TheCall->getArg(ScopeIndex);
3382   ArgExpr = Arg.get();
3383   Expr::EvalResult ArgResult1;
3384   // Check that sync scope is a constant literal
3385   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3386     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3387            << ArgExpr->getType();
3388 
3389   return false;
3390 }
3391 
3392 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3393                                          unsigned BuiltinID,
3394                                          CallExpr *TheCall) {
3395   // CodeGenFunction can also detect this, but this gives a better error
3396   // message.
3397   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3398   if (Features.find("experimental-v") != StringRef::npos &&
3399       !TI.hasFeature("experimental-v"))
3400     return Diag(TheCall->getBeginLoc(), diag::err_riscvv_builtin_requires_v)
3401            << TheCall->getSourceRange();
3402 
3403   return false;
3404 }
3405 
3406 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3407                                            CallExpr *TheCall) {
3408   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3409     Expr *Arg = TheCall->getArg(0);
3410     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3411       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3412         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3413                << Arg->getSourceRange();
3414   }
3415 
3416   // For intrinsics which take an immediate value as part of the instruction,
3417   // range check them here.
3418   unsigned i = 0, l = 0, u = 0;
3419   switch (BuiltinID) {
3420   default: return false;
3421   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3422   case SystemZ::BI__builtin_s390_verimb:
3423   case SystemZ::BI__builtin_s390_verimh:
3424   case SystemZ::BI__builtin_s390_verimf:
3425   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3426   case SystemZ::BI__builtin_s390_vfaeb:
3427   case SystemZ::BI__builtin_s390_vfaeh:
3428   case SystemZ::BI__builtin_s390_vfaef:
3429   case SystemZ::BI__builtin_s390_vfaebs:
3430   case SystemZ::BI__builtin_s390_vfaehs:
3431   case SystemZ::BI__builtin_s390_vfaefs:
3432   case SystemZ::BI__builtin_s390_vfaezb:
3433   case SystemZ::BI__builtin_s390_vfaezh:
3434   case SystemZ::BI__builtin_s390_vfaezf:
3435   case SystemZ::BI__builtin_s390_vfaezbs:
3436   case SystemZ::BI__builtin_s390_vfaezhs:
3437   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3438   case SystemZ::BI__builtin_s390_vfisb:
3439   case SystemZ::BI__builtin_s390_vfidb:
3440     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3441            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3442   case SystemZ::BI__builtin_s390_vftcisb:
3443   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3444   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3445   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3446   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3447   case SystemZ::BI__builtin_s390_vstrcb:
3448   case SystemZ::BI__builtin_s390_vstrch:
3449   case SystemZ::BI__builtin_s390_vstrcf:
3450   case SystemZ::BI__builtin_s390_vstrczb:
3451   case SystemZ::BI__builtin_s390_vstrczh:
3452   case SystemZ::BI__builtin_s390_vstrczf:
3453   case SystemZ::BI__builtin_s390_vstrcbs:
3454   case SystemZ::BI__builtin_s390_vstrchs:
3455   case SystemZ::BI__builtin_s390_vstrcfs:
3456   case SystemZ::BI__builtin_s390_vstrczbs:
3457   case SystemZ::BI__builtin_s390_vstrczhs:
3458   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3459   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3460   case SystemZ::BI__builtin_s390_vfminsb:
3461   case SystemZ::BI__builtin_s390_vfmaxsb:
3462   case SystemZ::BI__builtin_s390_vfmindb:
3463   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3464   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3465   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3466   }
3467   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3468 }
3469 
3470 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3471 /// This checks that the target supports __builtin_cpu_supports and
3472 /// that the string argument is constant and valid.
3473 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3474                                    CallExpr *TheCall) {
3475   Expr *Arg = TheCall->getArg(0);
3476 
3477   // Check if the argument is a string literal.
3478   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3479     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3480            << Arg->getSourceRange();
3481 
3482   // Check the contents of the string.
3483   StringRef Feature =
3484       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3485   if (!TI.validateCpuSupports(Feature))
3486     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3487            << Arg->getSourceRange();
3488   return false;
3489 }
3490 
3491 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3492 /// This checks that the target supports __builtin_cpu_is and
3493 /// that the string argument is constant and valid.
3494 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3495   Expr *Arg = TheCall->getArg(0);
3496 
3497   // Check if the argument is a string literal.
3498   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3499     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3500            << Arg->getSourceRange();
3501 
3502   // Check the contents of the string.
3503   StringRef Feature =
3504       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3505   if (!TI.validateCpuIs(Feature))
3506     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3507            << Arg->getSourceRange();
3508   return false;
3509 }
3510 
3511 // Check if the rounding mode is legal.
3512 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3513   // Indicates if this instruction has rounding control or just SAE.
3514   bool HasRC = false;
3515 
3516   unsigned ArgNum = 0;
3517   switch (BuiltinID) {
3518   default:
3519     return false;
3520   case X86::BI__builtin_ia32_vcvttsd2si32:
3521   case X86::BI__builtin_ia32_vcvttsd2si64:
3522   case X86::BI__builtin_ia32_vcvttsd2usi32:
3523   case X86::BI__builtin_ia32_vcvttsd2usi64:
3524   case X86::BI__builtin_ia32_vcvttss2si32:
3525   case X86::BI__builtin_ia32_vcvttss2si64:
3526   case X86::BI__builtin_ia32_vcvttss2usi32:
3527   case X86::BI__builtin_ia32_vcvttss2usi64:
3528     ArgNum = 1;
3529     break;
3530   case X86::BI__builtin_ia32_maxpd512:
3531   case X86::BI__builtin_ia32_maxps512:
3532   case X86::BI__builtin_ia32_minpd512:
3533   case X86::BI__builtin_ia32_minps512:
3534     ArgNum = 2;
3535     break;
3536   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3537   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3538   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3539   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3540   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3541   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3542   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3543   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3544   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3545   case X86::BI__builtin_ia32_exp2pd_mask:
3546   case X86::BI__builtin_ia32_exp2ps_mask:
3547   case X86::BI__builtin_ia32_getexppd512_mask:
3548   case X86::BI__builtin_ia32_getexpps512_mask:
3549   case X86::BI__builtin_ia32_rcp28pd_mask:
3550   case X86::BI__builtin_ia32_rcp28ps_mask:
3551   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3552   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3553   case X86::BI__builtin_ia32_vcomisd:
3554   case X86::BI__builtin_ia32_vcomiss:
3555   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3556     ArgNum = 3;
3557     break;
3558   case X86::BI__builtin_ia32_cmppd512_mask:
3559   case X86::BI__builtin_ia32_cmpps512_mask:
3560   case X86::BI__builtin_ia32_cmpsd_mask:
3561   case X86::BI__builtin_ia32_cmpss_mask:
3562   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3563   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3564   case X86::BI__builtin_ia32_getexpss128_round_mask:
3565   case X86::BI__builtin_ia32_getmantpd512_mask:
3566   case X86::BI__builtin_ia32_getmantps512_mask:
3567   case X86::BI__builtin_ia32_maxsd_round_mask:
3568   case X86::BI__builtin_ia32_maxss_round_mask:
3569   case X86::BI__builtin_ia32_minsd_round_mask:
3570   case X86::BI__builtin_ia32_minss_round_mask:
3571   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3572   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3573   case X86::BI__builtin_ia32_reducepd512_mask:
3574   case X86::BI__builtin_ia32_reduceps512_mask:
3575   case X86::BI__builtin_ia32_rndscalepd_mask:
3576   case X86::BI__builtin_ia32_rndscaleps_mask:
3577   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3578   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3579     ArgNum = 4;
3580     break;
3581   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3582   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3583   case X86::BI__builtin_ia32_fixupimmps512_mask:
3584   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3585   case X86::BI__builtin_ia32_fixupimmsd_mask:
3586   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3587   case X86::BI__builtin_ia32_fixupimmss_mask:
3588   case X86::BI__builtin_ia32_fixupimmss_maskz:
3589   case X86::BI__builtin_ia32_getmantsd_round_mask:
3590   case X86::BI__builtin_ia32_getmantss_round_mask:
3591   case X86::BI__builtin_ia32_rangepd512_mask:
3592   case X86::BI__builtin_ia32_rangeps512_mask:
3593   case X86::BI__builtin_ia32_rangesd128_round_mask:
3594   case X86::BI__builtin_ia32_rangess128_round_mask:
3595   case X86::BI__builtin_ia32_reducesd_mask:
3596   case X86::BI__builtin_ia32_reducess_mask:
3597   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3598   case X86::BI__builtin_ia32_rndscaless_round_mask:
3599     ArgNum = 5;
3600     break;
3601   case X86::BI__builtin_ia32_vcvtsd2si64:
3602   case X86::BI__builtin_ia32_vcvtsd2si32:
3603   case X86::BI__builtin_ia32_vcvtsd2usi32:
3604   case X86::BI__builtin_ia32_vcvtsd2usi64:
3605   case X86::BI__builtin_ia32_vcvtss2si32:
3606   case X86::BI__builtin_ia32_vcvtss2si64:
3607   case X86::BI__builtin_ia32_vcvtss2usi32:
3608   case X86::BI__builtin_ia32_vcvtss2usi64:
3609   case X86::BI__builtin_ia32_sqrtpd512:
3610   case X86::BI__builtin_ia32_sqrtps512:
3611     ArgNum = 1;
3612     HasRC = true;
3613     break;
3614   case X86::BI__builtin_ia32_addpd512:
3615   case X86::BI__builtin_ia32_addps512:
3616   case X86::BI__builtin_ia32_divpd512:
3617   case X86::BI__builtin_ia32_divps512:
3618   case X86::BI__builtin_ia32_mulpd512:
3619   case X86::BI__builtin_ia32_mulps512:
3620   case X86::BI__builtin_ia32_subpd512:
3621   case X86::BI__builtin_ia32_subps512:
3622   case X86::BI__builtin_ia32_cvtsi2sd64:
3623   case X86::BI__builtin_ia32_cvtsi2ss32:
3624   case X86::BI__builtin_ia32_cvtsi2ss64:
3625   case X86::BI__builtin_ia32_cvtusi2sd64:
3626   case X86::BI__builtin_ia32_cvtusi2ss32:
3627   case X86::BI__builtin_ia32_cvtusi2ss64:
3628     ArgNum = 2;
3629     HasRC = true;
3630     break;
3631   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3632   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3633   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3634   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3635   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3636   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3637   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3638   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3639   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3640   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3641   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3642   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3643   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3644   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3645   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3646     ArgNum = 3;
3647     HasRC = true;
3648     break;
3649   case X86::BI__builtin_ia32_addss_round_mask:
3650   case X86::BI__builtin_ia32_addsd_round_mask:
3651   case X86::BI__builtin_ia32_divss_round_mask:
3652   case X86::BI__builtin_ia32_divsd_round_mask:
3653   case X86::BI__builtin_ia32_mulss_round_mask:
3654   case X86::BI__builtin_ia32_mulsd_round_mask:
3655   case X86::BI__builtin_ia32_subss_round_mask:
3656   case X86::BI__builtin_ia32_subsd_round_mask:
3657   case X86::BI__builtin_ia32_scalefpd512_mask:
3658   case X86::BI__builtin_ia32_scalefps512_mask:
3659   case X86::BI__builtin_ia32_scalefsd_round_mask:
3660   case X86::BI__builtin_ia32_scalefss_round_mask:
3661   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3662   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3663   case X86::BI__builtin_ia32_sqrtss_round_mask:
3664   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3665   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3666   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3667   case X86::BI__builtin_ia32_vfmaddss3_mask:
3668   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3669   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3670   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3671   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3672   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3673   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3674   case X86::BI__builtin_ia32_vfmaddps512_mask:
3675   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3676   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3677   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3678   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3679   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3680   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3681   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3682   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3683   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3684   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3685   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3686     ArgNum = 4;
3687     HasRC = true;
3688     break;
3689   }
3690 
3691   llvm::APSInt Result;
3692 
3693   // We can't check the value of a dependent argument.
3694   Expr *Arg = TheCall->getArg(ArgNum);
3695   if (Arg->isTypeDependent() || Arg->isValueDependent())
3696     return false;
3697 
3698   // Check constant-ness first.
3699   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3700     return true;
3701 
3702   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3703   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3704   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3705   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3706   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3707       Result == 8/*ROUND_NO_EXC*/ ||
3708       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3709       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3710     return false;
3711 
3712   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3713          << Arg->getSourceRange();
3714 }
3715 
3716 // Check if the gather/scatter scale is legal.
3717 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3718                                              CallExpr *TheCall) {
3719   unsigned ArgNum = 0;
3720   switch (BuiltinID) {
3721   default:
3722     return false;
3723   case X86::BI__builtin_ia32_gatherpfdpd:
3724   case X86::BI__builtin_ia32_gatherpfdps:
3725   case X86::BI__builtin_ia32_gatherpfqpd:
3726   case X86::BI__builtin_ia32_gatherpfqps:
3727   case X86::BI__builtin_ia32_scatterpfdpd:
3728   case X86::BI__builtin_ia32_scatterpfdps:
3729   case X86::BI__builtin_ia32_scatterpfqpd:
3730   case X86::BI__builtin_ia32_scatterpfqps:
3731     ArgNum = 3;
3732     break;
3733   case X86::BI__builtin_ia32_gatherd_pd:
3734   case X86::BI__builtin_ia32_gatherd_pd256:
3735   case X86::BI__builtin_ia32_gatherq_pd:
3736   case X86::BI__builtin_ia32_gatherq_pd256:
3737   case X86::BI__builtin_ia32_gatherd_ps:
3738   case X86::BI__builtin_ia32_gatherd_ps256:
3739   case X86::BI__builtin_ia32_gatherq_ps:
3740   case X86::BI__builtin_ia32_gatherq_ps256:
3741   case X86::BI__builtin_ia32_gatherd_q:
3742   case X86::BI__builtin_ia32_gatherd_q256:
3743   case X86::BI__builtin_ia32_gatherq_q:
3744   case X86::BI__builtin_ia32_gatherq_q256:
3745   case X86::BI__builtin_ia32_gatherd_d:
3746   case X86::BI__builtin_ia32_gatherd_d256:
3747   case X86::BI__builtin_ia32_gatherq_d:
3748   case X86::BI__builtin_ia32_gatherq_d256:
3749   case X86::BI__builtin_ia32_gather3div2df:
3750   case X86::BI__builtin_ia32_gather3div2di:
3751   case X86::BI__builtin_ia32_gather3div4df:
3752   case X86::BI__builtin_ia32_gather3div4di:
3753   case X86::BI__builtin_ia32_gather3div4sf:
3754   case X86::BI__builtin_ia32_gather3div4si:
3755   case X86::BI__builtin_ia32_gather3div8sf:
3756   case X86::BI__builtin_ia32_gather3div8si:
3757   case X86::BI__builtin_ia32_gather3siv2df:
3758   case X86::BI__builtin_ia32_gather3siv2di:
3759   case X86::BI__builtin_ia32_gather3siv4df:
3760   case X86::BI__builtin_ia32_gather3siv4di:
3761   case X86::BI__builtin_ia32_gather3siv4sf:
3762   case X86::BI__builtin_ia32_gather3siv4si:
3763   case X86::BI__builtin_ia32_gather3siv8sf:
3764   case X86::BI__builtin_ia32_gather3siv8si:
3765   case X86::BI__builtin_ia32_gathersiv8df:
3766   case X86::BI__builtin_ia32_gathersiv16sf:
3767   case X86::BI__builtin_ia32_gatherdiv8df:
3768   case X86::BI__builtin_ia32_gatherdiv16sf:
3769   case X86::BI__builtin_ia32_gathersiv8di:
3770   case X86::BI__builtin_ia32_gathersiv16si:
3771   case X86::BI__builtin_ia32_gatherdiv8di:
3772   case X86::BI__builtin_ia32_gatherdiv16si:
3773   case X86::BI__builtin_ia32_scatterdiv2df:
3774   case X86::BI__builtin_ia32_scatterdiv2di:
3775   case X86::BI__builtin_ia32_scatterdiv4df:
3776   case X86::BI__builtin_ia32_scatterdiv4di:
3777   case X86::BI__builtin_ia32_scatterdiv4sf:
3778   case X86::BI__builtin_ia32_scatterdiv4si:
3779   case X86::BI__builtin_ia32_scatterdiv8sf:
3780   case X86::BI__builtin_ia32_scatterdiv8si:
3781   case X86::BI__builtin_ia32_scattersiv2df:
3782   case X86::BI__builtin_ia32_scattersiv2di:
3783   case X86::BI__builtin_ia32_scattersiv4df:
3784   case X86::BI__builtin_ia32_scattersiv4di:
3785   case X86::BI__builtin_ia32_scattersiv4sf:
3786   case X86::BI__builtin_ia32_scattersiv4si:
3787   case X86::BI__builtin_ia32_scattersiv8sf:
3788   case X86::BI__builtin_ia32_scattersiv8si:
3789   case X86::BI__builtin_ia32_scattersiv8df:
3790   case X86::BI__builtin_ia32_scattersiv16sf:
3791   case X86::BI__builtin_ia32_scatterdiv8df:
3792   case X86::BI__builtin_ia32_scatterdiv16sf:
3793   case X86::BI__builtin_ia32_scattersiv8di:
3794   case X86::BI__builtin_ia32_scattersiv16si:
3795   case X86::BI__builtin_ia32_scatterdiv8di:
3796   case X86::BI__builtin_ia32_scatterdiv16si:
3797     ArgNum = 4;
3798     break;
3799   }
3800 
3801   llvm::APSInt Result;
3802 
3803   // We can't check the value of a dependent argument.
3804   Expr *Arg = TheCall->getArg(ArgNum);
3805   if (Arg->isTypeDependent() || Arg->isValueDependent())
3806     return false;
3807 
3808   // Check constant-ness first.
3809   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3810     return true;
3811 
3812   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3813     return false;
3814 
3815   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3816          << Arg->getSourceRange();
3817 }
3818 
3819 enum { TileRegLow = 0, TileRegHigh = 7 };
3820 
3821 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3822                                              ArrayRef<int> ArgNums) {
3823   for (int ArgNum : ArgNums) {
3824     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3825       return true;
3826   }
3827   return false;
3828 }
3829 
3830 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3831                                         ArrayRef<int> ArgNums) {
3832   // Because the max number of tile register is TileRegHigh + 1, so here we use
3833   // each bit to represent the usage of them in bitset.
3834   std::bitset<TileRegHigh + 1> ArgValues;
3835   for (int ArgNum : ArgNums) {
3836     Expr *Arg = TheCall->getArg(ArgNum);
3837     if (Arg->isTypeDependent() || Arg->isValueDependent())
3838       continue;
3839 
3840     llvm::APSInt Result;
3841     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3842       return true;
3843     int ArgExtValue = Result.getExtValue();
3844     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3845            "Incorrect tile register num.");
3846     if (ArgValues.test(ArgExtValue))
3847       return Diag(TheCall->getBeginLoc(),
3848                   diag::err_x86_builtin_tile_arg_duplicate)
3849              << TheCall->getArg(ArgNum)->getSourceRange();
3850     ArgValues.set(ArgExtValue);
3851   }
3852   return false;
3853 }
3854 
3855 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3856                                                 ArrayRef<int> ArgNums) {
3857   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3858          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3859 }
3860 
3861 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3862   switch (BuiltinID) {
3863   default:
3864     return false;
3865   case X86::BI__builtin_ia32_tileloadd64:
3866   case X86::BI__builtin_ia32_tileloaddt164:
3867   case X86::BI__builtin_ia32_tilestored64:
3868   case X86::BI__builtin_ia32_tilezero:
3869     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3870   case X86::BI__builtin_ia32_tdpbssd:
3871   case X86::BI__builtin_ia32_tdpbsud:
3872   case X86::BI__builtin_ia32_tdpbusd:
3873   case X86::BI__builtin_ia32_tdpbuud:
3874   case X86::BI__builtin_ia32_tdpbf16ps:
3875     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3876   }
3877 }
3878 static bool isX86_32Builtin(unsigned BuiltinID) {
3879   // These builtins only work on x86-32 targets.
3880   switch (BuiltinID) {
3881   case X86::BI__builtin_ia32_readeflags_u32:
3882   case X86::BI__builtin_ia32_writeeflags_u32:
3883     return true;
3884   }
3885 
3886   return false;
3887 }
3888 
3889 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3890                                        CallExpr *TheCall) {
3891   if (BuiltinID == X86::BI__builtin_cpu_supports)
3892     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3893 
3894   if (BuiltinID == X86::BI__builtin_cpu_is)
3895     return SemaBuiltinCpuIs(*this, TI, TheCall);
3896 
3897   // Check for 32-bit only builtins on a 64-bit target.
3898   const llvm::Triple &TT = TI.getTriple();
3899   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3900     return Diag(TheCall->getCallee()->getBeginLoc(),
3901                 diag::err_32_bit_builtin_64_bit_tgt);
3902 
3903   // If the intrinsic has rounding or SAE make sure its valid.
3904   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3905     return true;
3906 
3907   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3908   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3909     return true;
3910 
3911   // If the intrinsic has a tile arguments, make sure they are valid.
3912   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3913     return true;
3914 
3915   // For intrinsics which take an immediate value as part of the instruction,
3916   // range check them here.
3917   int i = 0, l = 0, u = 0;
3918   switch (BuiltinID) {
3919   default:
3920     return false;
3921   case X86::BI__builtin_ia32_vec_ext_v2si:
3922   case X86::BI__builtin_ia32_vec_ext_v2di:
3923   case X86::BI__builtin_ia32_vextractf128_pd256:
3924   case X86::BI__builtin_ia32_vextractf128_ps256:
3925   case X86::BI__builtin_ia32_vextractf128_si256:
3926   case X86::BI__builtin_ia32_extract128i256:
3927   case X86::BI__builtin_ia32_extractf64x4_mask:
3928   case X86::BI__builtin_ia32_extracti64x4_mask:
3929   case X86::BI__builtin_ia32_extractf32x8_mask:
3930   case X86::BI__builtin_ia32_extracti32x8_mask:
3931   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3932   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3933   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3934   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3935     i = 1; l = 0; u = 1;
3936     break;
3937   case X86::BI__builtin_ia32_vec_set_v2di:
3938   case X86::BI__builtin_ia32_vinsertf128_pd256:
3939   case X86::BI__builtin_ia32_vinsertf128_ps256:
3940   case X86::BI__builtin_ia32_vinsertf128_si256:
3941   case X86::BI__builtin_ia32_insert128i256:
3942   case X86::BI__builtin_ia32_insertf32x8:
3943   case X86::BI__builtin_ia32_inserti32x8:
3944   case X86::BI__builtin_ia32_insertf64x4:
3945   case X86::BI__builtin_ia32_inserti64x4:
3946   case X86::BI__builtin_ia32_insertf64x2_256:
3947   case X86::BI__builtin_ia32_inserti64x2_256:
3948   case X86::BI__builtin_ia32_insertf32x4_256:
3949   case X86::BI__builtin_ia32_inserti32x4_256:
3950     i = 2; l = 0; u = 1;
3951     break;
3952   case X86::BI__builtin_ia32_vpermilpd:
3953   case X86::BI__builtin_ia32_vec_ext_v4hi:
3954   case X86::BI__builtin_ia32_vec_ext_v4si:
3955   case X86::BI__builtin_ia32_vec_ext_v4sf:
3956   case X86::BI__builtin_ia32_vec_ext_v4di:
3957   case X86::BI__builtin_ia32_extractf32x4_mask:
3958   case X86::BI__builtin_ia32_extracti32x4_mask:
3959   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3960   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3961     i = 1; l = 0; u = 3;
3962     break;
3963   case X86::BI_mm_prefetch:
3964   case X86::BI__builtin_ia32_vec_ext_v8hi:
3965   case X86::BI__builtin_ia32_vec_ext_v8si:
3966     i = 1; l = 0; u = 7;
3967     break;
3968   case X86::BI__builtin_ia32_sha1rnds4:
3969   case X86::BI__builtin_ia32_blendpd:
3970   case X86::BI__builtin_ia32_shufpd:
3971   case X86::BI__builtin_ia32_vec_set_v4hi:
3972   case X86::BI__builtin_ia32_vec_set_v4si:
3973   case X86::BI__builtin_ia32_vec_set_v4di:
3974   case X86::BI__builtin_ia32_shuf_f32x4_256:
3975   case X86::BI__builtin_ia32_shuf_f64x2_256:
3976   case X86::BI__builtin_ia32_shuf_i32x4_256:
3977   case X86::BI__builtin_ia32_shuf_i64x2_256:
3978   case X86::BI__builtin_ia32_insertf64x2_512:
3979   case X86::BI__builtin_ia32_inserti64x2_512:
3980   case X86::BI__builtin_ia32_insertf32x4:
3981   case X86::BI__builtin_ia32_inserti32x4:
3982     i = 2; l = 0; u = 3;
3983     break;
3984   case X86::BI__builtin_ia32_vpermil2pd:
3985   case X86::BI__builtin_ia32_vpermil2pd256:
3986   case X86::BI__builtin_ia32_vpermil2ps:
3987   case X86::BI__builtin_ia32_vpermil2ps256:
3988     i = 3; l = 0; u = 3;
3989     break;
3990   case X86::BI__builtin_ia32_cmpb128_mask:
3991   case X86::BI__builtin_ia32_cmpw128_mask:
3992   case X86::BI__builtin_ia32_cmpd128_mask:
3993   case X86::BI__builtin_ia32_cmpq128_mask:
3994   case X86::BI__builtin_ia32_cmpb256_mask:
3995   case X86::BI__builtin_ia32_cmpw256_mask:
3996   case X86::BI__builtin_ia32_cmpd256_mask:
3997   case X86::BI__builtin_ia32_cmpq256_mask:
3998   case X86::BI__builtin_ia32_cmpb512_mask:
3999   case X86::BI__builtin_ia32_cmpw512_mask:
4000   case X86::BI__builtin_ia32_cmpd512_mask:
4001   case X86::BI__builtin_ia32_cmpq512_mask:
4002   case X86::BI__builtin_ia32_ucmpb128_mask:
4003   case X86::BI__builtin_ia32_ucmpw128_mask:
4004   case X86::BI__builtin_ia32_ucmpd128_mask:
4005   case X86::BI__builtin_ia32_ucmpq128_mask:
4006   case X86::BI__builtin_ia32_ucmpb256_mask:
4007   case X86::BI__builtin_ia32_ucmpw256_mask:
4008   case X86::BI__builtin_ia32_ucmpd256_mask:
4009   case X86::BI__builtin_ia32_ucmpq256_mask:
4010   case X86::BI__builtin_ia32_ucmpb512_mask:
4011   case X86::BI__builtin_ia32_ucmpw512_mask:
4012   case X86::BI__builtin_ia32_ucmpd512_mask:
4013   case X86::BI__builtin_ia32_ucmpq512_mask:
4014   case X86::BI__builtin_ia32_vpcomub:
4015   case X86::BI__builtin_ia32_vpcomuw:
4016   case X86::BI__builtin_ia32_vpcomud:
4017   case X86::BI__builtin_ia32_vpcomuq:
4018   case X86::BI__builtin_ia32_vpcomb:
4019   case X86::BI__builtin_ia32_vpcomw:
4020   case X86::BI__builtin_ia32_vpcomd:
4021   case X86::BI__builtin_ia32_vpcomq:
4022   case X86::BI__builtin_ia32_vec_set_v8hi:
4023   case X86::BI__builtin_ia32_vec_set_v8si:
4024     i = 2; l = 0; u = 7;
4025     break;
4026   case X86::BI__builtin_ia32_vpermilpd256:
4027   case X86::BI__builtin_ia32_roundps:
4028   case X86::BI__builtin_ia32_roundpd:
4029   case X86::BI__builtin_ia32_roundps256:
4030   case X86::BI__builtin_ia32_roundpd256:
4031   case X86::BI__builtin_ia32_getmantpd128_mask:
4032   case X86::BI__builtin_ia32_getmantpd256_mask:
4033   case X86::BI__builtin_ia32_getmantps128_mask:
4034   case X86::BI__builtin_ia32_getmantps256_mask:
4035   case X86::BI__builtin_ia32_getmantpd512_mask:
4036   case X86::BI__builtin_ia32_getmantps512_mask:
4037   case X86::BI__builtin_ia32_vec_ext_v16qi:
4038   case X86::BI__builtin_ia32_vec_ext_v16hi:
4039     i = 1; l = 0; u = 15;
4040     break;
4041   case X86::BI__builtin_ia32_pblendd128:
4042   case X86::BI__builtin_ia32_blendps:
4043   case X86::BI__builtin_ia32_blendpd256:
4044   case X86::BI__builtin_ia32_shufpd256:
4045   case X86::BI__builtin_ia32_roundss:
4046   case X86::BI__builtin_ia32_roundsd:
4047   case X86::BI__builtin_ia32_rangepd128_mask:
4048   case X86::BI__builtin_ia32_rangepd256_mask:
4049   case X86::BI__builtin_ia32_rangepd512_mask:
4050   case X86::BI__builtin_ia32_rangeps128_mask:
4051   case X86::BI__builtin_ia32_rangeps256_mask:
4052   case X86::BI__builtin_ia32_rangeps512_mask:
4053   case X86::BI__builtin_ia32_getmantsd_round_mask:
4054   case X86::BI__builtin_ia32_getmantss_round_mask:
4055   case X86::BI__builtin_ia32_vec_set_v16qi:
4056   case X86::BI__builtin_ia32_vec_set_v16hi:
4057     i = 2; l = 0; u = 15;
4058     break;
4059   case X86::BI__builtin_ia32_vec_ext_v32qi:
4060     i = 1; l = 0; u = 31;
4061     break;
4062   case X86::BI__builtin_ia32_cmpps:
4063   case X86::BI__builtin_ia32_cmpss:
4064   case X86::BI__builtin_ia32_cmppd:
4065   case X86::BI__builtin_ia32_cmpsd:
4066   case X86::BI__builtin_ia32_cmpps256:
4067   case X86::BI__builtin_ia32_cmppd256:
4068   case X86::BI__builtin_ia32_cmpps128_mask:
4069   case X86::BI__builtin_ia32_cmppd128_mask:
4070   case X86::BI__builtin_ia32_cmpps256_mask:
4071   case X86::BI__builtin_ia32_cmppd256_mask:
4072   case X86::BI__builtin_ia32_cmpps512_mask:
4073   case X86::BI__builtin_ia32_cmppd512_mask:
4074   case X86::BI__builtin_ia32_cmpsd_mask:
4075   case X86::BI__builtin_ia32_cmpss_mask:
4076   case X86::BI__builtin_ia32_vec_set_v32qi:
4077     i = 2; l = 0; u = 31;
4078     break;
4079   case X86::BI__builtin_ia32_permdf256:
4080   case X86::BI__builtin_ia32_permdi256:
4081   case X86::BI__builtin_ia32_permdf512:
4082   case X86::BI__builtin_ia32_permdi512:
4083   case X86::BI__builtin_ia32_vpermilps:
4084   case X86::BI__builtin_ia32_vpermilps256:
4085   case X86::BI__builtin_ia32_vpermilpd512:
4086   case X86::BI__builtin_ia32_vpermilps512:
4087   case X86::BI__builtin_ia32_pshufd:
4088   case X86::BI__builtin_ia32_pshufd256:
4089   case X86::BI__builtin_ia32_pshufd512:
4090   case X86::BI__builtin_ia32_pshufhw:
4091   case X86::BI__builtin_ia32_pshufhw256:
4092   case X86::BI__builtin_ia32_pshufhw512:
4093   case X86::BI__builtin_ia32_pshuflw:
4094   case X86::BI__builtin_ia32_pshuflw256:
4095   case X86::BI__builtin_ia32_pshuflw512:
4096   case X86::BI__builtin_ia32_vcvtps2ph:
4097   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4098   case X86::BI__builtin_ia32_vcvtps2ph256:
4099   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4100   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4101   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4102   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4103   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4104   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4105   case X86::BI__builtin_ia32_rndscaleps_mask:
4106   case X86::BI__builtin_ia32_rndscalepd_mask:
4107   case X86::BI__builtin_ia32_reducepd128_mask:
4108   case X86::BI__builtin_ia32_reducepd256_mask:
4109   case X86::BI__builtin_ia32_reducepd512_mask:
4110   case X86::BI__builtin_ia32_reduceps128_mask:
4111   case X86::BI__builtin_ia32_reduceps256_mask:
4112   case X86::BI__builtin_ia32_reduceps512_mask:
4113   case X86::BI__builtin_ia32_prold512:
4114   case X86::BI__builtin_ia32_prolq512:
4115   case X86::BI__builtin_ia32_prold128:
4116   case X86::BI__builtin_ia32_prold256:
4117   case X86::BI__builtin_ia32_prolq128:
4118   case X86::BI__builtin_ia32_prolq256:
4119   case X86::BI__builtin_ia32_prord512:
4120   case X86::BI__builtin_ia32_prorq512:
4121   case X86::BI__builtin_ia32_prord128:
4122   case X86::BI__builtin_ia32_prord256:
4123   case X86::BI__builtin_ia32_prorq128:
4124   case X86::BI__builtin_ia32_prorq256:
4125   case X86::BI__builtin_ia32_fpclasspd128_mask:
4126   case X86::BI__builtin_ia32_fpclasspd256_mask:
4127   case X86::BI__builtin_ia32_fpclassps128_mask:
4128   case X86::BI__builtin_ia32_fpclassps256_mask:
4129   case X86::BI__builtin_ia32_fpclassps512_mask:
4130   case X86::BI__builtin_ia32_fpclasspd512_mask:
4131   case X86::BI__builtin_ia32_fpclasssd_mask:
4132   case X86::BI__builtin_ia32_fpclassss_mask:
4133   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4134   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4135   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4136   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4137   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4138   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4139   case X86::BI__builtin_ia32_kshiftliqi:
4140   case X86::BI__builtin_ia32_kshiftlihi:
4141   case X86::BI__builtin_ia32_kshiftlisi:
4142   case X86::BI__builtin_ia32_kshiftlidi:
4143   case X86::BI__builtin_ia32_kshiftriqi:
4144   case X86::BI__builtin_ia32_kshiftrihi:
4145   case X86::BI__builtin_ia32_kshiftrisi:
4146   case X86::BI__builtin_ia32_kshiftridi:
4147     i = 1; l = 0; u = 255;
4148     break;
4149   case X86::BI__builtin_ia32_vperm2f128_pd256:
4150   case X86::BI__builtin_ia32_vperm2f128_ps256:
4151   case X86::BI__builtin_ia32_vperm2f128_si256:
4152   case X86::BI__builtin_ia32_permti256:
4153   case X86::BI__builtin_ia32_pblendw128:
4154   case X86::BI__builtin_ia32_pblendw256:
4155   case X86::BI__builtin_ia32_blendps256:
4156   case X86::BI__builtin_ia32_pblendd256:
4157   case X86::BI__builtin_ia32_palignr128:
4158   case X86::BI__builtin_ia32_palignr256:
4159   case X86::BI__builtin_ia32_palignr512:
4160   case X86::BI__builtin_ia32_alignq512:
4161   case X86::BI__builtin_ia32_alignd512:
4162   case X86::BI__builtin_ia32_alignd128:
4163   case X86::BI__builtin_ia32_alignd256:
4164   case X86::BI__builtin_ia32_alignq128:
4165   case X86::BI__builtin_ia32_alignq256:
4166   case X86::BI__builtin_ia32_vcomisd:
4167   case X86::BI__builtin_ia32_vcomiss:
4168   case X86::BI__builtin_ia32_shuf_f32x4:
4169   case X86::BI__builtin_ia32_shuf_f64x2:
4170   case X86::BI__builtin_ia32_shuf_i32x4:
4171   case X86::BI__builtin_ia32_shuf_i64x2:
4172   case X86::BI__builtin_ia32_shufpd512:
4173   case X86::BI__builtin_ia32_shufps:
4174   case X86::BI__builtin_ia32_shufps256:
4175   case X86::BI__builtin_ia32_shufps512:
4176   case X86::BI__builtin_ia32_dbpsadbw128:
4177   case X86::BI__builtin_ia32_dbpsadbw256:
4178   case X86::BI__builtin_ia32_dbpsadbw512:
4179   case X86::BI__builtin_ia32_vpshldd128:
4180   case X86::BI__builtin_ia32_vpshldd256:
4181   case X86::BI__builtin_ia32_vpshldd512:
4182   case X86::BI__builtin_ia32_vpshldq128:
4183   case X86::BI__builtin_ia32_vpshldq256:
4184   case X86::BI__builtin_ia32_vpshldq512:
4185   case X86::BI__builtin_ia32_vpshldw128:
4186   case X86::BI__builtin_ia32_vpshldw256:
4187   case X86::BI__builtin_ia32_vpshldw512:
4188   case X86::BI__builtin_ia32_vpshrdd128:
4189   case X86::BI__builtin_ia32_vpshrdd256:
4190   case X86::BI__builtin_ia32_vpshrdd512:
4191   case X86::BI__builtin_ia32_vpshrdq128:
4192   case X86::BI__builtin_ia32_vpshrdq256:
4193   case X86::BI__builtin_ia32_vpshrdq512:
4194   case X86::BI__builtin_ia32_vpshrdw128:
4195   case X86::BI__builtin_ia32_vpshrdw256:
4196   case X86::BI__builtin_ia32_vpshrdw512:
4197     i = 2; l = 0; u = 255;
4198     break;
4199   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4200   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4201   case X86::BI__builtin_ia32_fixupimmps512_mask:
4202   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4203   case X86::BI__builtin_ia32_fixupimmsd_mask:
4204   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4205   case X86::BI__builtin_ia32_fixupimmss_mask:
4206   case X86::BI__builtin_ia32_fixupimmss_maskz:
4207   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4208   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4209   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4210   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4211   case X86::BI__builtin_ia32_fixupimmps128_mask:
4212   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4213   case X86::BI__builtin_ia32_fixupimmps256_mask:
4214   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4215   case X86::BI__builtin_ia32_pternlogd512_mask:
4216   case X86::BI__builtin_ia32_pternlogd512_maskz:
4217   case X86::BI__builtin_ia32_pternlogq512_mask:
4218   case X86::BI__builtin_ia32_pternlogq512_maskz:
4219   case X86::BI__builtin_ia32_pternlogd128_mask:
4220   case X86::BI__builtin_ia32_pternlogd128_maskz:
4221   case X86::BI__builtin_ia32_pternlogd256_mask:
4222   case X86::BI__builtin_ia32_pternlogd256_maskz:
4223   case X86::BI__builtin_ia32_pternlogq128_mask:
4224   case X86::BI__builtin_ia32_pternlogq128_maskz:
4225   case X86::BI__builtin_ia32_pternlogq256_mask:
4226   case X86::BI__builtin_ia32_pternlogq256_maskz:
4227     i = 3; l = 0; u = 255;
4228     break;
4229   case X86::BI__builtin_ia32_gatherpfdpd:
4230   case X86::BI__builtin_ia32_gatherpfdps:
4231   case X86::BI__builtin_ia32_gatherpfqpd:
4232   case X86::BI__builtin_ia32_gatherpfqps:
4233   case X86::BI__builtin_ia32_scatterpfdpd:
4234   case X86::BI__builtin_ia32_scatterpfdps:
4235   case X86::BI__builtin_ia32_scatterpfqpd:
4236   case X86::BI__builtin_ia32_scatterpfqps:
4237     i = 4; l = 2; u = 3;
4238     break;
4239   case X86::BI__builtin_ia32_reducesd_mask:
4240   case X86::BI__builtin_ia32_reducess_mask:
4241   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4242   case X86::BI__builtin_ia32_rndscaless_round_mask:
4243     i = 4; l = 0; u = 255;
4244     break;
4245   }
4246 
4247   // Note that we don't force a hard error on the range check here, allowing
4248   // template-generated or macro-generated dead code to potentially have out-of-
4249   // range values. These need to code generate, but don't need to necessarily
4250   // make any sense. We use a warning that defaults to an error.
4251   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4252 }
4253 
4254 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4255 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4256 /// Returns true when the format fits the function and the FormatStringInfo has
4257 /// been populated.
4258 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4259                                FormatStringInfo *FSI) {
4260   FSI->HasVAListArg = Format->getFirstArg() == 0;
4261   FSI->FormatIdx = Format->getFormatIdx() - 1;
4262   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4263 
4264   // The way the format attribute works in GCC, the implicit this argument
4265   // of member functions is counted. However, it doesn't appear in our own
4266   // lists, so decrement format_idx in that case.
4267   if (IsCXXMember) {
4268     if(FSI->FormatIdx == 0)
4269       return false;
4270     --FSI->FormatIdx;
4271     if (FSI->FirstDataArg != 0)
4272       --FSI->FirstDataArg;
4273   }
4274   return true;
4275 }
4276 
4277 /// Checks if a the given expression evaluates to null.
4278 ///
4279 /// Returns true if the value evaluates to null.
4280 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4281   // If the expression has non-null type, it doesn't evaluate to null.
4282   if (auto nullability
4283         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4284     if (*nullability == NullabilityKind::NonNull)
4285       return false;
4286   }
4287 
4288   // As a special case, transparent unions initialized with zero are
4289   // considered null for the purposes of the nonnull attribute.
4290   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4291     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4292       if (const CompoundLiteralExpr *CLE =
4293           dyn_cast<CompoundLiteralExpr>(Expr))
4294         if (const InitListExpr *ILE =
4295             dyn_cast<InitListExpr>(CLE->getInitializer()))
4296           Expr = ILE->getInit(0);
4297   }
4298 
4299   bool Result;
4300   return (!Expr->isValueDependent() &&
4301           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4302           !Result);
4303 }
4304 
4305 static void CheckNonNullArgument(Sema &S,
4306                                  const Expr *ArgExpr,
4307                                  SourceLocation CallSiteLoc) {
4308   if (CheckNonNullExpr(S, ArgExpr))
4309     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4310                           S.PDiag(diag::warn_null_arg)
4311                               << ArgExpr->getSourceRange());
4312 }
4313 
4314 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4315   FormatStringInfo FSI;
4316   if ((GetFormatStringType(Format) == FST_NSString) &&
4317       getFormatStringInfo(Format, false, &FSI)) {
4318     Idx = FSI.FormatIdx;
4319     return true;
4320   }
4321   return false;
4322 }
4323 
4324 /// Diagnose use of %s directive in an NSString which is being passed
4325 /// as formatting string to formatting method.
4326 static void
4327 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4328                                         const NamedDecl *FDecl,
4329                                         Expr **Args,
4330                                         unsigned NumArgs) {
4331   unsigned Idx = 0;
4332   bool Format = false;
4333   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4334   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4335     Idx = 2;
4336     Format = true;
4337   }
4338   else
4339     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4340       if (S.GetFormatNSStringIdx(I, Idx)) {
4341         Format = true;
4342         break;
4343       }
4344     }
4345   if (!Format || NumArgs <= Idx)
4346     return;
4347   const Expr *FormatExpr = Args[Idx];
4348   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4349     FormatExpr = CSCE->getSubExpr();
4350   const StringLiteral *FormatString;
4351   if (const ObjCStringLiteral *OSL =
4352       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4353     FormatString = OSL->getString();
4354   else
4355     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4356   if (!FormatString)
4357     return;
4358   if (S.FormatStringHasSArg(FormatString)) {
4359     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4360       << "%s" << 1 << 1;
4361     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4362       << FDecl->getDeclName();
4363   }
4364 }
4365 
4366 /// Determine whether the given type has a non-null nullability annotation.
4367 static bool isNonNullType(ASTContext &ctx, QualType type) {
4368   if (auto nullability = type->getNullability(ctx))
4369     return *nullability == NullabilityKind::NonNull;
4370 
4371   return false;
4372 }
4373 
4374 static void CheckNonNullArguments(Sema &S,
4375                                   const NamedDecl *FDecl,
4376                                   const FunctionProtoType *Proto,
4377                                   ArrayRef<const Expr *> Args,
4378                                   SourceLocation CallSiteLoc) {
4379   assert((FDecl || Proto) && "Need a function declaration or prototype");
4380 
4381   // Already checked by by constant evaluator.
4382   if (S.isConstantEvaluated())
4383     return;
4384   // Check the attributes attached to the method/function itself.
4385   llvm::SmallBitVector NonNullArgs;
4386   if (FDecl) {
4387     // Handle the nonnull attribute on the function/method declaration itself.
4388     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4389       if (!NonNull->args_size()) {
4390         // Easy case: all pointer arguments are nonnull.
4391         for (const auto *Arg : Args)
4392           if (S.isValidPointerAttrType(Arg->getType()))
4393             CheckNonNullArgument(S, Arg, CallSiteLoc);
4394         return;
4395       }
4396 
4397       for (const ParamIdx &Idx : NonNull->args()) {
4398         unsigned IdxAST = Idx.getASTIndex();
4399         if (IdxAST >= Args.size())
4400           continue;
4401         if (NonNullArgs.empty())
4402           NonNullArgs.resize(Args.size());
4403         NonNullArgs.set(IdxAST);
4404       }
4405     }
4406   }
4407 
4408   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4409     // Handle the nonnull attribute on the parameters of the
4410     // function/method.
4411     ArrayRef<ParmVarDecl*> parms;
4412     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4413       parms = FD->parameters();
4414     else
4415       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4416 
4417     unsigned ParamIndex = 0;
4418     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4419          I != E; ++I, ++ParamIndex) {
4420       const ParmVarDecl *PVD = *I;
4421       if (PVD->hasAttr<NonNullAttr>() ||
4422           isNonNullType(S.Context, PVD->getType())) {
4423         if (NonNullArgs.empty())
4424           NonNullArgs.resize(Args.size());
4425 
4426         NonNullArgs.set(ParamIndex);
4427       }
4428     }
4429   } else {
4430     // If we have a non-function, non-method declaration but no
4431     // function prototype, try to dig out the function prototype.
4432     if (!Proto) {
4433       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4434         QualType type = VD->getType().getNonReferenceType();
4435         if (auto pointerType = type->getAs<PointerType>())
4436           type = pointerType->getPointeeType();
4437         else if (auto blockType = type->getAs<BlockPointerType>())
4438           type = blockType->getPointeeType();
4439         // FIXME: data member pointers?
4440 
4441         // Dig out the function prototype, if there is one.
4442         Proto = type->getAs<FunctionProtoType>();
4443       }
4444     }
4445 
4446     // Fill in non-null argument information from the nullability
4447     // information on the parameter types (if we have them).
4448     if (Proto) {
4449       unsigned Index = 0;
4450       for (auto paramType : Proto->getParamTypes()) {
4451         if (isNonNullType(S.Context, paramType)) {
4452           if (NonNullArgs.empty())
4453             NonNullArgs.resize(Args.size());
4454 
4455           NonNullArgs.set(Index);
4456         }
4457 
4458         ++Index;
4459       }
4460     }
4461   }
4462 
4463   // Check for non-null arguments.
4464   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4465        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4466     if (NonNullArgs[ArgIndex])
4467       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4468   }
4469 }
4470 
4471 /// Handles the checks for format strings, non-POD arguments to vararg
4472 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4473 /// attributes.
4474 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4475                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4476                      bool IsMemberFunction, SourceLocation Loc,
4477                      SourceRange Range, VariadicCallType CallType) {
4478   // FIXME: We should check as much as we can in the template definition.
4479   if (CurContext->isDependentContext())
4480     return;
4481 
4482   // Printf and scanf checking.
4483   llvm::SmallBitVector CheckedVarArgs;
4484   if (FDecl) {
4485     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4486       // Only create vector if there are format attributes.
4487       CheckedVarArgs.resize(Args.size());
4488 
4489       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4490                            CheckedVarArgs);
4491     }
4492   }
4493 
4494   // Refuse POD arguments that weren't caught by the format string
4495   // checks above.
4496   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4497   if (CallType != VariadicDoesNotApply &&
4498       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4499     unsigned NumParams = Proto ? Proto->getNumParams()
4500                        : FDecl && isa<FunctionDecl>(FDecl)
4501                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4502                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4503                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4504                        : 0;
4505 
4506     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4507       // Args[ArgIdx] can be null in malformed code.
4508       if (const Expr *Arg = Args[ArgIdx]) {
4509         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4510           checkVariadicArgument(Arg, CallType);
4511       }
4512     }
4513   }
4514 
4515   if (FDecl || Proto) {
4516     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4517 
4518     // Type safety checking.
4519     if (FDecl) {
4520       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4521         CheckArgumentWithTypeTag(I, Args, Loc);
4522     }
4523   }
4524 
4525   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4526     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4527     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4528     if (!Arg->isValueDependent()) {
4529       Expr::EvalResult Align;
4530       if (Arg->EvaluateAsInt(Align, Context)) {
4531         const llvm::APSInt &I = Align.Val.getInt();
4532         if (!I.isPowerOf2())
4533           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4534               << Arg->getSourceRange();
4535 
4536         if (I > Sema::MaximumAlignment)
4537           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4538               << Arg->getSourceRange() << Sema::MaximumAlignment;
4539       }
4540     }
4541   }
4542 
4543   if (FD)
4544     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4545 }
4546 
4547 /// CheckConstructorCall - Check a constructor call for correctness and safety
4548 /// properties not enforced by the C type system.
4549 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4550                                 ArrayRef<const Expr *> Args,
4551                                 const FunctionProtoType *Proto,
4552                                 SourceLocation Loc) {
4553   VariadicCallType CallType =
4554     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4555   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4556             Loc, SourceRange(), CallType);
4557 }
4558 
4559 /// CheckFunctionCall - Check a direct function call for various correctness
4560 /// and safety properties not strictly enforced by the C type system.
4561 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4562                              const FunctionProtoType *Proto) {
4563   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4564                               isa<CXXMethodDecl>(FDecl);
4565   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4566                           IsMemberOperatorCall;
4567   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4568                                                   TheCall->getCallee());
4569   Expr** Args = TheCall->getArgs();
4570   unsigned NumArgs = TheCall->getNumArgs();
4571 
4572   Expr *ImplicitThis = nullptr;
4573   if (IsMemberOperatorCall) {
4574     // If this is a call to a member operator, hide the first argument
4575     // from checkCall.
4576     // FIXME: Our choice of AST representation here is less than ideal.
4577     ImplicitThis = Args[0];
4578     ++Args;
4579     --NumArgs;
4580   } else if (IsMemberFunction)
4581     ImplicitThis =
4582         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4583 
4584   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4585             IsMemberFunction, TheCall->getRParenLoc(),
4586             TheCall->getCallee()->getSourceRange(), CallType);
4587 
4588   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4589   // None of the checks below are needed for functions that don't have
4590   // simple names (e.g., C++ conversion functions).
4591   if (!FnInfo)
4592     return false;
4593 
4594   CheckTCBEnforcement(TheCall, FDecl);
4595 
4596   CheckAbsoluteValueFunction(TheCall, FDecl);
4597   CheckMaxUnsignedZero(TheCall, FDecl);
4598 
4599   if (getLangOpts().ObjC)
4600     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4601 
4602   unsigned CMId = FDecl->getMemoryFunctionKind();
4603 
4604   // Handle memory setting and copying functions.
4605   switch (CMId) {
4606   case 0:
4607     return false;
4608   case Builtin::BIstrlcpy: // fallthrough
4609   case Builtin::BIstrlcat:
4610     CheckStrlcpycatArguments(TheCall, FnInfo);
4611     break;
4612   case Builtin::BIstrncat:
4613     CheckStrncatArguments(TheCall, FnInfo);
4614     break;
4615   case Builtin::BIfree:
4616     CheckFreeArguments(TheCall);
4617     break;
4618   default:
4619     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4620   }
4621 
4622   return false;
4623 }
4624 
4625 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4626                                ArrayRef<const Expr *> Args) {
4627   VariadicCallType CallType =
4628       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4629 
4630   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4631             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4632             CallType);
4633 
4634   return false;
4635 }
4636 
4637 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4638                             const FunctionProtoType *Proto) {
4639   QualType Ty;
4640   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4641     Ty = V->getType().getNonReferenceType();
4642   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4643     Ty = F->getType().getNonReferenceType();
4644   else
4645     return false;
4646 
4647   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4648       !Ty->isFunctionProtoType())
4649     return false;
4650 
4651   VariadicCallType CallType;
4652   if (!Proto || !Proto->isVariadic()) {
4653     CallType = VariadicDoesNotApply;
4654   } else if (Ty->isBlockPointerType()) {
4655     CallType = VariadicBlock;
4656   } else { // Ty->isFunctionPointerType()
4657     CallType = VariadicFunction;
4658   }
4659 
4660   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4661             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4662             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4663             TheCall->getCallee()->getSourceRange(), CallType);
4664 
4665   return false;
4666 }
4667 
4668 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4669 /// such as function pointers returned from functions.
4670 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4671   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4672                                                   TheCall->getCallee());
4673   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4674             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4675             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4676             TheCall->getCallee()->getSourceRange(), CallType);
4677 
4678   return false;
4679 }
4680 
4681 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4682   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4683     return false;
4684 
4685   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4686   switch (Op) {
4687   case AtomicExpr::AO__c11_atomic_init:
4688   case AtomicExpr::AO__opencl_atomic_init:
4689     llvm_unreachable("There is no ordering argument for an init");
4690 
4691   case AtomicExpr::AO__c11_atomic_load:
4692   case AtomicExpr::AO__opencl_atomic_load:
4693   case AtomicExpr::AO__atomic_load_n:
4694   case AtomicExpr::AO__atomic_load:
4695     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4696            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4697 
4698   case AtomicExpr::AO__c11_atomic_store:
4699   case AtomicExpr::AO__opencl_atomic_store:
4700   case AtomicExpr::AO__atomic_store:
4701   case AtomicExpr::AO__atomic_store_n:
4702     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4703            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4704            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4705 
4706   default:
4707     return true;
4708   }
4709 }
4710 
4711 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4712                                          AtomicExpr::AtomicOp Op) {
4713   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4714   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4715   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4716   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4717                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4718                          Op);
4719 }
4720 
4721 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4722                                  SourceLocation RParenLoc, MultiExprArg Args,
4723                                  AtomicExpr::AtomicOp Op,
4724                                  AtomicArgumentOrder ArgOrder) {
4725   // All the non-OpenCL operations take one of the following forms.
4726   // The OpenCL operations take the __c11 forms with one extra argument for
4727   // synchronization scope.
4728   enum {
4729     // C    __c11_atomic_init(A *, C)
4730     Init,
4731 
4732     // C    __c11_atomic_load(A *, int)
4733     Load,
4734 
4735     // void __atomic_load(A *, CP, int)
4736     LoadCopy,
4737 
4738     // void __atomic_store(A *, CP, int)
4739     Copy,
4740 
4741     // C    __c11_atomic_add(A *, M, int)
4742     Arithmetic,
4743 
4744     // C    __atomic_exchange_n(A *, CP, int)
4745     Xchg,
4746 
4747     // void __atomic_exchange(A *, C *, CP, int)
4748     GNUXchg,
4749 
4750     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4751     C11CmpXchg,
4752 
4753     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4754     GNUCmpXchg
4755   } Form = Init;
4756 
4757   const unsigned NumForm = GNUCmpXchg + 1;
4758   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4759   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4760   // where:
4761   //   C is an appropriate type,
4762   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4763   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4764   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4765   //   the int parameters are for orderings.
4766 
4767   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4768       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4769       "need to update code for modified forms");
4770   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4771                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4772                         AtomicExpr::AO__atomic_load,
4773                 "need to update code for modified C11 atomics");
4774   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4775                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4776   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4777                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4778                IsOpenCL;
4779   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4780              Op == AtomicExpr::AO__atomic_store_n ||
4781              Op == AtomicExpr::AO__atomic_exchange_n ||
4782              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4783   bool IsAddSub = false;
4784 
4785   switch (Op) {
4786   case AtomicExpr::AO__c11_atomic_init:
4787   case AtomicExpr::AO__opencl_atomic_init:
4788     Form = Init;
4789     break;
4790 
4791   case AtomicExpr::AO__c11_atomic_load:
4792   case AtomicExpr::AO__opencl_atomic_load:
4793   case AtomicExpr::AO__atomic_load_n:
4794     Form = Load;
4795     break;
4796 
4797   case AtomicExpr::AO__atomic_load:
4798     Form = LoadCopy;
4799     break;
4800 
4801   case AtomicExpr::AO__c11_atomic_store:
4802   case AtomicExpr::AO__opencl_atomic_store:
4803   case AtomicExpr::AO__atomic_store:
4804   case AtomicExpr::AO__atomic_store_n:
4805     Form = Copy;
4806     break;
4807 
4808   case AtomicExpr::AO__c11_atomic_fetch_add:
4809   case AtomicExpr::AO__c11_atomic_fetch_sub:
4810   case AtomicExpr::AO__opencl_atomic_fetch_add:
4811   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4812   case AtomicExpr::AO__atomic_fetch_add:
4813   case AtomicExpr::AO__atomic_fetch_sub:
4814   case AtomicExpr::AO__atomic_add_fetch:
4815   case AtomicExpr::AO__atomic_sub_fetch:
4816     IsAddSub = true;
4817     LLVM_FALLTHROUGH;
4818   case AtomicExpr::AO__c11_atomic_fetch_and:
4819   case AtomicExpr::AO__c11_atomic_fetch_or:
4820   case AtomicExpr::AO__c11_atomic_fetch_xor:
4821   case AtomicExpr::AO__opencl_atomic_fetch_and:
4822   case AtomicExpr::AO__opencl_atomic_fetch_or:
4823   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4824   case AtomicExpr::AO__atomic_fetch_and:
4825   case AtomicExpr::AO__atomic_fetch_or:
4826   case AtomicExpr::AO__atomic_fetch_xor:
4827   case AtomicExpr::AO__atomic_fetch_nand:
4828   case AtomicExpr::AO__atomic_and_fetch:
4829   case AtomicExpr::AO__atomic_or_fetch:
4830   case AtomicExpr::AO__atomic_xor_fetch:
4831   case AtomicExpr::AO__atomic_nand_fetch:
4832   case AtomicExpr::AO__c11_atomic_fetch_min:
4833   case AtomicExpr::AO__c11_atomic_fetch_max:
4834   case AtomicExpr::AO__opencl_atomic_fetch_min:
4835   case AtomicExpr::AO__opencl_atomic_fetch_max:
4836   case AtomicExpr::AO__atomic_min_fetch:
4837   case AtomicExpr::AO__atomic_max_fetch:
4838   case AtomicExpr::AO__atomic_fetch_min:
4839   case AtomicExpr::AO__atomic_fetch_max:
4840     Form = Arithmetic;
4841     break;
4842 
4843   case AtomicExpr::AO__c11_atomic_exchange:
4844   case AtomicExpr::AO__opencl_atomic_exchange:
4845   case AtomicExpr::AO__atomic_exchange_n:
4846     Form = Xchg;
4847     break;
4848 
4849   case AtomicExpr::AO__atomic_exchange:
4850     Form = GNUXchg;
4851     break;
4852 
4853   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4854   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4855   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4856   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4857     Form = C11CmpXchg;
4858     break;
4859 
4860   case AtomicExpr::AO__atomic_compare_exchange:
4861   case AtomicExpr::AO__atomic_compare_exchange_n:
4862     Form = GNUCmpXchg;
4863     break;
4864   }
4865 
4866   unsigned AdjustedNumArgs = NumArgs[Form];
4867   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4868     ++AdjustedNumArgs;
4869   // Check we have the right number of arguments.
4870   if (Args.size() < AdjustedNumArgs) {
4871     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4872         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4873         << ExprRange;
4874     return ExprError();
4875   } else if (Args.size() > AdjustedNumArgs) {
4876     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4877          diag::err_typecheck_call_too_many_args)
4878         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4879         << ExprRange;
4880     return ExprError();
4881   }
4882 
4883   // Inspect the first argument of the atomic operation.
4884   Expr *Ptr = Args[0];
4885   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4886   if (ConvertedPtr.isInvalid())
4887     return ExprError();
4888 
4889   Ptr = ConvertedPtr.get();
4890   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4891   if (!pointerType) {
4892     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4893         << Ptr->getType() << Ptr->getSourceRange();
4894     return ExprError();
4895   }
4896 
4897   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4898   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4899   QualType ValType = AtomTy; // 'C'
4900   if (IsC11) {
4901     if (!AtomTy->isAtomicType()) {
4902       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4903           << Ptr->getType() << Ptr->getSourceRange();
4904       return ExprError();
4905     }
4906     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4907         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4908       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4909           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4910           << Ptr->getSourceRange();
4911       return ExprError();
4912     }
4913     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4914   } else if (Form != Load && Form != LoadCopy) {
4915     if (ValType.isConstQualified()) {
4916       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4917           << Ptr->getType() << Ptr->getSourceRange();
4918       return ExprError();
4919     }
4920   }
4921 
4922   // For an arithmetic operation, the implied arithmetic must be well-formed.
4923   if (Form == Arithmetic) {
4924     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4925     if (IsAddSub && !ValType->isIntegerType()
4926         && !ValType->isPointerType()) {
4927       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4928           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4929       return ExprError();
4930     }
4931     if (!IsAddSub && !ValType->isIntegerType()) {
4932       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4933           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4934       return ExprError();
4935     }
4936     if (IsC11 && ValType->isPointerType() &&
4937         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4938                             diag::err_incomplete_type)) {
4939       return ExprError();
4940     }
4941   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4942     // For __atomic_*_n operations, the value type must be a scalar integral or
4943     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4944     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4945         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4946     return ExprError();
4947   }
4948 
4949   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4950       !AtomTy->isScalarType()) {
4951     // For GNU atomics, require a trivially-copyable type. This is not part of
4952     // the GNU atomics specification, but we enforce it for sanity.
4953     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4954         << Ptr->getType() << Ptr->getSourceRange();
4955     return ExprError();
4956   }
4957 
4958   switch (ValType.getObjCLifetime()) {
4959   case Qualifiers::OCL_None:
4960   case Qualifiers::OCL_ExplicitNone:
4961     // okay
4962     break;
4963 
4964   case Qualifiers::OCL_Weak:
4965   case Qualifiers::OCL_Strong:
4966   case Qualifiers::OCL_Autoreleasing:
4967     // FIXME: Can this happen? By this point, ValType should be known
4968     // to be trivially copyable.
4969     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4970         << ValType << Ptr->getSourceRange();
4971     return ExprError();
4972   }
4973 
4974   // All atomic operations have an overload which takes a pointer to a volatile
4975   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4976   // into the result or the other operands. Similarly atomic_load takes a
4977   // pointer to a const 'A'.
4978   ValType.removeLocalVolatile();
4979   ValType.removeLocalConst();
4980   QualType ResultType = ValType;
4981   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4982       Form == Init)
4983     ResultType = Context.VoidTy;
4984   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4985     ResultType = Context.BoolTy;
4986 
4987   // The type of a parameter passed 'by value'. In the GNU atomics, such
4988   // arguments are actually passed as pointers.
4989   QualType ByValType = ValType; // 'CP'
4990   bool IsPassedByAddress = false;
4991   if (!IsC11 && !IsN) {
4992     ByValType = Ptr->getType();
4993     IsPassedByAddress = true;
4994   }
4995 
4996   SmallVector<Expr *, 5> APIOrderedArgs;
4997   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4998     APIOrderedArgs.push_back(Args[0]);
4999     switch (Form) {
5000     case Init:
5001     case Load:
5002       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5003       break;
5004     case LoadCopy:
5005     case Copy:
5006     case Arithmetic:
5007     case Xchg:
5008       APIOrderedArgs.push_back(Args[2]); // Val1
5009       APIOrderedArgs.push_back(Args[1]); // Order
5010       break;
5011     case GNUXchg:
5012       APIOrderedArgs.push_back(Args[2]); // Val1
5013       APIOrderedArgs.push_back(Args[3]); // Val2
5014       APIOrderedArgs.push_back(Args[1]); // Order
5015       break;
5016     case C11CmpXchg:
5017       APIOrderedArgs.push_back(Args[2]); // Val1
5018       APIOrderedArgs.push_back(Args[4]); // Val2
5019       APIOrderedArgs.push_back(Args[1]); // Order
5020       APIOrderedArgs.push_back(Args[3]); // OrderFail
5021       break;
5022     case GNUCmpXchg:
5023       APIOrderedArgs.push_back(Args[2]); // Val1
5024       APIOrderedArgs.push_back(Args[4]); // Val2
5025       APIOrderedArgs.push_back(Args[5]); // Weak
5026       APIOrderedArgs.push_back(Args[1]); // Order
5027       APIOrderedArgs.push_back(Args[3]); // OrderFail
5028       break;
5029     }
5030   } else
5031     APIOrderedArgs.append(Args.begin(), Args.end());
5032 
5033   // The first argument's non-CV pointer type is used to deduce the type of
5034   // subsequent arguments, except for:
5035   //  - weak flag (always converted to bool)
5036   //  - memory order (always converted to int)
5037   //  - scope  (always converted to int)
5038   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5039     QualType Ty;
5040     if (i < NumVals[Form] + 1) {
5041       switch (i) {
5042       case 0:
5043         // The first argument is always a pointer. It has a fixed type.
5044         // It is always dereferenced, a nullptr is undefined.
5045         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5046         // Nothing else to do: we already know all we want about this pointer.
5047         continue;
5048       case 1:
5049         // The second argument is the non-atomic operand. For arithmetic, this
5050         // is always passed by value, and for a compare_exchange it is always
5051         // passed by address. For the rest, GNU uses by-address and C11 uses
5052         // by-value.
5053         assert(Form != Load);
5054         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5055           Ty = ValType;
5056         else if (Form == Copy || Form == Xchg) {
5057           if (IsPassedByAddress) {
5058             // The value pointer is always dereferenced, a nullptr is undefined.
5059             CheckNonNullArgument(*this, APIOrderedArgs[i],
5060                                  ExprRange.getBegin());
5061           }
5062           Ty = ByValType;
5063         } else if (Form == Arithmetic)
5064           Ty = Context.getPointerDiffType();
5065         else {
5066           Expr *ValArg = APIOrderedArgs[i];
5067           // The value pointer is always dereferenced, a nullptr is undefined.
5068           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5069           LangAS AS = LangAS::Default;
5070           // Keep address space of non-atomic pointer type.
5071           if (const PointerType *PtrTy =
5072                   ValArg->getType()->getAs<PointerType>()) {
5073             AS = PtrTy->getPointeeType().getAddressSpace();
5074           }
5075           Ty = Context.getPointerType(
5076               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5077         }
5078         break;
5079       case 2:
5080         // The third argument to compare_exchange / GNU exchange is the desired
5081         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5082         if (IsPassedByAddress)
5083           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5084         Ty = ByValType;
5085         break;
5086       case 3:
5087         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5088         Ty = Context.BoolTy;
5089         break;
5090       }
5091     } else {
5092       // The order(s) and scope are always converted to int.
5093       Ty = Context.IntTy;
5094     }
5095 
5096     InitializedEntity Entity =
5097         InitializedEntity::InitializeParameter(Context, Ty, false);
5098     ExprResult Arg = APIOrderedArgs[i];
5099     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5100     if (Arg.isInvalid())
5101       return true;
5102     APIOrderedArgs[i] = Arg.get();
5103   }
5104 
5105   // Permute the arguments into a 'consistent' order.
5106   SmallVector<Expr*, 5> SubExprs;
5107   SubExprs.push_back(Ptr);
5108   switch (Form) {
5109   case Init:
5110     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5111     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5112     break;
5113   case Load:
5114     SubExprs.push_back(APIOrderedArgs[1]); // Order
5115     break;
5116   case LoadCopy:
5117   case Copy:
5118   case Arithmetic:
5119   case Xchg:
5120     SubExprs.push_back(APIOrderedArgs[2]); // Order
5121     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5122     break;
5123   case GNUXchg:
5124     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5125     SubExprs.push_back(APIOrderedArgs[3]); // Order
5126     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5127     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5128     break;
5129   case C11CmpXchg:
5130     SubExprs.push_back(APIOrderedArgs[3]); // Order
5131     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5132     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5133     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5134     break;
5135   case GNUCmpXchg:
5136     SubExprs.push_back(APIOrderedArgs[4]); // Order
5137     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5138     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5139     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5140     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5141     break;
5142   }
5143 
5144   if (SubExprs.size() >= 2 && Form != Init) {
5145     if (Optional<llvm::APSInt> Result =
5146             SubExprs[1]->getIntegerConstantExpr(Context))
5147       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5148         Diag(SubExprs[1]->getBeginLoc(),
5149              diag::warn_atomic_op_has_invalid_memory_order)
5150             << SubExprs[1]->getSourceRange();
5151   }
5152 
5153   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5154     auto *Scope = Args[Args.size() - 1];
5155     if (Optional<llvm::APSInt> Result =
5156             Scope->getIntegerConstantExpr(Context)) {
5157       if (!ScopeModel->isValid(Result->getZExtValue()))
5158         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5159             << Scope->getSourceRange();
5160     }
5161     SubExprs.push_back(Scope);
5162   }
5163 
5164   AtomicExpr *AE = new (Context)
5165       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5166 
5167   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5168        Op == AtomicExpr::AO__c11_atomic_store ||
5169        Op == AtomicExpr::AO__opencl_atomic_load ||
5170        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5171       Context.AtomicUsesUnsupportedLibcall(AE))
5172     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5173         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5174              Op == AtomicExpr::AO__opencl_atomic_load)
5175                 ? 0
5176                 : 1);
5177 
5178   if (ValType->isExtIntType()) {
5179     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5180     return ExprError();
5181   }
5182 
5183   return AE;
5184 }
5185 
5186 /// checkBuiltinArgument - Given a call to a builtin function, perform
5187 /// normal type-checking on the given argument, updating the call in
5188 /// place.  This is useful when a builtin function requires custom
5189 /// type-checking for some of its arguments but not necessarily all of
5190 /// them.
5191 ///
5192 /// Returns true on error.
5193 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5194   FunctionDecl *Fn = E->getDirectCallee();
5195   assert(Fn && "builtin call without direct callee!");
5196 
5197   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5198   InitializedEntity Entity =
5199     InitializedEntity::InitializeParameter(S.Context, Param);
5200 
5201   ExprResult Arg = E->getArg(0);
5202   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5203   if (Arg.isInvalid())
5204     return true;
5205 
5206   E->setArg(ArgIndex, Arg.get());
5207   return false;
5208 }
5209 
5210 /// We have a call to a function like __sync_fetch_and_add, which is an
5211 /// overloaded function based on the pointer type of its first argument.
5212 /// The main BuildCallExpr routines have already promoted the types of
5213 /// arguments because all of these calls are prototyped as void(...).
5214 ///
5215 /// This function goes through and does final semantic checking for these
5216 /// builtins, as well as generating any warnings.
5217 ExprResult
5218 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5219   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5220   Expr *Callee = TheCall->getCallee();
5221   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5222   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5223 
5224   // Ensure that we have at least one argument to do type inference from.
5225   if (TheCall->getNumArgs() < 1) {
5226     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5227         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5228     return ExprError();
5229   }
5230 
5231   // Inspect the first argument of the atomic builtin.  This should always be
5232   // a pointer type, whose element is an integral scalar or pointer type.
5233   // Because it is a pointer type, we don't have to worry about any implicit
5234   // casts here.
5235   // FIXME: We don't allow floating point scalars as input.
5236   Expr *FirstArg = TheCall->getArg(0);
5237   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5238   if (FirstArgResult.isInvalid())
5239     return ExprError();
5240   FirstArg = FirstArgResult.get();
5241   TheCall->setArg(0, FirstArg);
5242 
5243   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5244   if (!pointerType) {
5245     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5246         << FirstArg->getType() << FirstArg->getSourceRange();
5247     return ExprError();
5248   }
5249 
5250   QualType ValType = pointerType->getPointeeType();
5251   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5252       !ValType->isBlockPointerType()) {
5253     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5254         << FirstArg->getType() << FirstArg->getSourceRange();
5255     return ExprError();
5256   }
5257 
5258   if (ValType.isConstQualified()) {
5259     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5260         << FirstArg->getType() << FirstArg->getSourceRange();
5261     return ExprError();
5262   }
5263 
5264   switch (ValType.getObjCLifetime()) {
5265   case Qualifiers::OCL_None:
5266   case Qualifiers::OCL_ExplicitNone:
5267     // okay
5268     break;
5269 
5270   case Qualifiers::OCL_Weak:
5271   case Qualifiers::OCL_Strong:
5272   case Qualifiers::OCL_Autoreleasing:
5273     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5274         << ValType << FirstArg->getSourceRange();
5275     return ExprError();
5276   }
5277 
5278   // Strip any qualifiers off ValType.
5279   ValType = ValType.getUnqualifiedType();
5280 
5281   // The majority of builtins return a value, but a few have special return
5282   // types, so allow them to override appropriately below.
5283   QualType ResultType = ValType;
5284 
5285   // We need to figure out which concrete builtin this maps onto.  For example,
5286   // __sync_fetch_and_add with a 2 byte object turns into
5287   // __sync_fetch_and_add_2.
5288 #define BUILTIN_ROW(x) \
5289   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5290     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5291 
5292   static const unsigned BuiltinIndices[][5] = {
5293     BUILTIN_ROW(__sync_fetch_and_add),
5294     BUILTIN_ROW(__sync_fetch_and_sub),
5295     BUILTIN_ROW(__sync_fetch_and_or),
5296     BUILTIN_ROW(__sync_fetch_and_and),
5297     BUILTIN_ROW(__sync_fetch_and_xor),
5298     BUILTIN_ROW(__sync_fetch_and_nand),
5299 
5300     BUILTIN_ROW(__sync_add_and_fetch),
5301     BUILTIN_ROW(__sync_sub_and_fetch),
5302     BUILTIN_ROW(__sync_and_and_fetch),
5303     BUILTIN_ROW(__sync_or_and_fetch),
5304     BUILTIN_ROW(__sync_xor_and_fetch),
5305     BUILTIN_ROW(__sync_nand_and_fetch),
5306 
5307     BUILTIN_ROW(__sync_val_compare_and_swap),
5308     BUILTIN_ROW(__sync_bool_compare_and_swap),
5309     BUILTIN_ROW(__sync_lock_test_and_set),
5310     BUILTIN_ROW(__sync_lock_release),
5311     BUILTIN_ROW(__sync_swap)
5312   };
5313 #undef BUILTIN_ROW
5314 
5315   // Determine the index of the size.
5316   unsigned SizeIndex;
5317   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5318   case 1: SizeIndex = 0; break;
5319   case 2: SizeIndex = 1; break;
5320   case 4: SizeIndex = 2; break;
5321   case 8: SizeIndex = 3; break;
5322   case 16: SizeIndex = 4; break;
5323   default:
5324     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5325         << FirstArg->getType() << FirstArg->getSourceRange();
5326     return ExprError();
5327   }
5328 
5329   // Each of these builtins has one pointer argument, followed by some number of
5330   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5331   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5332   // as the number of fixed args.
5333   unsigned BuiltinID = FDecl->getBuiltinID();
5334   unsigned BuiltinIndex, NumFixed = 1;
5335   bool WarnAboutSemanticsChange = false;
5336   switch (BuiltinID) {
5337   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5338   case Builtin::BI__sync_fetch_and_add:
5339   case Builtin::BI__sync_fetch_and_add_1:
5340   case Builtin::BI__sync_fetch_and_add_2:
5341   case Builtin::BI__sync_fetch_and_add_4:
5342   case Builtin::BI__sync_fetch_and_add_8:
5343   case Builtin::BI__sync_fetch_and_add_16:
5344     BuiltinIndex = 0;
5345     break;
5346 
5347   case Builtin::BI__sync_fetch_and_sub:
5348   case Builtin::BI__sync_fetch_and_sub_1:
5349   case Builtin::BI__sync_fetch_and_sub_2:
5350   case Builtin::BI__sync_fetch_and_sub_4:
5351   case Builtin::BI__sync_fetch_and_sub_8:
5352   case Builtin::BI__sync_fetch_and_sub_16:
5353     BuiltinIndex = 1;
5354     break;
5355 
5356   case Builtin::BI__sync_fetch_and_or:
5357   case Builtin::BI__sync_fetch_and_or_1:
5358   case Builtin::BI__sync_fetch_and_or_2:
5359   case Builtin::BI__sync_fetch_and_or_4:
5360   case Builtin::BI__sync_fetch_and_or_8:
5361   case Builtin::BI__sync_fetch_and_or_16:
5362     BuiltinIndex = 2;
5363     break;
5364 
5365   case Builtin::BI__sync_fetch_and_and:
5366   case Builtin::BI__sync_fetch_and_and_1:
5367   case Builtin::BI__sync_fetch_and_and_2:
5368   case Builtin::BI__sync_fetch_and_and_4:
5369   case Builtin::BI__sync_fetch_and_and_8:
5370   case Builtin::BI__sync_fetch_and_and_16:
5371     BuiltinIndex = 3;
5372     break;
5373 
5374   case Builtin::BI__sync_fetch_and_xor:
5375   case Builtin::BI__sync_fetch_and_xor_1:
5376   case Builtin::BI__sync_fetch_and_xor_2:
5377   case Builtin::BI__sync_fetch_and_xor_4:
5378   case Builtin::BI__sync_fetch_and_xor_8:
5379   case Builtin::BI__sync_fetch_and_xor_16:
5380     BuiltinIndex = 4;
5381     break;
5382 
5383   case Builtin::BI__sync_fetch_and_nand:
5384   case Builtin::BI__sync_fetch_and_nand_1:
5385   case Builtin::BI__sync_fetch_and_nand_2:
5386   case Builtin::BI__sync_fetch_and_nand_4:
5387   case Builtin::BI__sync_fetch_and_nand_8:
5388   case Builtin::BI__sync_fetch_and_nand_16:
5389     BuiltinIndex = 5;
5390     WarnAboutSemanticsChange = true;
5391     break;
5392 
5393   case Builtin::BI__sync_add_and_fetch:
5394   case Builtin::BI__sync_add_and_fetch_1:
5395   case Builtin::BI__sync_add_and_fetch_2:
5396   case Builtin::BI__sync_add_and_fetch_4:
5397   case Builtin::BI__sync_add_and_fetch_8:
5398   case Builtin::BI__sync_add_and_fetch_16:
5399     BuiltinIndex = 6;
5400     break;
5401 
5402   case Builtin::BI__sync_sub_and_fetch:
5403   case Builtin::BI__sync_sub_and_fetch_1:
5404   case Builtin::BI__sync_sub_and_fetch_2:
5405   case Builtin::BI__sync_sub_and_fetch_4:
5406   case Builtin::BI__sync_sub_and_fetch_8:
5407   case Builtin::BI__sync_sub_and_fetch_16:
5408     BuiltinIndex = 7;
5409     break;
5410 
5411   case Builtin::BI__sync_and_and_fetch:
5412   case Builtin::BI__sync_and_and_fetch_1:
5413   case Builtin::BI__sync_and_and_fetch_2:
5414   case Builtin::BI__sync_and_and_fetch_4:
5415   case Builtin::BI__sync_and_and_fetch_8:
5416   case Builtin::BI__sync_and_and_fetch_16:
5417     BuiltinIndex = 8;
5418     break;
5419 
5420   case Builtin::BI__sync_or_and_fetch:
5421   case Builtin::BI__sync_or_and_fetch_1:
5422   case Builtin::BI__sync_or_and_fetch_2:
5423   case Builtin::BI__sync_or_and_fetch_4:
5424   case Builtin::BI__sync_or_and_fetch_8:
5425   case Builtin::BI__sync_or_and_fetch_16:
5426     BuiltinIndex = 9;
5427     break;
5428 
5429   case Builtin::BI__sync_xor_and_fetch:
5430   case Builtin::BI__sync_xor_and_fetch_1:
5431   case Builtin::BI__sync_xor_and_fetch_2:
5432   case Builtin::BI__sync_xor_and_fetch_4:
5433   case Builtin::BI__sync_xor_and_fetch_8:
5434   case Builtin::BI__sync_xor_and_fetch_16:
5435     BuiltinIndex = 10;
5436     break;
5437 
5438   case Builtin::BI__sync_nand_and_fetch:
5439   case Builtin::BI__sync_nand_and_fetch_1:
5440   case Builtin::BI__sync_nand_and_fetch_2:
5441   case Builtin::BI__sync_nand_and_fetch_4:
5442   case Builtin::BI__sync_nand_and_fetch_8:
5443   case Builtin::BI__sync_nand_and_fetch_16:
5444     BuiltinIndex = 11;
5445     WarnAboutSemanticsChange = true;
5446     break;
5447 
5448   case Builtin::BI__sync_val_compare_and_swap:
5449   case Builtin::BI__sync_val_compare_and_swap_1:
5450   case Builtin::BI__sync_val_compare_and_swap_2:
5451   case Builtin::BI__sync_val_compare_and_swap_4:
5452   case Builtin::BI__sync_val_compare_and_swap_8:
5453   case Builtin::BI__sync_val_compare_and_swap_16:
5454     BuiltinIndex = 12;
5455     NumFixed = 2;
5456     break;
5457 
5458   case Builtin::BI__sync_bool_compare_and_swap:
5459   case Builtin::BI__sync_bool_compare_and_swap_1:
5460   case Builtin::BI__sync_bool_compare_and_swap_2:
5461   case Builtin::BI__sync_bool_compare_and_swap_4:
5462   case Builtin::BI__sync_bool_compare_and_swap_8:
5463   case Builtin::BI__sync_bool_compare_and_swap_16:
5464     BuiltinIndex = 13;
5465     NumFixed = 2;
5466     ResultType = Context.BoolTy;
5467     break;
5468 
5469   case Builtin::BI__sync_lock_test_and_set:
5470   case Builtin::BI__sync_lock_test_and_set_1:
5471   case Builtin::BI__sync_lock_test_and_set_2:
5472   case Builtin::BI__sync_lock_test_and_set_4:
5473   case Builtin::BI__sync_lock_test_and_set_8:
5474   case Builtin::BI__sync_lock_test_and_set_16:
5475     BuiltinIndex = 14;
5476     break;
5477 
5478   case Builtin::BI__sync_lock_release:
5479   case Builtin::BI__sync_lock_release_1:
5480   case Builtin::BI__sync_lock_release_2:
5481   case Builtin::BI__sync_lock_release_4:
5482   case Builtin::BI__sync_lock_release_8:
5483   case Builtin::BI__sync_lock_release_16:
5484     BuiltinIndex = 15;
5485     NumFixed = 0;
5486     ResultType = Context.VoidTy;
5487     break;
5488 
5489   case Builtin::BI__sync_swap:
5490   case Builtin::BI__sync_swap_1:
5491   case Builtin::BI__sync_swap_2:
5492   case Builtin::BI__sync_swap_4:
5493   case Builtin::BI__sync_swap_8:
5494   case Builtin::BI__sync_swap_16:
5495     BuiltinIndex = 16;
5496     break;
5497   }
5498 
5499   // Now that we know how many fixed arguments we expect, first check that we
5500   // have at least that many.
5501   if (TheCall->getNumArgs() < 1+NumFixed) {
5502     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5503         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5504         << Callee->getSourceRange();
5505     return ExprError();
5506   }
5507 
5508   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5509       << Callee->getSourceRange();
5510 
5511   if (WarnAboutSemanticsChange) {
5512     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5513         << Callee->getSourceRange();
5514   }
5515 
5516   // Get the decl for the concrete builtin from this, we can tell what the
5517   // concrete integer type we should convert to is.
5518   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5519   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5520   FunctionDecl *NewBuiltinDecl;
5521   if (NewBuiltinID == BuiltinID)
5522     NewBuiltinDecl = FDecl;
5523   else {
5524     // Perform builtin lookup to avoid redeclaring it.
5525     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5526     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5527     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5528     assert(Res.getFoundDecl());
5529     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5530     if (!NewBuiltinDecl)
5531       return ExprError();
5532   }
5533 
5534   // The first argument --- the pointer --- has a fixed type; we
5535   // deduce the types of the rest of the arguments accordingly.  Walk
5536   // the remaining arguments, converting them to the deduced value type.
5537   for (unsigned i = 0; i != NumFixed; ++i) {
5538     ExprResult Arg = TheCall->getArg(i+1);
5539 
5540     // GCC does an implicit conversion to the pointer or integer ValType.  This
5541     // can fail in some cases (1i -> int**), check for this error case now.
5542     // Initialize the argument.
5543     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5544                                                    ValType, /*consume*/ false);
5545     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5546     if (Arg.isInvalid())
5547       return ExprError();
5548 
5549     // Okay, we have something that *can* be converted to the right type.  Check
5550     // to see if there is a potentially weird extension going on here.  This can
5551     // happen when you do an atomic operation on something like an char* and
5552     // pass in 42.  The 42 gets converted to char.  This is even more strange
5553     // for things like 45.123 -> char, etc.
5554     // FIXME: Do this check.
5555     TheCall->setArg(i+1, Arg.get());
5556   }
5557 
5558   // Create a new DeclRefExpr to refer to the new decl.
5559   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5560       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5561       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5562       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5563 
5564   // Set the callee in the CallExpr.
5565   // FIXME: This loses syntactic information.
5566   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5567   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5568                                               CK_BuiltinFnToFnPtr);
5569   TheCall->setCallee(PromotedCall.get());
5570 
5571   // Change the result type of the call to match the original value type. This
5572   // is arbitrary, but the codegen for these builtins ins design to handle it
5573   // gracefully.
5574   TheCall->setType(ResultType);
5575 
5576   // Prohibit use of _ExtInt with atomic builtins.
5577   // The arguments would have already been converted to the first argument's
5578   // type, so only need to check the first argument.
5579   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5580   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5581     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5582     return ExprError();
5583   }
5584 
5585   return TheCallResult;
5586 }
5587 
5588 /// SemaBuiltinNontemporalOverloaded - We have a call to
5589 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5590 /// overloaded function based on the pointer type of its last argument.
5591 ///
5592 /// This function goes through and does final semantic checking for these
5593 /// builtins.
5594 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5595   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5596   DeclRefExpr *DRE =
5597       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5598   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5599   unsigned BuiltinID = FDecl->getBuiltinID();
5600   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5601           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5602          "Unexpected nontemporal load/store builtin!");
5603   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5604   unsigned numArgs = isStore ? 2 : 1;
5605 
5606   // Ensure that we have the proper number of arguments.
5607   if (checkArgCount(*this, TheCall, numArgs))
5608     return ExprError();
5609 
5610   // Inspect the last argument of the nontemporal builtin.  This should always
5611   // be a pointer type, from which we imply the type of the memory access.
5612   // Because it is a pointer type, we don't have to worry about any implicit
5613   // casts here.
5614   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5615   ExprResult PointerArgResult =
5616       DefaultFunctionArrayLvalueConversion(PointerArg);
5617 
5618   if (PointerArgResult.isInvalid())
5619     return ExprError();
5620   PointerArg = PointerArgResult.get();
5621   TheCall->setArg(numArgs - 1, PointerArg);
5622 
5623   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5624   if (!pointerType) {
5625     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5626         << PointerArg->getType() << PointerArg->getSourceRange();
5627     return ExprError();
5628   }
5629 
5630   QualType ValType = pointerType->getPointeeType();
5631 
5632   // Strip any qualifiers off ValType.
5633   ValType = ValType.getUnqualifiedType();
5634   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5635       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5636       !ValType->isVectorType()) {
5637     Diag(DRE->getBeginLoc(),
5638          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5639         << PointerArg->getType() << PointerArg->getSourceRange();
5640     return ExprError();
5641   }
5642 
5643   if (!isStore) {
5644     TheCall->setType(ValType);
5645     return TheCallResult;
5646   }
5647 
5648   ExprResult ValArg = TheCall->getArg(0);
5649   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5650       Context, ValType, /*consume*/ false);
5651   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5652   if (ValArg.isInvalid())
5653     return ExprError();
5654 
5655   TheCall->setArg(0, ValArg.get());
5656   TheCall->setType(Context.VoidTy);
5657   return TheCallResult;
5658 }
5659 
5660 /// CheckObjCString - Checks that the argument to the builtin
5661 /// CFString constructor is correct
5662 /// Note: It might also make sense to do the UTF-16 conversion here (would
5663 /// simplify the backend).
5664 bool Sema::CheckObjCString(Expr *Arg) {
5665   Arg = Arg->IgnoreParenCasts();
5666   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5667 
5668   if (!Literal || !Literal->isAscii()) {
5669     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5670         << Arg->getSourceRange();
5671     return true;
5672   }
5673 
5674   if (Literal->containsNonAsciiOrNull()) {
5675     StringRef String = Literal->getString();
5676     unsigned NumBytes = String.size();
5677     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5678     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5679     llvm::UTF16 *ToPtr = &ToBuf[0];
5680 
5681     llvm::ConversionResult Result =
5682         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5683                                  ToPtr + NumBytes, llvm::strictConversion);
5684     // Check for conversion failure.
5685     if (Result != llvm::conversionOK)
5686       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5687           << Arg->getSourceRange();
5688   }
5689   return false;
5690 }
5691 
5692 /// CheckObjCString - Checks that the format string argument to the os_log()
5693 /// and os_trace() functions is correct, and converts it to const char *.
5694 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5695   Arg = Arg->IgnoreParenCasts();
5696   auto *Literal = dyn_cast<StringLiteral>(Arg);
5697   if (!Literal) {
5698     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5699       Literal = ObjcLiteral->getString();
5700     }
5701   }
5702 
5703   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5704     return ExprError(
5705         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5706         << Arg->getSourceRange());
5707   }
5708 
5709   ExprResult Result(Literal);
5710   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5711   InitializedEntity Entity =
5712       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5713   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5714   return Result;
5715 }
5716 
5717 /// Check that the user is calling the appropriate va_start builtin for the
5718 /// target and calling convention.
5719 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5720   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5721   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5722   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5723                     TT.getArch() == llvm::Triple::aarch64_32);
5724   bool IsWindows = TT.isOSWindows();
5725   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5726   if (IsX64 || IsAArch64) {
5727     CallingConv CC = CC_C;
5728     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5729       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5730     if (IsMSVAStart) {
5731       // Don't allow this in System V ABI functions.
5732       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5733         return S.Diag(Fn->getBeginLoc(),
5734                       diag::err_ms_va_start_used_in_sysv_function);
5735     } else {
5736       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5737       // On x64 Windows, don't allow this in System V ABI functions.
5738       // (Yes, that means there's no corresponding way to support variadic
5739       // System V ABI functions on Windows.)
5740       if ((IsWindows && CC == CC_X86_64SysV) ||
5741           (!IsWindows && CC == CC_Win64))
5742         return S.Diag(Fn->getBeginLoc(),
5743                       diag::err_va_start_used_in_wrong_abi_function)
5744                << !IsWindows;
5745     }
5746     return false;
5747   }
5748 
5749   if (IsMSVAStart)
5750     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5751   return false;
5752 }
5753 
5754 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5755                                              ParmVarDecl **LastParam = nullptr) {
5756   // Determine whether the current function, block, or obj-c method is variadic
5757   // and get its parameter list.
5758   bool IsVariadic = false;
5759   ArrayRef<ParmVarDecl *> Params;
5760   DeclContext *Caller = S.CurContext;
5761   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5762     IsVariadic = Block->isVariadic();
5763     Params = Block->parameters();
5764   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5765     IsVariadic = FD->isVariadic();
5766     Params = FD->parameters();
5767   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5768     IsVariadic = MD->isVariadic();
5769     // FIXME: This isn't correct for methods (results in bogus warning).
5770     Params = MD->parameters();
5771   } else if (isa<CapturedDecl>(Caller)) {
5772     // We don't support va_start in a CapturedDecl.
5773     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5774     return true;
5775   } else {
5776     // This must be some other declcontext that parses exprs.
5777     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5778     return true;
5779   }
5780 
5781   if (!IsVariadic) {
5782     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5783     return true;
5784   }
5785 
5786   if (LastParam)
5787     *LastParam = Params.empty() ? nullptr : Params.back();
5788 
5789   return false;
5790 }
5791 
5792 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5793 /// for validity.  Emit an error and return true on failure; return false
5794 /// on success.
5795 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5796   Expr *Fn = TheCall->getCallee();
5797 
5798   if (checkVAStartABI(*this, BuiltinID, Fn))
5799     return true;
5800 
5801   if (checkArgCount(*this, TheCall, 2))
5802     return true;
5803 
5804   // Type-check the first argument normally.
5805   if (checkBuiltinArgument(*this, TheCall, 0))
5806     return true;
5807 
5808   // Check that the current function is variadic, and get its last parameter.
5809   ParmVarDecl *LastParam;
5810   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5811     return true;
5812 
5813   // Verify that the second argument to the builtin is the last argument of the
5814   // current function or method.
5815   bool SecondArgIsLastNamedArgument = false;
5816   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5817 
5818   // These are valid if SecondArgIsLastNamedArgument is false after the next
5819   // block.
5820   QualType Type;
5821   SourceLocation ParamLoc;
5822   bool IsCRegister = false;
5823 
5824   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5825     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5826       SecondArgIsLastNamedArgument = PV == LastParam;
5827 
5828       Type = PV->getType();
5829       ParamLoc = PV->getLocation();
5830       IsCRegister =
5831           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5832     }
5833   }
5834 
5835   if (!SecondArgIsLastNamedArgument)
5836     Diag(TheCall->getArg(1)->getBeginLoc(),
5837          diag::warn_second_arg_of_va_start_not_last_named_param);
5838   else if (IsCRegister || Type->isReferenceType() ||
5839            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5840              // Promotable integers are UB, but enumerations need a bit of
5841              // extra checking to see what their promotable type actually is.
5842              if (!Type->isPromotableIntegerType())
5843                return false;
5844              if (!Type->isEnumeralType())
5845                return true;
5846              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5847              return !(ED &&
5848                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5849            }()) {
5850     unsigned Reason = 0;
5851     if (Type->isReferenceType())  Reason = 1;
5852     else if (IsCRegister)         Reason = 2;
5853     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5854     Diag(ParamLoc, diag::note_parameter_type) << Type;
5855   }
5856 
5857   TheCall->setType(Context.VoidTy);
5858   return false;
5859 }
5860 
5861 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5862   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5863   //                 const char *named_addr);
5864 
5865   Expr *Func = Call->getCallee();
5866 
5867   if (Call->getNumArgs() < 3)
5868     return Diag(Call->getEndLoc(),
5869                 diag::err_typecheck_call_too_few_args_at_least)
5870            << 0 /*function call*/ << 3 << Call->getNumArgs();
5871 
5872   // Type-check the first argument normally.
5873   if (checkBuiltinArgument(*this, Call, 0))
5874     return true;
5875 
5876   // Check that the current function is variadic.
5877   if (checkVAStartIsInVariadicFunction(*this, Func))
5878     return true;
5879 
5880   // __va_start on Windows does not validate the parameter qualifiers
5881 
5882   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5883   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5884 
5885   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5886   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5887 
5888   const QualType &ConstCharPtrTy =
5889       Context.getPointerType(Context.CharTy.withConst());
5890   if (!Arg1Ty->isPointerType() ||
5891       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5892     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5893         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5894         << 0                                      /* qualifier difference */
5895         << 3                                      /* parameter mismatch */
5896         << 2 << Arg1->getType() << ConstCharPtrTy;
5897 
5898   const QualType SizeTy = Context.getSizeType();
5899   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5900     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5901         << Arg2->getType() << SizeTy << 1 /* different class */
5902         << 0                              /* qualifier difference */
5903         << 3                              /* parameter mismatch */
5904         << 3 << Arg2->getType() << SizeTy;
5905 
5906   return false;
5907 }
5908 
5909 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5910 /// friends.  This is declared to take (...), so we have to check everything.
5911 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5912   if (checkArgCount(*this, TheCall, 2))
5913     return true;
5914 
5915   ExprResult OrigArg0 = TheCall->getArg(0);
5916   ExprResult OrigArg1 = TheCall->getArg(1);
5917 
5918   // Do standard promotions between the two arguments, returning their common
5919   // type.
5920   QualType Res = UsualArithmeticConversions(
5921       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5922   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5923     return true;
5924 
5925   // Make sure any conversions are pushed back into the call; this is
5926   // type safe since unordered compare builtins are declared as "_Bool
5927   // foo(...)".
5928   TheCall->setArg(0, OrigArg0.get());
5929   TheCall->setArg(1, OrigArg1.get());
5930 
5931   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5932     return false;
5933 
5934   // If the common type isn't a real floating type, then the arguments were
5935   // invalid for this operation.
5936   if (Res.isNull() || !Res->isRealFloatingType())
5937     return Diag(OrigArg0.get()->getBeginLoc(),
5938                 diag::err_typecheck_call_invalid_ordered_compare)
5939            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5940            << SourceRange(OrigArg0.get()->getBeginLoc(),
5941                           OrigArg1.get()->getEndLoc());
5942 
5943   return false;
5944 }
5945 
5946 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5947 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5948 /// to check everything. We expect the last argument to be a floating point
5949 /// value.
5950 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5951   if (checkArgCount(*this, TheCall, NumArgs))
5952     return true;
5953 
5954   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5955   // on all preceding parameters just being int.  Try all of those.
5956   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5957     Expr *Arg = TheCall->getArg(i);
5958 
5959     if (Arg->isTypeDependent())
5960       return false;
5961 
5962     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5963 
5964     if (Res.isInvalid())
5965       return true;
5966     TheCall->setArg(i, Res.get());
5967   }
5968 
5969   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5970 
5971   if (OrigArg->isTypeDependent())
5972     return false;
5973 
5974   // Usual Unary Conversions will convert half to float, which we want for
5975   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5976   // type how it is, but do normal L->Rvalue conversions.
5977   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5978     OrigArg = UsualUnaryConversions(OrigArg).get();
5979   else
5980     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5981   TheCall->setArg(NumArgs - 1, OrigArg);
5982 
5983   // This operation requires a non-_Complex floating-point number.
5984   if (!OrigArg->getType()->isRealFloatingType())
5985     return Diag(OrigArg->getBeginLoc(),
5986                 diag::err_typecheck_call_invalid_unary_fp)
5987            << OrigArg->getType() << OrigArg->getSourceRange();
5988 
5989   return false;
5990 }
5991 
5992 /// Perform semantic analysis for a call to __builtin_complex.
5993 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5994   if (checkArgCount(*this, TheCall, 2))
5995     return true;
5996 
5997   bool Dependent = false;
5998   for (unsigned I = 0; I != 2; ++I) {
5999     Expr *Arg = TheCall->getArg(I);
6000     QualType T = Arg->getType();
6001     if (T->isDependentType()) {
6002       Dependent = true;
6003       continue;
6004     }
6005 
6006     // Despite supporting _Complex int, GCC requires a real floating point type
6007     // for the operands of __builtin_complex.
6008     if (!T->isRealFloatingType()) {
6009       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6010              << Arg->getType() << Arg->getSourceRange();
6011     }
6012 
6013     ExprResult Converted = DefaultLvalueConversion(Arg);
6014     if (Converted.isInvalid())
6015       return true;
6016     TheCall->setArg(I, Converted.get());
6017   }
6018 
6019   if (Dependent) {
6020     TheCall->setType(Context.DependentTy);
6021     return false;
6022   }
6023 
6024   Expr *Real = TheCall->getArg(0);
6025   Expr *Imag = TheCall->getArg(1);
6026   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6027     return Diag(Real->getBeginLoc(),
6028                 diag::err_typecheck_call_different_arg_types)
6029            << Real->getType() << Imag->getType()
6030            << Real->getSourceRange() << Imag->getSourceRange();
6031   }
6032 
6033   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6034   // don't allow this builtin to form those types either.
6035   // FIXME: Should we allow these types?
6036   if (Real->getType()->isFloat16Type())
6037     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6038            << "_Float16";
6039   if (Real->getType()->isHalfType())
6040     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6041            << "half";
6042 
6043   TheCall->setType(Context.getComplexType(Real->getType()));
6044   return false;
6045 }
6046 
6047 // Customized Sema Checking for VSX builtins that have the following signature:
6048 // vector [...] builtinName(vector [...], vector [...], const int);
6049 // Which takes the same type of vectors (any legal vector type) for the first
6050 // two arguments and takes compile time constant for the third argument.
6051 // Example builtins are :
6052 // vector double vec_xxpermdi(vector double, vector double, int);
6053 // vector short vec_xxsldwi(vector short, vector short, int);
6054 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6055   unsigned ExpectedNumArgs = 3;
6056   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6057     return true;
6058 
6059   // Check the third argument is a compile time constant
6060   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6061     return Diag(TheCall->getBeginLoc(),
6062                 diag::err_vsx_builtin_nonconstant_argument)
6063            << 3 /* argument index */ << TheCall->getDirectCallee()
6064            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6065                           TheCall->getArg(2)->getEndLoc());
6066 
6067   QualType Arg1Ty = TheCall->getArg(0)->getType();
6068   QualType Arg2Ty = TheCall->getArg(1)->getType();
6069 
6070   // Check the type of argument 1 and argument 2 are vectors.
6071   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6072   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6073       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6074     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6075            << TheCall->getDirectCallee()
6076            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6077                           TheCall->getArg(1)->getEndLoc());
6078   }
6079 
6080   // Check the first two arguments are the same type.
6081   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6082     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6083            << TheCall->getDirectCallee()
6084            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6085                           TheCall->getArg(1)->getEndLoc());
6086   }
6087 
6088   // When default clang type checking is turned off and the customized type
6089   // checking is used, the returning type of the function must be explicitly
6090   // set. Otherwise it is _Bool by default.
6091   TheCall->setType(Arg1Ty);
6092 
6093   return false;
6094 }
6095 
6096 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6097 // This is declared to take (...), so we have to check everything.
6098 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6099   if (TheCall->getNumArgs() < 2)
6100     return ExprError(Diag(TheCall->getEndLoc(),
6101                           diag::err_typecheck_call_too_few_args_at_least)
6102                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6103                      << TheCall->getSourceRange());
6104 
6105   // Determine which of the following types of shufflevector we're checking:
6106   // 1) unary, vector mask: (lhs, mask)
6107   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6108   QualType resType = TheCall->getArg(0)->getType();
6109   unsigned numElements = 0;
6110 
6111   if (!TheCall->getArg(0)->isTypeDependent() &&
6112       !TheCall->getArg(1)->isTypeDependent()) {
6113     QualType LHSType = TheCall->getArg(0)->getType();
6114     QualType RHSType = TheCall->getArg(1)->getType();
6115 
6116     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6117       return ExprError(
6118           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6119           << TheCall->getDirectCallee()
6120           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6121                          TheCall->getArg(1)->getEndLoc()));
6122 
6123     numElements = LHSType->castAs<VectorType>()->getNumElements();
6124     unsigned numResElements = TheCall->getNumArgs() - 2;
6125 
6126     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6127     // with mask.  If so, verify that RHS is an integer vector type with the
6128     // same number of elts as lhs.
6129     if (TheCall->getNumArgs() == 2) {
6130       if (!RHSType->hasIntegerRepresentation() ||
6131           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6132         return ExprError(Diag(TheCall->getBeginLoc(),
6133                               diag::err_vec_builtin_incompatible_vector)
6134                          << TheCall->getDirectCallee()
6135                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6136                                         TheCall->getArg(1)->getEndLoc()));
6137     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6138       return ExprError(Diag(TheCall->getBeginLoc(),
6139                             diag::err_vec_builtin_incompatible_vector)
6140                        << TheCall->getDirectCallee()
6141                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6142                                       TheCall->getArg(1)->getEndLoc()));
6143     } else if (numElements != numResElements) {
6144       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6145       resType = Context.getVectorType(eltType, numResElements,
6146                                       VectorType::GenericVector);
6147     }
6148   }
6149 
6150   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6151     if (TheCall->getArg(i)->isTypeDependent() ||
6152         TheCall->getArg(i)->isValueDependent())
6153       continue;
6154 
6155     Optional<llvm::APSInt> Result;
6156     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6157       return ExprError(Diag(TheCall->getBeginLoc(),
6158                             diag::err_shufflevector_nonconstant_argument)
6159                        << TheCall->getArg(i)->getSourceRange());
6160 
6161     // Allow -1 which will be translated to undef in the IR.
6162     if (Result->isSigned() && Result->isAllOnesValue())
6163       continue;
6164 
6165     if (Result->getActiveBits() > 64 ||
6166         Result->getZExtValue() >= numElements * 2)
6167       return ExprError(Diag(TheCall->getBeginLoc(),
6168                             diag::err_shufflevector_argument_too_large)
6169                        << TheCall->getArg(i)->getSourceRange());
6170   }
6171 
6172   SmallVector<Expr*, 32> exprs;
6173 
6174   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6175     exprs.push_back(TheCall->getArg(i));
6176     TheCall->setArg(i, nullptr);
6177   }
6178 
6179   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6180                                          TheCall->getCallee()->getBeginLoc(),
6181                                          TheCall->getRParenLoc());
6182 }
6183 
6184 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6185 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6186                                        SourceLocation BuiltinLoc,
6187                                        SourceLocation RParenLoc) {
6188   ExprValueKind VK = VK_RValue;
6189   ExprObjectKind OK = OK_Ordinary;
6190   QualType DstTy = TInfo->getType();
6191   QualType SrcTy = E->getType();
6192 
6193   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6194     return ExprError(Diag(BuiltinLoc,
6195                           diag::err_convertvector_non_vector)
6196                      << E->getSourceRange());
6197   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6198     return ExprError(Diag(BuiltinLoc,
6199                           diag::err_convertvector_non_vector_type));
6200 
6201   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6202     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6203     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6204     if (SrcElts != DstElts)
6205       return ExprError(Diag(BuiltinLoc,
6206                             diag::err_convertvector_incompatible_vector)
6207                        << E->getSourceRange());
6208   }
6209 
6210   return new (Context)
6211       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6212 }
6213 
6214 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6215 // This is declared to take (const void*, ...) and can take two
6216 // optional constant int args.
6217 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6218   unsigned NumArgs = TheCall->getNumArgs();
6219 
6220   if (NumArgs > 3)
6221     return Diag(TheCall->getEndLoc(),
6222                 diag::err_typecheck_call_too_many_args_at_most)
6223            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6224 
6225   // Argument 0 is checked for us and the remaining arguments must be
6226   // constant integers.
6227   for (unsigned i = 1; i != NumArgs; ++i)
6228     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6229       return true;
6230 
6231   return false;
6232 }
6233 
6234 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6235 // __assume does not evaluate its arguments, and should warn if its argument
6236 // has side effects.
6237 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6238   Expr *Arg = TheCall->getArg(0);
6239   if (Arg->isInstantiationDependent()) return false;
6240 
6241   if (Arg->HasSideEffects(Context))
6242     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6243         << Arg->getSourceRange()
6244         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6245 
6246   return false;
6247 }
6248 
6249 /// Handle __builtin_alloca_with_align. This is declared
6250 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6251 /// than 8.
6252 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6253   // The alignment must be a constant integer.
6254   Expr *Arg = TheCall->getArg(1);
6255 
6256   // We can't check the value of a dependent argument.
6257   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6258     if (const auto *UE =
6259             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6260       if (UE->getKind() == UETT_AlignOf ||
6261           UE->getKind() == UETT_PreferredAlignOf)
6262         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6263             << Arg->getSourceRange();
6264 
6265     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6266 
6267     if (!Result.isPowerOf2())
6268       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6269              << Arg->getSourceRange();
6270 
6271     if (Result < Context.getCharWidth())
6272       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6273              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6274 
6275     if (Result > std::numeric_limits<int32_t>::max())
6276       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6277              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6278   }
6279 
6280   return false;
6281 }
6282 
6283 /// Handle __builtin_assume_aligned. This is declared
6284 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6285 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6286   unsigned NumArgs = TheCall->getNumArgs();
6287 
6288   if (NumArgs > 3)
6289     return Diag(TheCall->getEndLoc(),
6290                 diag::err_typecheck_call_too_many_args_at_most)
6291            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6292 
6293   // The alignment must be a constant integer.
6294   Expr *Arg = TheCall->getArg(1);
6295 
6296   // We can't check the value of a dependent argument.
6297   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6298     llvm::APSInt Result;
6299     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6300       return true;
6301 
6302     if (!Result.isPowerOf2())
6303       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6304              << Arg->getSourceRange();
6305 
6306     if (Result > Sema::MaximumAlignment)
6307       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6308           << Arg->getSourceRange() << Sema::MaximumAlignment;
6309   }
6310 
6311   if (NumArgs > 2) {
6312     ExprResult Arg(TheCall->getArg(2));
6313     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6314       Context.getSizeType(), false);
6315     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6316     if (Arg.isInvalid()) return true;
6317     TheCall->setArg(2, Arg.get());
6318   }
6319 
6320   return false;
6321 }
6322 
6323 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6324   unsigned BuiltinID =
6325       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6326   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6327 
6328   unsigned NumArgs = TheCall->getNumArgs();
6329   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6330   if (NumArgs < NumRequiredArgs) {
6331     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6332            << 0 /* function call */ << NumRequiredArgs << NumArgs
6333            << TheCall->getSourceRange();
6334   }
6335   if (NumArgs >= NumRequiredArgs + 0x100) {
6336     return Diag(TheCall->getEndLoc(),
6337                 diag::err_typecheck_call_too_many_args_at_most)
6338            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6339            << TheCall->getSourceRange();
6340   }
6341   unsigned i = 0;
6342 
6343   // For formatting call, check buffer arg.
6344   if (!IsSizeCall) {
6345     ExprResult Arg(TheCall->getArg(i));
6346     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6347         Context, Context.VoidPtrTy, false);
6348     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6349     if (Arg.isInvalid())
6350       return true;
6351     TheCall->setArg(i, Arg.get());
6352     i++;
6353   }
6354 
6355   // Check string literal arg.
6356   unsigned FormatIdx = i;
6357   {
6358     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6359     if (Arg.isInvalid())
6360       return true;
6361     TheCall->setArg(i, Arg.get());
6362     i++;
6363   }
6364 
6365   // Make sure variadic args are scalar.
6366   unsigned FirstDataArg = i;
6367   while (i < NumArgs) {
6368     ExprResult Arg = DefaultVariadicArgumentPromotion(
6369         TheCall->getArg(i), VariadicFunction, nullptr);
6370     if (Arg.isInvalid())
6371       return true;
6372     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6373     if (ArgSize.getQuantity() >= 0x100) {
6374       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6375              << i << (int)ArgSize.getQuantity() << 0xff
6376              << TheCall->getSourceRange();
6377     }
6378     TheCall->setArg(i, Arg.get());
6379     i++;
6380   }
6381 
6382   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6383   // call to avoid duplicate diagnostics.
6384   if (!IsSizeCall) {
6385     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6386     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6387     bool Success = CheckFormatArguments(
6388         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6389         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6390         CheckedVarArgs);
6391     if (!Success)
6392       return true;
6393   }
6394 
6395   if (IsSizeCall) {
6396     TheCall->setType(Context.getSizeType());
6397   } else {
6398     TheCall->setType(Context.VoidPtrTy);
6399   }
6400   return false;
6401 }
6402 
6403 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6404 /// TheCall is a constant expression.
6405 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6406                                   llvm::APSInt &Result) {
6407   Expr *Arg = TheCall->getArg(ArgNum);
6408   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6409   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6410 
6411   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6412 
6413   Optional<llvm::APSInt> R;
6414   if (!(R = Arg->getIntegerConstantExpr(Context)))
6415     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6416            << FDecl->getDeclName() << Arg->getSourceRange();
6417   Result = *R;
6418   return false;
6419 }
6420 
6421 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6422 /// TheCall is a constant expression in the range [Low, High].
6423 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6424                                        int Low, int High, bool RangeIsError) {
6425   if (isConstantEvaluated())
6426     return false;
6427   llvm::APSInt Result;
6428 
6429   // We can't check the value of a dependent argument.
6430   Expr *Arg = TheCall->getArg(ArgNum);
6431   if (Arg->isTypeDependent() || Arg->isValueDependent())
6432     return false;
6433 
6434   // Check constant-ness first.
6435   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6436     return true;
6437 
6438   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6439     if (RangeIsError)
6440       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6441              << Result.toString(10) << Low << High << Arg->getSourceRange();
6442     else
6443       // Defer the warning until we know if the code will be emitted so that
6444       // dead code can ignore this.
6445       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6446                           PDiag(diag::warn_argument_invalid_range)
6447                               << Result.toString(10) << Low << High
6448                               << Arg->getSourceRange());
6449   }
6450 
6451   return false;
6452 }
6453 
6454 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6455 /// TheCall is a constant expression is a multiple of Num..
6456 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6457                                           unsigned Num) {
6458   llvm::APSInt Result;
6459 
6460   // We can't check the value of a dependent argument.
6461   Expr *Arg = TheCall->getArg(ArgNum);
6462   if (Arg->isTypeDependent() || Arg->isValueDependent())
6463     return false;
6464 
6465   // Check constant-ness first.
6466   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6467     return true;
6468 
6469   if (Result.getSExtValue() % Num != 0)
6470     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6471            << Num << Arg->getSourceRange();
6472 
6473   return false;
6474 }
6475 
6476 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6477 /// constant expression representing a power of 2.
6478 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6479   llvm::APSInt Result;
6480 
6481   // We can't check the value of a dependent argument.
6482   Expr *Arg = TheCall->getArg(ArgNum);
6483   if (Arg->isTypeDependent() || Arg->isValueDependent())
6484     return false;
6485 
6486   // Check constant-ness first.
6487   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6488     return true;
6489 
6490   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6491   // and only if x is a power of 2.
6492   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6493     return false;
6494 
6495   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6496          << Arg->getSourceRange();
6497 }
6498 
6499 static bool IsShiftedByte(llvm::APSInt Value) {
6500   if (Value.isNegative())
6501     return false;
6502 
6503   // Check if it's a shifted byte, by shifting it down
6504   while (true) {
6505     // If the value fits in the bottom byte, the check passes.
6506     if (Value < 0x100)
6507       return true;
6508 
6509     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6510     // fails.
6511     if ((Value & 0xFF) != 0)
6512       return false;
6513 
6514     // If the bottom 8 bits are all 0, but something above that is nonzero,
6515     // then shifting the value right by 8 bits won't affect whether it's a
6516     // shifted byte or not. So do that, and go round again.
6517     Value >>= 8;
6518   }
6519 }
6520 
6521 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6522 /// a constant expression representing an arbitrary byte value shifted left by
6523 /// a multiple of 8 bits.
6524 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6525                                              unsigned ArgBits) {
6526   llvm::APSInt Result;
6527 
6528   // We can't check the value of a dependent argument.
6529   Expr *Arg = TheCall->getArg(ArgNum);
6530   if (Arg->isTypeDependent() || Arg->isValueDependent())
6531     return false;
6532 
6533   // Check constant-ness first.
6534   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6535     return true;
6536 
6537   // Truncate to the given size.
6538   Result = Result.getLoBits(ArgBits);
6539   Result.setIsUnsigned(true);
6540 
6541   if (IsShiftedByte(Result))
6542     return false;
6543 
6544   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6545          << Arg->getSourceRange();
6546 }
6547 
6548 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6549 /// TheCall is a constant expression representing either a shifted byte value,
6550 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6551 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6552 /// Arm MVE intrinsics.
6553 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6554                                                    int ArgNum,
6555                                                    unsigned ArgBits) {
6556   llvm::APSInt Result;
6557 
6558   // We can't check the value of a dependent argument.
6559   Expr *Arg = TheCall->getArg(ArgNum);
6560   if (Arg->isTypeDependent() || Arg->isValueDependent())
6561     return false;
6562 
6563   // Check constant-ness first.
6564   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6565     return true;
6566 
6567   // Truncate to the given size.
6568   Result = Result.getLoBits(ArgBits);
6569   Result.setIsUnsigned(true);
6570 
6571   // Check to see if it's in either of the required forms.
6572   if (IsShiftedByte(Result) ||
6573       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6574     return false;
6575 
6576   return Diag(TheCall->getBeginLoc(),
6577               diag::err_argument_not_shifted_byte_or_xxff)
6578          << Arg->getSourceRange();
6579 }
6580 
6581 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6582 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6583   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6584     if (checkArgCount(*this, TheCall, 2))
6585       return true;
6586     Expr *Arg0 = TheCall->getArg(0);
6587     Expr *Arg1 = TheCall->getArg(1);
6588 
6589     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6590     if (FirstArg.isInvalid())
6591       return true;
6592     QualType FirstArgType = FirstArg.get()->getType();
6593     if (!FirstArgType->isAnyPointerType())
6594       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6595                << "first" << FirstArgType << Arg0->getSourceRange();
6596     TheCall->setArg(0, FirstArg.get());
6597 
6598     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6599     if (SecArg.isInvalid())
6600       return true;
6601     QualType SecArgType = SecArg.get()->getType();
6602     if (!SecArgType->isIntegerType())
6603       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6604                << "second" << SecArgType << Arg1->getSourceRange();
6605 
6606     // Derive the return type from the pointer argument.
6607     TheCall->setType(FirstArgType);
6608     return false;
6609   }
6610 
6611   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6612     if (checkArgCount(*this, TheCall, 2))
6613       return true;
6614 
6615     Expr *Arg0 = TheCall->getArg(0);
6616     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6617     if (FirstArg.isInvalid())
6618       return true;
6619     QualType FirstArgType = FirstArg.get()->getType();
6620     if (!FirstArgType->isAnyPointerType())
6621       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6622                << "first" << FirstArgType << Arg0->getSourceRange();
6623     TheCall->setArg(0, FirstArg.get());
6624 
6625     // Derive the return type from the pointer argument.
6626     TheCall->setType(FirstArgType);
6627 
6628     // Second arg must be an constant in range [0,15]
6629     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6630   }
6631 
6632   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6633     if (checkArgCount(*this, TheCall, 2))
6634       return true;
6635     Expr *Arg0 = TheCall->getArg(0);
6636     Expr *Arg1 = TheCall->getArg(1);
6637 
6638     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6639     if (FirstArg.isInvalid())
6640       return true;
6641     QualType FirstArgType = FirstArg.get()->getType();
6642     if (!FirstArgType->isAnyPointerType())
6643       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6644                << "first" << FirstArgType << Arg0->getSourceRange();
6645 
6646     QualType SecArgType = Arg1->getType();
6647     if (!SecArgType->isIntegerType())
6648       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6649                << "second" << SecArgType << Arg1->getSourceRange();
6650     TheCall->setType(Context.IntTy);
6651     return false;
6652   }
6653 
6654   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6655       BuiltinID == AArch64::BI__builtin_arm_stg) {
6656     if (checkArgCount(*this, TheCall, 1))
6657       return true;
6658     Expr *Arg0 = TheCall->getArg(0);
6659     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6660     if (FirstArg.isInvalid())
6661       return true;
6662 
6663     QualType FirstArgType = FirstArg.get()->getType();
6664     if (!FirstArgType->isAnyPointerType())
6665       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6666                << "first" << FirstArgType << Arg0->getSourceRange();
6667     TheCall->setArg(0, FirstArg.get());
6668 
6669     // Derive the return type from the pointer argument.
6670     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6671       TheCall->setType(FirstArgType);
6672     return false;
6673   }
6674 
6675   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6676     Expr *ArgA = TheCall->getArg(0);
6677     Expr *ArgB = TheCall->getArg(1);
6678 
6679     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6680     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6681 
6682     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6683       return true;
6684 
6685     QualType ArgTypeA = ArgExprA.get()->getType();
6686     QualType ArgTypeB = ArgExprB.get()->getType();
6687 
6688     auto isNull = [&] (Expr *E) -> bool {
6689       return E->isNullPointerConstant(
6690                         Context, Expr::NPC_ValueDependentIsNotNull); };
6691 
6692     // argument should be either a pointer or null
6693     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6694       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6695         << "first" << ArgTypeA << ArgA->getSourceRange();
6696 
6697     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6698       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6699         << "second" << ArgTypeB << ArgB->getSourceRange();
6700 
6701     // Ensure Pointee types are compatible
6702     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6703         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6704       QualType pointeeA = ArgTypeA->getPointeeType();
6705       QualType pointeeB = ArgTypeB->getPointeeType();
6706       if (!Context.typesAreCompatible(
6707              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6708              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6709         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6710           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6711           << ArgB->getSourceRange();
6712       }
6713     }
6714 
6715     // at least one argument should be pointer type
6716     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6717       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6718         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6719 
6720     if (isNull(ArgA)) // adopt type of the other pointer
6721       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6722 
6723     if (isNull(ArgB))
6724       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6725 
6726     TheCall->setArg(0, ArgExprA.get());
6727     TheCall->setArg(1, ArgExprB.get());
6728     TheCall->setType(Context.LongLongTy);
6729     return false;
6730   }
6731   assert(false && "Unhandled ARM MTE intrinsic");
6732   return true;
6733 }
6734 
6735 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6736 /// TheCall is an ARM/AArch64 special register string literal.
6737 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6738                                     int ArgNum, unsigned ExpectedFieldNum,
6739                                     bool AllowName) {
6740   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6741                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6742                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6743                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6744                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6745                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6746   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6747                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6748                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6749                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6750                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6751                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6752   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6753 
6754   // We can't check the value of a dependent argument.
6755   Expr *Arg = TheCall->getArg(ArgNum);
6756   if (Arg->isTypeDependent() || Arg->isValueDependent())
6757     return false;
6758 
6759   // Check if the argument is a string literal.
6760   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6761     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6762            << Arg->getSourceRange();
6763 
6764   // Check the type of special register given.
6765   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6766   SmallVector<StringRef, 6> Fields;
6767   Reg.split(Fields, ":");
6768 
6769   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6770     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6771            << Arg->getSourceRange();
6772 
6773   // If the string is the name of a register then we cannot check that it is
6774   // valid here but if the string is of one the forms described in ACLE then we
6775   // can check that the supplied fields are integers and within the valid
6776   // ranges.
6777   if (Fields.size() > 1) {
6778     bool FiveFields = Fields.size() == 5;
6779 
6780     bool ValidString = true;
6781     if (IsARMBuiltin) {
6782       ValidString &= Fields[0].startswith_lower("cp") ||
6783                      Fields[0].startswith_lower("p");
6784       if (ValidString)
6785         Fields[0] =
6786           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6787 
6788       ValidString &= Fields[2].startswith_lower("c");
6789       if (ValidString)
6790         Fields[2] = Fields[2].drop_front(1);
6791 
6792       if (FiveFields) {
6793         ValidString &= Fields[3].startswith_lower("c");
6794         if (ValidString)
6795           Fields[3] = Fields[3].drop_front(1);
6796       }
6797     }
6798 
6799     SmallVector<int, 5> Ranges;
6800     if (FiveFields)
6801       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6802     else
6803       Ranges.append({15, 7, 15});
6804 
6805     for (unsigned i=0; i<Fields.size(); ++i) {
6806       int IntField;
6807       ValidString &= !Fields[i].getAsInteger(10, IntField);
6808       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6809     }
6810 
6811     if (!ValidString)
6812       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6813              << Arg->getSourceRange();
6814   } else if (IsAArch64Builtin && Fields.size() == 1) {
6815     // If the register name is one of those that appear in the condition below
6816     // and the special register builtin being used is one of the write builtins,
6817     // then we require that the argument provided for writing to the register
6818     // is an integer constant expression. This is because it will be lowered to
6819     // an MSR (immediate) instruction, so we need to know the immediate at
6820     // compile time.
6821     if (TheCall->getNumArgs() != 2)
6822       return false;
6823 
6824     std::string RegLower = Reg.lower();
6825     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6826         RegLower != "pan" && RegLower != "uao")
6827       return false;
6828 
6829     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6830   }
6831 
6832   return false;
6833 }
6834 
6835 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6836 /// Emit an error and return true on failure; return false on success.
6837 /// TypeStr is a string containing the type descriptor of the value returned by
6838 /// the builtin and the descriptors of the expected type of the arguments.
6839 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6840 
6841   assert((TypeStr[0] != '\0') &&
6842          "Invalid types in PPC MMA builtin declaration");
6843 
6844   unsigned Mask = 0;
6845   unsigned ArgNum = 0;
6846 
6847   // The first type in TypeStr is the type of the value returned by the
6848   // builtin. So we first read that type and change the type of TheCall.
6849   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6850   TheCall->setType(type);
6851 
6852   while (*TypeStr != '\0') {
6853     Mask = 0;
6854     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6855     if (ArgNum >= TheCall->getNumArgs()) {
6856       ArgNum++;
6857       break;
6858     }
6859 
6860     Expr *Arg = TheCall->getArg(ArgNum);
6861     QualType ArgType = Arg->getType();
6862 
6863     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6864         (!ExpectedType->isVoidPointerType() &&
6865            ArgType.getCanonicalType() != ExpectedType))
6866       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6867              << ArgType << ExpectedType << 1 << 0 << 0;
6868 
6869     // If the value of the Mask is not 0, we have a constraint in the size of
6870     // the integer argument so here we ensure the argument is a constant that
6871     // is in the valid range.
6872     if (Mask != 0 &&
6873         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6874       return true;
6875 
6876     ArgNum++;
6877   }
6878 
6879   // In case we exited early from the previous loop, there are other types to
6880   // read from TypeStr. So we need to read them all to ensure we have the right
6881   // number of arguments in TheCall and if it is not the case, to display a
6882   // better error message.
6883   while (*TypeStr != '\0') {
6884     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6885     ArgNum++;
6886   }
6887   if (checkArgCount(*this, TheCall, ArgNum))
6888     return true;
6889 
6890   return false;
6891 }
6892 
6893 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6894 /// This checks that the target supports __builtin_longjmp and
6895 /// that val is a constant 1.
6896 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6897   if (!Context.getTargetInfo().hasSjLjLowering())
6898     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6899            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6900 
6901   Expr *Arg = TheCall->getArg(1);
6902   llvm::APSInt Result;
6903 
6904   // TODO: This is less than ideal. Overload this to take a value.
6905   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6906     return true;
6907 
6908   if (Result != 1)
6909     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6910            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6911 
6912   return false;
6913 }
6914 
6915 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6916 /// This checks that the target supports __builtin_setjmp.
6917 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6918   if (!Context.getTargetInfo().hasSjLjLowering())
6919     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6920            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6921   return false;
6922 }
6923 
6924 namespace {
6925 
6926 class UncoveredArgHandler {
6927   enum { Unknown = -1, AllCovered = -2 };
6928 
6929   signed FirstUncoveredArg = Unknown;
6930   SmallVector<const Expr *, 4> DiagnosticExprs;
6931 
6932 public:
6933   UncoveredArgHandler() = default;
6934 
6935   bool hasUncoveredArg() const {
6936     return (FirstUncoveredArg >= 0);
6937   }
6938 
6939   unsigned getUncoveredArg() const {
6940     assert(hasUncoveredArg() && "no uncovered argument");
6941     return FirstUncoveredArg;
6942   }
6943 
6944   void setAllCovered() {
6945     // A string has been found with all arguments covered, so clear out
6946     // the diagnostics.
6947     DiagnosticExprs.clear();
6948     FirstUncoveredArg = AllCovered;
6949   }
6950 
6951   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6952     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6953 
6954     // Don't update if a previous string covers all arguments.
6955     if (FirstUncoveredArg == AllCovered)
6956       return;
6957 
6958     // UncoveredArgHandler tracks the highest uncovered argument index
6959     // and with it all the strings that match this index.
6960     if (NewFirstUncoveredArg == FirstUncoveredArg)
6961       DiagnosticExprs.push_back(StrExpr);
6962     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6963       DiagnosticExprs.clear();
6964       DiagnosticExprs.push_back(StrExpr);
6965       FirstUncoveredArg = NewFirstUncoveredArg;
6966     }
6967   }
6968 
6969   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6970 };
6971 
6972 enum StringLiteralCheckType {
6973   SLCT_NotALiteral,
6974   SLCT_UncheckedLiteral,
6975   SLCT_CheckedLiteral
6976 };
6977 
6978 } // namespace
6979 
6980 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6981                                      BinaryOperatorKind BinOpKind,
6982                                      bool AddendIsRight) {
6983   unsigned BitWidth = Offset.getBitWidth();
6984   unsigned AddendBitWidth = Addend.getBitWidth();
6985   // There might be negative interim results.
6986   if (Addend.isUnsigned()) {
6987     Addend = Addend.zext(++AddendBitWidth);
6988     Addend.setIsSigned(true);
6989   }
6990   // Adjust the bit width of the APSInts.
6991   if (AddendBitWidth > BitWidth) {
6992     Offset = Offset.sext(AddendBitWidth);
6993     BitWidth = AddendBitWidth;
6994   } else if (BitWidth > AddendBitWidth) {
6995     Addend = Addend.sext(BitWidth);
6996   }
6997 
6998   bool Ov = false;
6999   llvm::APSInt ResOffset = Offset;
7000   if (BinOpKind == BO_Add)
7001     ResOffset = Offset.sadd_ov(Addend, Ov);
7002   else {
7003     assert(AddendIsRight && BinOpKind == BO_Sub &&
7004            "operator must be add or sub with addend on the right");
7005     ResOffset = Offset.ssub_ov(Addend, Ov);
7006   }
7007 
7008   // We add an offset to a pointer here so we should support an offset as big as
7009   // possible.
7010   if (Ov) {
7011     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7012            "index (intermediate) result too big");
7013     Offset = Offset.sext(2 * BitWidth);
7014     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7015     return;
7016   }
7017 
7018   Offset = ResOffset;
7019 }
7020 
7021 namespace {
7022 
7023 // This is a wrapper class around StringLiteral to support offsetted string
7024 // literals as format strings. It takes the offset into account when returning
7025 // the string and its length or the source locations to display notes correctly.
7026 class FormatStringLiteral {
7027   const StringLiteral *FExpr;
7028   int64_t Offset;
7029 
7030  public:
7031   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7032       : FExpr(fexpr), Offset(Offset) {}
7033 
7034   StringRef getString() const {
7035     return FExpr->getString().drop_front(Offset);
7036   }
7037 
7038   unsigned getByteLength() const {
7039     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7040   }
7041 
7042   unsigned getLength() const { return FExpr->getLength() - Offset; }
7043   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7044 
7045   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7046 
7047   QualType getType() const { return FExpr->getType(); }
7048 
7049   bool isAscii() const { return FExpr->isAscii(); }
7050   bool isWide() const { return FExpr->isWide(); }
7051   bool isUTF8() const { return FExpr->isUTF8(); }
7052   bool isUTF16() const { return FExpr->isUTF16(); }
7053   bool isUTF32() const { return FExpr->isUTF32(); }
7054   bool isPascal() const { return FExpr->isPascal(); }
7055 
7056   SourceLocation getLocationOfByte(
7057       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7058       const TargetInfo &Target, unsigned *StartToken = nullptr,
7059       unsigned *StartTokenByteOffset = nullptr) const {
7060     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7061                                     StartToken, StartTokenByteOffset);
7062   }
7063 
7064   SourceLocation getBeginLoc() const LLVM_READONLY {
7065     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7066   }
7067 
7068   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7069 };
7070 
7071 }  // namespace
7072 
7073 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7074                               const Expr *OrigFormatExpr,
7075                               ArrayRef<const Expr *> Args,
7076                               bool HasVAListArg, unsigned format_idx,
7077                               unsigned firstDataArg,
7078                               Sema::FormatStringType Type,
7079                               bool inFunctionCall,
7080                               Sema::VariadicCallType CallType,
7081                               llvm::SmallBitVector &CheckedVarArgs,
7082                               UncoveredArgHandler &UncoveredArg,
7083                               bool IgnoreStringsWithoutSpecifiers);
7084 
7085 // Determine if an expression is a string literal or constant string.
7086 // If this function returns false on the arguments to a function expecting a
7087 // format string, we will usually need to emit a warning.
7088 // True string literals are then checked by CheckFormatString.
7089 static StringLiteralCheckType
7090 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7091                       bool HasVAListArg, unsigned format_idx,
7092                       unsigned firstDataArg, Sema::FormatStringType Type,
7093                       Sema::VariadicCallType CallType, bool InFunctionCall,
7094                       llvm::SmallBitVector &CheckedVarArgs,
7095                       UncoveredArgHandler &UncoveredArg,
7096                       llvm::APSInt Offset,
7097                       bool IgnoreStringsWithoutSpecifiers = false) {
7098   if (S.isConstantEvaluated())
7099     return SLCT_NotALiteral;
7100  tryAgain:
7101   assert(Offset.isSigned() && "invalid offset");
7102 
7103   if (E->isTypeDependent() || E->isValueDependent())
7104     return SLCT_NotALiteral;
7105 
7106   E = E->IgnoreParenCasts();
7107 
7108   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7109     // Technically -Wformat-nonliteral does not warn about this case.
7110     // The behavior of printf and friends in this case is implementation
7111     // dependent.  Ideally if the format string cannot be null then
7112     // it should have a 'nonnull' attribute in the function prototype.
7113     return SLCT_UncheckedLiteral;
7114 
7115   switch (E->getStmtClass()) {
7116   case Stmt::BinaryConditionalOperatorClass:
7117   case Stmt::ConditionalOperatorClass: {
7118     // The expression is a literal if both sub-expressions were, and it was
7119     // completely checked only if both sub-expressions were checked.
7120     const AbstractConditionalOperator *C =
7121         cast<AbstractConditionalOperator>(E);
7122 
7123     // Determine whether it is necessary to check both sub-expressions, for
7124     // example, because the condition expression is a constant that can be
7125     // evaluated at compile time.
7126     bool CheckLeft = true, CheckRight = true;
7127 
7128     bool Cond;
7129     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7130                                                  S.isConstantEvaluated())) {
7131       if (Cond)
7132         CheckRight = false;
7133       else
7134         CheckLeft = false;
7135     }
7136 
7137     // We need to maintain the offsets for the right and the left hand side
7138     // separately to check if every possible indexed expression is a valid
7139     // string literal. They might have different offsets for different string
7140     // literals in the end.
7141     StringLiteralCheckType Left;
7142     if (!CheckLeft)
7143       Left = SLCT_UncheckedLiteral;
7144     else {
7145       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7146                                    HasVAListArg, format_idx, firstDataArg,
7147                                    Type, CallType, InFunctionCall,
7148                                    CheckedVarArgs, UncoveredArg, Offset,
7149                                    IgnoreStringsWithoutSpecifiers);
7150       if (Left == SLCT_NotALiteral || !CheckRight) {
7151         return Left;
7152       }
7153     }
7154 
7155     StringLiteralCheckType Right = checkFormatStringExpr(
7156         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7157         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7158         IgnoreStringsWithoutSpecifiers);
7159 
7160     return (CheckLeft && Left < Right) ? Left : Right;
7161   }
7162 
7163   case Stmt::ImplicitCastExprClass:
7164     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7165     goto tryAgain;
7166 
7167   case Stmt::OpaqueValueExprClass:
7168     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7169       E = src;
7170       goto tryAgain;
7171     }
7172     return SLCT_NotALiteral;
7173 
7174   case Stmt::PredefinedExprClass:
7175     // While __func__, etc., are technically not string literals, they
7176     // cannot contain format specifiers and thus are not a security
7177     // liability.
7178     return SLCT_UncheckedLiteral;
7179 
7180   case Stmt::DeclRefExprClass: {
7181     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7182 
7183     // As an exception, do not flag errors for variables binding to
7184     // const string literals.
7185     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7186       bool isConstant = false;
7187       QualType T = DR->getType();
7188 
7189       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7190         isConstant = AT->getElementType().isConstant(S.Context);
7191       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7192         isConstant = T.isConstant(S.Context) &&
7193                      PT->getPointeeType().isConstant(S.Context);
7194       } else if (T->isObjCObjectPointerType()) {
7195         // In ObjC, there is usually no "const ObjectPointer" type,
7196         // so don't check if the pointee type is constant.
7197         isConstant = T.isConstant(S.Context);
7198       }
7199 
7200       if (isConstant) {
7201         if (const Expr *Init = VD->getAnyInitializer()) {
7202           // Look through initializers like const char c[] = { "foo" }
7203           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7204             if (InitList->isStringLiteralInit())
7205               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7206           }
7207           return checkFormatStringExpr(S, Init, Args,
7208                                        HasVAListArg, format_idx,
7209                                        firstDataArg, Type, CallType,
7210                                        /*InFunctionCall*/ false, CheckedVarArgs,
7211                                        UncoveredArg, Offset);
7212         }
7213       }
7214 
7215       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7216       // special check to see if the format string is a function parameter
7217       // of the function calling the printf function.  If the function
7218       // has an attribute indicating it is a printf-like function, then we
7219       // should suppress warnings concerning non-literals being used in a call
7220       // to a vprintf function.  For example:
7221       //
7222       // void
7223       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7224       //      va_list ap;
7225       //      va_start(ap, fmt);
7226       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7227       //      ...
7228       // }
7229       if (HasVAListArg) {
7230         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7231           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7232             int PVIndex = PV->getFunctionScopeIndex() + 1;
7233             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7234               // adjust for implicit parameter
7235               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7236                 if (MD->isInstance())
7237                   ++PVIndex;
7238               // We also check if the formats are compatible.
7239               // We can't pass a 'scanf' string to a 'printf' function.
7240               if (PVIndex == PVFormat->getFormatIdx() &&
7241                   Type == S.GetFormatStringType(PVFormat))
7242                 return SLCT_UncheckedLiteral;
7243             }
7244           }
7245         }
7246       }
7247     }
7248 
7249     return SLCT_NotALiteral;
7250   }
7251 
7252   case Stmt::CallExprClass:
7253   case Stmt::CXXMemberCallExprClass: {
7254     const CallExpr *CE = cast<CallExpr>(E);
7255     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7256       bool IsFirst = true;
7257       StringLiteralCheckType CommonResult;
7258       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7259         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7260         StringLiteralCheckType Result = checkFormatStringExpr(
7261             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7262             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7263             IgnoreStringsWithoutSpecifiers);
7264         if (IsFirst) {
7265           CommonResult = Result;
7266           IsFirst = false;
7267         }
7268       }
7269       if (!IsFirst)
7270         return CommonResult;
7271 
7272       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7273         unsigned BuiltinID = FD->getBuiltinID();
7274         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7275             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7276           const Expr *Arg = CE->getArg(0);
7277           return checkFormatStringExpr(S, Arg, Args,
7278                                        HasVAListArg, format_idx,
7279                                        firstDataArg, Type, CallType,
7280                                        InFunctionCall, CheckedVarArgs,
7281                                        UncoveredArg, Offset,
7282                                        IgnoreStringsWithoutSpecifiers);
7283         }
7284       }
7285     }
7286 
7287     return SLCT_NotALiteral;
7288   }
7289   case Stmt::ObjCMessageExprClass: {
7290     const auto *ME = cast<ObjCMessageExpr>(E);
7291     if (const auto *MD = ME->getMethodDecl()) {
7292       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7293         // As a special case heuristic, if we're using the method -[NSBundle
7294         // localizedStringForKey:value:table:], ignore any key strings that lack
7295         // format specifiers. The idea is that if the key doesn't have any
7296         // format specifiers then its probably just a key to map to the
7297         // localized strings. If it does have format specifiers though, then its
7298         // likely that the text of the key is the format string in the
7299         // programmer's language, and should be checked.
7300         const ObjCInterfaceDecl *IFace;
7301         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7302             IFace->getIdentifier()->isStr("NSBundle") &&
7303             MD->getSelector().isKeywordSelector(
7304                 {"localizedStringForKey", "value", "table"})) {
7305           IgnoreStringsWithoutSpecifiers = true;
7306         }
7307 
7308         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7309         return checkFormatStringExpr(
7310             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7311             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7312             IgnoreStringsWithoutSpecifiers);
7313       }
7314     }
7315 
7316     return SLCT_NotALiteral;
7317   }
7318   case Stmt::ObjCStringLiteralClass:
7319   case Stmt::StringLiteralClass: {
7320     const StringLiteral *StrE = nullptr;
7321 
7322     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7323       StrE = ObjCFExpr->getString();
7324     else
7325       StrE = cast<StringLiteral>(E);
7326 
7327     if (StrE) {
7328       if (Offset.isNegative() || Offset > StrE->getLength()) {
7329         // TODO: It would be better to have an explicit warning for out of
7330         // bounds literals.
7331         return SLCT_NotALiteral;
7332       }
7333       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7334       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7335                         firstDataArg, Type, InFunctionCall, CallType,
7336                         CheckedVarArgs, UncoveredArg,
7337                         IgnoreStringsWithoutSpecifiers);
7338       return SLCT_CheckedLiteral;
7339     }
7340 
7341     return SLCT_NotALiteral;
7342   }
7343   case Stmt::BinaryOperatorClass: {
7344     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7345 
7346     // A string literal + an int offset is still a string literal.
7347     if (BinOp->isAdditiveOp()) {
7348       Expr::EvalResult LResult, RResult;
7349 
7350       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7351           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7352       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7353           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7354 
7355       if (LIsInt != RIsInt) {
7356         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7357 
7358         if (LIsInt) {
7359           if (BinOpKind == BO_Add) {
7360             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7361             E = BinOp->getRHS();
7362             goto tryAgain;
7363           }
7364         } else {
7365           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7366           E = BinOp->getLHS();
7367           goto tryAgain;
7368         }
7369       }
7370     }
7371 
7372     return SLCT_NotALiteral;
7373   }
7374   case Stmt::UnaryOperatorClass: {
7375     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7376     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7377     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7378       Expr::EvalResult IndexResult;
7379       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7380                                        Expr::SE_NoSideEffects,
7381                                        S.isConstantEvaluated())) {
7382         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7383                    /*RHS is int*/ true);
7384         E = ASE->getBase();
7385         goto tryAgain;
7386       }
7387     }
7388 
7389     return SLCT_NotALiteral;
7390   }
7391 
7392   default:
7393     return SLCT_NotALiteral;
7394   }
7395 }
7396 
7397 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7398   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7399       .Case("scanf", FST_Scanf)
7400       .Cases("printf", "printf0", FST_Printf)
7401       .Cases("NSString", "CFString", FST_NSString)
7402       .Case("strftime", FST_Strftime)
7403       .Case("strfmon", FST_Strfmon)
7404       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7405       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7406       .Case("os_trace", FST_OSLog)
7407       .Case("os_log", FST_OSLog)
7408       .Default(FST_Unknown);
7409 }
7410 
7411 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7412 /// functions) for correct use of format strings.
7413 /// Returns true if a format string has been fully checked.
7414 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7415                                 ArrayRef<const Expr *> Args,
7416                                 bool IsCXXMember,
7417                                 VariadicCallType CallType,
7418                                 SourceLocation Loc, SourceRange Range,
7419                                 llvm::SmallBitVector &CheckedVarArgs) {
7420   FormatStringInfo FSI;
7421   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7422     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7423                                 FSI.FirstDataArg, GetFormatStringType(Format),
7424                                 CallType, Loc, Range, CheckedVarArgs);
7425   return false;
7426 }
7427 
7428 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7429                                 bool HasVAListArg, unsigned format_idx,
7430                                 unsigned firstDataArg, FormatStringType Type,
7431                                 VariadicCallType CallType,
7432                                 SourceLocation Loc, SourceRange Range,
7433                                 llvm::SmallBitVector &CheckedVarArgs) {
7434   // CHECK: printf/scanf-like function is called with no format string.
7435   if (format_idx >= Args.size()) {
7436     Diag(Loc, diag::warn_missing_format_string) << Range;
7437     return false;
7438   }
7439 
7440   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7441 
7442   // CHECK: format string is not a string literal.
7443   //
7444   // Dynamically generated format strings are difficult to
7445   // automatically vet at compile time.  Requiring that format strings
7446   // are string literals: (1) permits the checking of format strings by
7447   // the compiler and thereby (2) can practically remove the source of
7448   // many format string exploits.
7449 
7450   // Format string can be either ObjC string (e.g. @"%d") or
7451   // C string (e.g. "%d")
7452   // ObjC string uses the same format specifiers as C string, so we can use
7453   // the same format string checking logic for both ObjC and C strings.
7454   UncoveredArgHandler UncoveredArg;
7455   StringLiteralCheckType CT =
7456       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7457                             format_idx, firstDataArg, Type, CallType,
7458                             /*IsFunctionCall*/ true, CheckedVarArgs,
7459                             UncoveredArg,
7460                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7461 
7462   // Generate a diagnostic where an uncovered argument is detected.
7463   if (UncoveredArg.hasUncoveredArg()) {
7464     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7465     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7466     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7467   }
7468 
7469   if (CT != SLCT_NotALiteral)
7470     // Literal format string found, check done!
7471     return CT == SLCT_CheckedLiteral;
7472 
7473   // Strftime is particular as it always uses a single 'time' argument,
7474   // so it is safe to pass a non-literal string.
7475   if (Type == FST_Strftime)
7476     return false;
7477 
7478   // Do not emit diag when the string param is a macro expansion and the
7479   // format is either NSString or CFString. This is a hack to prevent
7480   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7481   // which are usually used in place of NS and CF string literals.
7482   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7483   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7484     return false;
7485 
7486   // If there are no arguments specified, warn with -Wformat-security, otherwise
7487   // warn only with -Wformat-nonliteral.
7488   if (Args.size() == firstDataArg) {
7489     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7490       << OrigFormatExpr->getSourceRange();
7491     switch (Type) {
7492     default:
7493       break;
7494     case FST_Kprintf:
7495     case FST_FreeBSDKPrintf:
7496     case FST_Printf:
7497       Diag(FormatLoc, diag::note_format_security_fixit)
7498         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7499       break;
7500     case FST_NSString:
7501       Diag(FormatLoc, diag::note_format_security_fixit)
7502         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7503       break;
7504     }
7505   } else {
7506     Diag(FormatLoc, diag::warn_format_nonliteral)
7507       << OrigFormatExpr->getSourceRange();
7508   }
7509   return false;
7510 }
7511 
7512 namespace {
7513 
7514 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7515 protected:
7516   Sema &S;
7517   const FormatStringLiteral *FExpr;
7518   const Expr *OrigFormatExpr;
7519   const Sema::FormatStringType FSType;
7520   const unsigned FirstDataArg;
7521   const unsigned NumDataArgs;
7522   const char *Beg; // Start of format string.
7523   const bool HasVAListArg;
7524   ArrayRef<const Expr *> Args;
7525   unsigned FormatIdx;
7526   llvm::SmallBitVector CoveredArgs;
7527   bool usesPositionalArgs = false;
7528   bool atFirstArg = true;
7529   bool inFunctionCall;
7530   Sema::VariadicCallType CallType;
7531   llvm::SmallBitVector &CheckedVarArgs;
7532   UncoveredArgHandler &UncoveredArg;
7533 
7534 public:
7535   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7536                      const Expr *origFormatExpr,
7537                      const Sema::FormatStringType type, unsigned firstDataArg,
7538                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7539                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7540                      bool inFunctionCall, Sema::VariadicCallType callType,
7541                      llvm::SmallBitVector &CheckedVarArgs,
7542                      UncoveredArgHandler &UncoveredArg)
7543       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7544         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7545         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7546         inFunctionCall(inFunctionCall), CallType(callType),
7547         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7548     CoveredArgs.resize(numDataArgs);
7549     CoveredArgs.reset();
7550   }
7551 
7552   void DoneProcessing();
7553 
7554   void HandleIncompleteSpecifier(const char *startSpecifier,
7555                                  unsigned specifierLen) override;
7556 
7557   void HandleInvalidLengthModifier(
7558                            const analyze_format_string::FormatSpecifier &FS,
7559                            const analyze_format_string::ConversionSpecifier &CS,
7560                            const char *startSpecifier, unsigned specifierLen,
7561                            unsigned DiagID);
7562 
7563   void HandleNonStandardLengthModifier(
7564                     const analyze_format_string::FormatSpecifier &FS,
7565                     const char *startSpecifier, unsigned specifierLen);
7566 
7567   void HandleNonStandardConversionSpecifier(
7568                     const analyze_format_string::ConversionSpecifier &CS,
7569                     const char *startSpecifier, unsigned specifierLen);
7570 
7571   void HandlePosition(const char *startPos, unsigned posLen) override;
7572 
7573   void HandleInvalidPosition(const char *startSpecifier,
7574                              unsigned specifierLen,
7575                              analyze_format_string::PositionContext p) override;
7576 
7577   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7578 
7579   void HandleNullChar(const char *nullCharacter) override;
7580 
7581   template <typename Range>
7582   static void
7583   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7584                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7585                        bool IsStringLocation, Range StringRange,
7586                        ArrayRef<FixItHint> Fixit = None);
7587 
7588 protected:
7589   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7590                                         const char *startSpec,
7591                                         unsigned specifierLen,
7592                                         const char *csStart, unsigned csLen);
7593 
7594   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7595                                          const char *startSpec,
7596                                          unsigned specifierLen);
7597 
7598   SourceRange getFormatStringRange();
7599   CharSourceRange getSpecifierRange(const char *startSpecifier,
7600                                     unsigned specifierLen);
7601   SourceLocation getLocationOfByte(const char *x);
7602 
7603   const Expr *getDataArg(unsigned i) const;
7604 
7605   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7606                     const analyze_format_string::ConversionSpecifier &CS,
7607                     const char *startSpecifier, unsigned specifierLen,
7608                     unsigned argIndex);
7609 
7610   template <typename Range>
7611   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7612                             bool IsStringLocation, Range StringRange,
7613                             ArrayRef<FixItHint> Fixit = None);
7614 };
7615 
7616 } // namespace
7617 
7618 SourceRange CheckFormatHandler::getFormatStringRange() {
7619   return OrigFormatExpr->getSourceRange();
7620 }
7621 
7622 CharSourceRange CheckFormatHandler::
7623 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7624   SourceLocation Start = getLocationOfByte(startSpecifier);
7625   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7626 
7627   // Advance the end SourceLocation by one due to half-open ranges.
7628   End = End.getLocWithOffset(1);
7629 
7630   return CharSourceRange::getCharRange(Start, End);
7631 }
7632 
7633 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7634   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7635                                   S.getLangOpts(), S.Context.getTargetInfo());
7636 }
7637 
7638 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7639                                                    unsigned specifierLen){
7640   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7641                        getLocationOfByte(startSpecifier),
7642                        /*IsStringLocation*/true,
7643                        getSpecifierRange(startSpecifier, specifierLen));
7644 }
7645 
7646 void CheckFormatHandler::HandleInvalidLengthModifier(
7647     const analyze_format_string::FormatSpecifier &FS,
7648     const analyze_format_string::ConversionSpecifier &CS,
7649     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7650   using namespace analyze_format_string;
7651 
7652   const LengthModifier &LM = FS.getLengthModifier();
7653   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7654 
7655   // See if we know how to fix this length modifier.
7656   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7657   if (FixedLM) {
7658     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7659                          getLocationOfByte(LM.getStart()),
7660                          /*IsStringLocation*/true,
7661                          getSpecifierRange(startSpecifier, specifierLen));
7662 
7663     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7664       << FixedLM->toString()
7665       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7666 
7667   } else {
7668     FixItHint Hint;
7669     if (DiagID == diag::warn_format_nonsensical_length)
7670       Hint = FixItHint::CreateRemoval(LMRange);
7671 
7672     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7673                          getLocationOfByte(LM.getStart()),
7674                          /*IsStringLocation*/true,
7675                          getSpecifierRange(startSpecifier, specifierLen),
7676                          Hint);
7677   }
7678 }
7679 
7680 void CheckFormatHandler::HandleNonStandardLengthModifier(
7681     const analyze_format_string::FormatSpecifier &FS,
7682     const char *startSpecifier, unsigned specifierLen) {
7683   using namespace analyze_format_string;
7684 
7685   const LengthModifier &LM = FS.getLengthModifier();
7686   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7687 
7688   // See if we know how to fix this length modifier.
7689   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7690   if (FixedLM) {
7691     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7692                            << LM.toString() << 0,
7693                          getLocationOfByte(LM.getStart()),
7694                          /*IsStringLocation*/true,
7695                          getSpecifierRange(startSpecifier, specifierLen));
7696 
7697     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7698       << FixedLM->toString()
7699       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7700 
7701   } else {
7702     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7703                            << LM.toString() << 0,
7704                          getLocationOfByte(LM.getStart()),
7705                          /*IsStringLocation*/true,
7706                          getSpecifierRange(startSpecifier, specifierLen));
7707   }
7708 }
7709 
7710 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7711     const analyze_format_string::ConversionSpecifier &CS,
7712     const char *startSpecifier, unsigned specifierLen) {
7713   using namespace analyze_format_string;
7714 
7715   // See if we know how to fix this conversion specifier.
7716   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7717   if (FixedCS) {
7718     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7719                           << CS.toString() << /*conversion specifier*/1,
7720                          getLocationOfByte(CS.getStart()),
7721                          /*IsStringLocation*/true,
7722                          getSpecifierRange(startSpecifier, specifierLen));
7723 
7724     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7725     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7726       << FixedCS->toString()
7727       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7728   } else {
7729     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7730                           << CS.toString() << /*conversion specifier*/1,
7731                          getLocationOfByte(CS.getStart()),
7732                          /*IsStringLocation*/true,
7733                          getSpecifierRange(startSpecifier, specifierLen));
7734   }
7735 }
7736 
7737 void CheckFormatHandler::HandlePosition(const char *startPos,
7738                                         unsigned posLen) {
7739   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7740                                getLocationOfByte(startPos),
7741                                /*IsStringLocation*/true,
7742                                getSpecifierRange(startPos, posLen));
7743 }
7744 
7745 void
7746 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7747                                      analyze_format_string::PositionContext p) {
7748   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7749                          << (unsigned) p,
7750                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7751                        getSpecifierRange(startPos, posLen));
7752 }
7753 
7754 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7755                                             unsigned posLen) {
7756   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7757                                getLocationOfByte(startPos),
7758                                /*IsStringLocation*/true,
7759                                getSpecifierRange(startPos, posLen));
7760 }
7761 
7762 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7763   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7764     // The presence of a null character is likely an error.
7765     EmitFormatDiagnostic(
7766       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7767       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7768       getFormatStringRange());
7769   }
7770 }
7771 
7772 // Note that this may return NULL if there was an error parsing or building
7773 // one of the argument expressions.
7774 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7775   return Args[FirstDataArg + i];
7776 }
7777 
7778 void CheckFormatHandler::DoneProcessing() {
7779   // Does the number of data arguments exceed the number of
7780   // format conversions in the format string?
7781   if (!HasVAListArg) {
7782       // Find any arguments that weren't covered.
7783     CoveredArgs.flip();
7784     signed notCoveredArg = CoveredArgs.find_first();
7785     if (notCoveredArg >= 0) {
7786       assert((unsigned)notCoveredArg < NumDataArgs);
7787       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7788     } else {
7789       UncoveredArg.setAllCovered();
7790     }
7791   }
7792 }
7793 
7794 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7795                                    const Expr *ArgExpr) {
7796   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7797          "Invalid state");
7798 
7799   if (!ArgExpr)
7800     return;
7801 
7802   SourceLocation Loc = ArgExpr->getBeginLoc();
7803 
7804   if (S.getSourceManager().isInSystemMacro(Loc))
7805     return;
7806 
7807   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7808   for (auto E : DiagnosticExprs)
7809     PDiag << E->getSourceRange();
7810 
7811   CheckFormatHandler::EmitFormatDiagnostic(
7812                                   S, IsFunctionCall, DiagnosticExprs[0],
7813                                   PDiag, Loc, /*IsStringLocation*/false,
7814                                   DiagnosticExprs[0]->getSourceRange());
7815 }
7816 
7817 bool
7818 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7819                                                      SourceLocation Loc,
7820                                                      const char *startSpec,
7821                                                      unsigned specifierLen,
7822                                                      const char *csStart,
7823                                                      unsigned csLen) {
7824   bool keepGoing = true;
7825   if (argIndex < NumDataArgs) {
7826     // Consider the argument coverered, even though the specifier doesn't
7827     // make sense.
7828     CoveredArgs.set(argIndex);
7829   }
7830   else {
7831     // If argIndex exceeds the number of data arguments we
7832     // don't issue a warning because that is just a cascade of warnings (and
7833     // they may have intended '%%' anyway). We don't want to continue processing
7834     // the format string after this point, however, as we will like just get
7835     // gibberish when trying to match arguments.
7836     keepGoing = false;
7837   }
7838 
7839   StringRef Specifier(csStart, csLen);
7840 
7841   // If the specifier in non-printable, it could be the first byte of a UTF-8
7842   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7843   // hex value.
7844   std::string CodePointStr;
7845   if (!llvm::sys::locale::isPrint(*csStart)) {
7846     llvm::UTF32 CodePoint;
7847     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7848     const llvm::UTF8 *E =
7849         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7850     llvm::ConversionResult Result =
7851         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7852 
7853     if (Result != llvm::conversionOK) {
7854       unsigned char FirstChar = *csStart;
7855       CodePoint = (llvm::UTF32)FirstChar;
7856     }
7857 
7858     llvm::raw_string_ostream OS(CodePointStr);
7859     if (CodePoint < 256)
7860       OS << "\\x" << llvm::format("%02x", CodePoint);
7861     else if (CodePoint <= 0xFFFF)
7862       OS << "\\u" << llvm::format("%04x", CodePoint);
7863     else
7864       OS << "\\U" << llvm::format("%08x", CodePoint);
7865     OS.flush();
7866     Specifier = CodePointStr;
7867   }
7868 
7869   EmitFormatDiagnostic(
7870       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7871       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7872 
7873   return keepGoing;
7874 }
7875 
7876 void
7877 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7878                                                       const char *startSpec,
7879                                                       unsigned specifierLen) {
7880   EmitFormatDiagnostic(
7881     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7882     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7883 }
7884 
7885 bool
7886 CheckFormatHandler::CheckNumArgs(
7887   const analyze_format_string::FormatSpecifier &FS,
7888   const analyze_format_string::ConversionSpecifier &CS,
7889   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7890 
7891   if (argIndex >= NumDataArgs) {
7892     PartialDiagnostic PDiag = FS.usesPositionalArg()
7893       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7894            << (argIndex+1) << NumDataArgs)
7895       : S.PDiag(diag::warn_printf_insufficient_data_args);
7896     EmitFormatDiagnostic(
7897       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7898       getSpecifierRange(startSpecifier, specifierLen));
7899 
7900     // Since more arguments than conversion tokens are given, by extension
7901     // all arguments are covered, so mark this as so.
7902     UncoveredArg.setAllCovered();
7903     return false;
7904   }
7905   return true;
7906 }
7907 
7908 template<typename Range>
7909 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7910                                               SourceLocation Loc,
7911                                               bool IsStringLocation,
7912                                               Range StringRange,
7913                                               ArrayRef<FixItHint> FixIt) {
7914   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7915                        Loc, IsStringLocation, StringRange, FixIt);
7916 }
7917 
7918 /// If the format string is not within the function call, emit a note
7919 /// so that the function call and string are in diagnostic messages.
7920 ///
7921 /// \param InFunctionCall if true, the format string is within the function
7922 /// call and only one diagnostic message will be produced.  Otherwise, an
7923 /// extra note will be emitted pointing to location of the format string.
7924 ///
7925 /// \param ArgumentExpr the expression that is passed as the format string
7926 /// argument in the function call.  Used for getting locations when two
7927 /// diagnostics are emitted.
7928 ///
7929 /// \param PDiag the callee should already have provided any strings for the
7930 /// diagnostic message.  This function only adds locations and fixits
7931 /// to diagnostics.
7932 ///
7933 /// \param Loc primary location for diagnostic.  If two diagnostics are
7934 /// required, one will be at Loc and a new SourceLocation will be created for
7935 /// the other one.
7936 ///
7937 /// \param IsStringLocation if true, Loc points to the format string should be
7938 /// used for the note.  Otherwise, Loc points to the argument list and will
7939 /// be used with PDiag.
7940 ///
7941 /// \param StringRange some or all of the string to highlight.  This is
7942 /// templated so it can accept either a CharSourceRange or a SourceRange.
7943 ///
7944 /// \param FixIt optional fix it hint for the format string.
7945 template <typename Range>
7946 void CheckFormatHandler::EmitFormatDiagnostic(
7947     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7948     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7949     Range StringRange, ArrayRef<FixItHint> FixIt) {
7950   if (InFunctionCall) {
7951     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7952     D << StringRange;
7953     D << FixIt;
7954   } else {
7955     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7956       << ArgumentExpr->getSourceRange();
7957 
7958     const Sema::SemaDiagnosticBuilder &Note =
7959       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7960              diag::note_format_string_defined);
7961 
7962     Note << StringRange;
7963     Note << FixIt;
7964   }
7965 }
7966 
7967 //===--- CHECK: Printf format string checking ------------------------------===//
7968 
7969 namespace {
7970 
7971 class CheckPrintfHandler : public CheckFormatHandler {
7972 public:
7973   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7974                      const Expr *origFormatExpr,
7975                      const Sema::FormatStringType type, unsigned firstDataArg,
7976                      unsigned numDataArgs, bool isObjC, const char *beg,
7977                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7978                      unsigned formatIdx, bool inFunctionCall,
7979                      Sema::VariadicCallType CallType,
7980                      llvm::SmallBitVector &CheckedVarArgs,
7981                      UncoveredArgHandler &UncoveredArg)
7982       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7983                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7984                            inFunctionCall, CallType, CheckedVarArgs,
7985                            UncoveredArg) {}
7986 
7987   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7988 
7989   /// Returns true if '%@' specifiers are allowed in the format string.
7990   bool allowsObjCArg() const {
7991     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7992            FSType == Sema::FST_OSTrace;
7993   }
7994 
7995   bool HandleInvalidPrintfConversionSpecifier(
7996                                       const analyze_printf::PrintfSpecifier &FS,
7997                                       const char *startSpecifier,
7998                                       unsigned specifierLen) override;
7999 
8000   void handleInvalidMaskType(StringRef MaskType) override;
8001 
8002   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8003                              const char *startSpecifier,
8004                              unsigned specifierLen) override;
8005   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8006                        const char *StartSpecifier,
8007                        unsigned SpecifierLen,
8008                        const Expr *E);
8009 
8010   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8011                     const char *startSpecifier, unsigned specifierLen);
8012   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8013                            const analyze_printf::OptionalAmount &Amt,
8014                            unsigned type,
8015                            const char *startSpecifier, unsigned specifierLen);
8016   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8017                   const analyze_printf::OptionalFlag &flag,
8018                   const char *startSpecifier, unsigned specifierLen);
8019   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8020                          const analyze_printf::OptionalFlag &ignoredFlag,
8021                          const analyze_printf::OptionalFlag &flag,
8022                          const char *startSpecifier, unsigned specifierLen);
8023   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8024                            const Expr *E);
8025 
8026   void HandleEmptyObjCModifierFlag(const char *startFlag,
8027                                    unsigned flagLen) override;
8028 
8029   void HandleInvalidObjCModifierFlag(const char *startFlag,
8030                                             unsigned flagLen) override;
8031 
8032   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8033                                            const char *flagsEnd,
8034                                            const char *conversionPosition)
8035                                              override;
8036 };
8037 
8038 } // namespace
8039 
8040 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8041                                       const analyze_printf::PrintfSpecifier &FS,
8042                                       const char *startSpecifier,
8043                                       unsigned specifierLen) {
8044   const analyze_printf::PrintfConversionSpecifier &CS =
8045     FS.getConversionSpecifier();
8046 
8047   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8048                                           getLocationOfByte(CS.getStart()),
8049                                           startSpecifier, specifierLen,
8050                                           CS.getStart(), CS.getLength());
8051 }
8052 
8053 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8054   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8055 }
8056 
8057 bool CheckPrintfHandler::HandleAmount(
8058                                const analyze_format_string::OptionalAmount &Amt,
8059                                unsigned k, const char *startSpecifier,
8060                                unsigned specifierLen) {
8061   if (Amt.hasDataArgument()) {
8062     if (!HasVAListArg) {
8063       unsigned argIndex = Amt.getArgIndex();
8064       if (argIndex >= NumDataArgs) {
8065         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8066                                << k,
8067                              getLocationOfByte(Amt.getStart()),
8068                              /*IsStringLocation*/true,
8069                              getSpecifierRange(startSpecifier, specifierLen));
8070         // Don't do any more checking.  We will just emit
8071         // spurious errors.
8072         return false;
8073       }
8074 
8075       // Type check the data argument.  It should be an 'int'.
8076       // Although not in conformance with C99, we also allow the argument to be
8077       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8078       // doesn't emit a warning for that case.
8079       CoveredArgs.set(argIndex);
8080       const Expr *Arg = getDataArg(argIndex);
8081       if (!Arg)
8082         return false;
8083 
8084       QualType T = Arg->getType();
8085 
8086       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8087       assert(AT.isValid());
8088 
8089       if (!AT.matchesType(S.Context, T)) {
8090         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8091                                << k << AT.getRepresentativeTypeName(S.Context)
8092                                << T << Arg->getSourceRange(),
8093                              getLocationOfByte(Amt.getStart()),
8094                              /*IsStringLocation*/true,
8095                              getSpecifierRange(startSpecifier, specifierLen));
8096         // Don't do any more checking.  We will just emit
8097         // spurious errors.
8098         return false;
8099       }
8100     }
8101   }
8102   return true;
8103 }
8104 
8105 void CheckPrintfHandler::HandleInvalidAmount(
8106                                       const analyze_printf::PrintfSpecifier &FS,
8107                                       const analyze_printf::OptionalAmount &Amt,
8108                                       unsigned type,
8109                                       const char *startSpecifier,
8110                                       unsigned specifierLen) {
8111   const analyze_printf::PrintfConversionSpecifier &CS =
8112     FS.getConversionSpecifier();
8113 
8114   FixItHint fixit =
8115     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8116       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8117                                  Amt.getConstantLength()))
8118       : FixItHint();
8119 
8120   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8121                          << type << CS.toString(),
8122                        getLocationOfByte(Amt.getStart()),
8123                        /*IsStringLocation*/true,
8124                        getSpecifierRange(startSpecifier, specifierLen),
8125                        fixit);
8126 }
8127 
8128 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8129                                     const analyze_printf::OptionalFlag &flag,
8130                                     const char *startSpecifier,
8131                                     unsigned specifierLen) {
8132   // Warn about pointless flag with a fixit removal.
8133   const analyze_printf::PrintfConversionSpecifier &CS =
8134     FS.getConversionSpecifier();
8135   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8136                          << flag.toString() << CS.toString(),
8137                        getLocationOfByte(flag.getPosition()),
8138                        /*IsStringLocation*/true,
8139                        getSpecifierRange(startSpecifier, specifierLen),
8140                        FixItHint::CreateRemoval(
8141                          getSpecifierRange(flag.getPosition(), 1)));
8142 }
8143 
8144 void CheckPrintfHandler::HandleIgnoredFlag(
8145                                 const analyze_printf::PrintfSpecifier &FS,
8146                                 const analyze_printf::OptionalFlag &ignoredFlag,
8147                                 const analyze_printf::OptionalFlag &flag,
8148                                 const char *startSpecifier,
8149                                 unsigned specifierLen) {
8150   // Warn about ignored flag with a fixit removal.
8151   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8152                          << ignoredFlag.toString() << flag.toString(),
8153                        getLocationOfByte(ignoredFlag.getPosition()),
8154                        /*IsStringLocation*/true,
8155                        getSpecifierRange(startSpecifier, specifierLen),
8156                        FixItHint::CreateRemoval(
8157                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8158 }
8159 
8160 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8161                                                      unsigned flagLen) {
8162   // Warn about an empty flag.
8163   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8164                        getLocationOfByte(startFlag),
8165                        /*IsStringLocation*/true,
8166                        getSpecifierRange(startFlag, flagLen));
8167 }
8168 
8169 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8170                                                        unsigned flagLen) {
8171   // Warn about an invalid flag.
8172   auto Range = getSpecifierRange(startFlag, flagLen);
8173   StringRef flag(startFlag, flagLen);
8174   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8175                       getLocationOfByte(startFlag),
8176                       /*IsStringLocation*/true,
8177                       Range, FixItHint::CreateRemoval(Range));
8178 }
8179 
8180 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8181     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8182     // Warn about using '[...]' without a '@' conversion.
8183     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8184     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8185     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8186                          getLocationOfByte(conversionPosition),
8187                          /*IsStringLocation*/true,
8188                          Range, FixItHint::CreateRemoval(Range));
8189 }
8190 
8191 // Determines if the specified is a C++ class or struct containing
8192 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8193 // "c_str()").
8194 template<typename MemberKind>
8195 static llvm::SmallPtrSet<MemberKind*, 1>
8196 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8197   const RecordType *RT = Ty->getAs<RecordType>();
8198   llvm::SmallPtrSet<MemberKind*, 1> Results;
8199 
8200   if (!RT)
8201     return Results;
8202   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8203   if (!RD || !RD->getDefinition())
8204     return Results;
8205 
8206   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8207                  Sema::LookupMemberName);
8208   R.suppressDiagnostics();
8209 
8210   // We just need to include all members of the right kind turned up by the
8211   // filter, at this point.
8212   if (S.LookupQualifiedName(R, RT->getDecl()))
8213     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8214       NamedDecl *decl = (*I)->getUnderlyingDecl();
8215       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8216         Results.insert(FK);
8217     }
8218   return Results;
8219 }
8220 
8221 /// Check if we could call '.c_str()' on an object.
8222 ///
8223 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8224 /// allow the call, or if it would be ambiguous).
8225 bool Sema::hasCStrMethod(const Expr *E) {
8226   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8227 
8228   MethodSet Results =
8229       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8230   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8231        MI != ME; ++MI)
8232     if ((*MI)->getMinRequiredArguments() == 0)
8233       return true;
8234   return false;
8235 }
8236 
8237 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8238 // better diagnostic if so. AT is assumed to be valid.
8239 // Returns true when a c_str() conversion method is found.
8240 bool CheckPrintfHandler::checkForCStrMembers(
8241     const analyze_printf::ArgType &AT, const Expr *E) {
8242   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8243 
8244   MethodSet Results =
8245       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8246 
8247   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8248        MI != ME; ++MI) {
8249     const CXXMethodDecl *Method = *MI;
8250     if (Method->getMinRequiredArguments() == 0 &&
8251         AT.matchesType(S.Context, Method->getReturnType())) {
8252       // FIXME: Suggest parens if the expression needs them.
8253       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8254       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8255           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8256       return true;
8257     }
8258   }
8259 
8260   return false;
8261 }
8262 
8263 bool
8264 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8265                                             &FS,
8266                                           const char *startSpecifier,
8267                                           unsigned specifierLen) {
8268   using namespace analyze_format_string;
8269   using namespace analyze_printf;
8270 
8271   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8272 
8273   if (FS.consumesDataArgument()) {
8274     if (atFirstArg) {
8275         atFirstArg = false;
8276         usesPositionalArgs = FS.usesPositionalArg();
8277     }
8278     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8279       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8280                                         startSpecifier, specifierLen);
8281       return false;
8282     }
8283   }
8284 
8285   // First check if the field width, precision, and conversion specifier
8286   // have matching data arguments.
8287   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8288                     startSpecifier, specifierLen)) {
8289     return false;
8290   }
8291 
8292   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8293                     startSpecifier, specifierLen)) {
8294     return false;
8295   }
8296 
8297   if (!CS.consumesDataArgument()) {
8298     // FIXME: Technically specifying a precision or field width here
8299     // makes no sense.  Worth issuing a warning at some point.
8300     return true;
8301   }
8302 
8303   // Consume the argument.
8304   unsigned argIndex = FS.getArgIndex();
8305   if (argIndex < NumDataArgs) {
8306     // The check to see if the argIndex is valid will come later.
8307     // We set the bit here because we may exit early from this
8308     // function if we encounter some other error.
8309     CoveredArgs.set(argIndex);
8310   }
8311 
8312   // FreeBSD kernel extensions.
8313   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8314       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8315     // We need at least two arguments.
8316     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8317       return false;
8318 
8319     // Claim the second argument.
8320     CoveredArgs.set(argIndex + 1);
8321 
8322     // Type check the first argument (int for %b, pointer for %D)
8323     const Expr *Ex = getDataArg(argIndex);
8324     const analyze_printf::ArgType &AT =
8325       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8326         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8327     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8328       EmitFormatDiagnostic(
8329           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8330               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8331               << false << Ex->getSourceRange(),
8332           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8333           getSpecifierRange(startSpecifier, specifierLen));
8334 
8335     // Type check the second argument (char * for both %b and %D)
8336     Ex = getDataArg(argIndex + 1);
8337     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8338     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8339       EmitFormatDiagnostic(
8340           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8341               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8342               << false << Ex->getSourceRange(),
8343           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8344           getSpecifierRange(startSpecifier, specifierLen));
8345 
8346      return true;
8347   }
8348 
8349   // Check for using an Objective-C specific conversion specifier
8350   // in a non-ObjC literal.
8351   if (!allowsObjCArg() && CS.isObjCArg()) {
8352     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8353                                                   specifierLen);
8354   }
8355 
8356   // %P can only be used with os_log.
8357   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8358     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8359                                                   specifierLen);
8360   }
8361 
8362   // %n is not allowed with os_log.
8363   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8364     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8365                          getLocationOfByte(CS.getStart()),
8366                          /*IsStringLocation*/ false,
8367                          getSpecifierRange(startSpecifier, specifierLen));
8368 
8369     return true;
8370   }
8371 
8372   // Only scalars are allowed for os_trace.
8373   if (FSType == Sema::FST_OSTrace &&
8374       (CS.getKind() == ConversionSpecifier::PArg ||
8375        CS.getKind() == ConversionSpecifier::sArg ||
8376        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8377     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8378                                                   specifierLen);
8379   }
8380 
8381   // Check for use of public/private annotation outside of os_log().
8382   if (FSType != Sema::FST_OSLog) {
8383     if (FS.isPublic().isSet()) {
8384       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8385                                << "public",
8386                            getLocationOfByte(FS.isPublic().getPosition()),
8387                            /*IsStringLocation*/ false,
8388                            getSpecifierRange(startSpecifier, specifierLen));
8389     }
8390     if (FS.isPrivate().isSet()) {
8391       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8392                                << "private",
8393                            getLocationOfByte(FS.isPrivate().getPosition()),
8394                            /*IsStringLocation*/ false,
8395                            getSpecifierRange(startSpecifier, specifierLen));
8396     }
8397   }
8398 
8399   // Check for invalid use of field width
8400   if (!FS.hasValidFieldWidth()) {
8401     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8402         startSpecifier, specifierLen);
8403   }
8404 
8405   // Check for invalid use of precision
8406   if (!FS.hasValidPrecision()) {
8407     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8408         startSpecifier, specifierLen);
8409   }
8410 
8411   // Precision is mandatory for %P specifier.
8412   if (CS.getKind() == ConversionSpecifier::PArg &&
8413       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8414     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8415                          getLocationOfByte(startSpecifier),
8416                          /*IsStringLocation*/ false,
8417                          getSpecifierRange(startSpecifier, specifierLen));
8418   }
8419 
8420   // Check each flag does not conflict with any other component.
8421   if (!FS.hasValidThousandsGroupingPrefix())
8422     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8423   if (!FS.hasValidLeadingZeros())
8424     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8425   if (!FS.hasValidPlusPrefix())
8426     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8427   if (!FS.hasValidSpacePrefix())
8428     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8429   if (!FS.hasValidAlternativeForm())
8430     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8431   if (!FS.hasValidLeftJustified())
8432     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8433 
8434   // Check that flags are not ignored by another flag
8435   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8436     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8437         startSpecifier, specifierLen);
8438   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8439     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8440             startSpecifier, specifierLen);
8441 
8442   // Check the length modifier is valid with the given conversion specifier.
8443   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8444                                  S.getLangOpts()))
8445     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8446                                 diag::warn_format_nonsensical_length);
8447   else if (!FS.hasStandardLengthModifier())
8448     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8449   else if (!FS.hasStandardLengthConversionCombination())
8450     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8451                                 diag::warn_format_non_standard_conversion_spec);
8452 
8453   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8454     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8455 
8456   // The remaining checks depend on the data arguments.
8457   if (HasVAListArg)
8458     return true;
8459 
8460   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8461     return false;
8462 
8463   const Expr *Arg = getDataArg(argIndex);
8464   if (!Arg)
8465     return true;
8466 
8467   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8468 }
8469 
8470 static bool requiresParensToAddCast(const Expr *E) {
8471   // FIXME: We should have a general way to reason about operator
8472   // precedence and whether parens are actually needed here.
8473   // Take care of a few common cases where they aren't.
8474   const Expr *Inside = E->IgnoreImpCasts();
8475   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8476     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8477 
8478   switch (Inside->getStmtClass()) {
8479   case Stmt::ArraySubscriptExprClass:
8480   case Stmt::CallExprClass:
8481   case Stmt::CharacterLiteralClass:
8482   case Stmt::CXXBoolLiteralExprClass:
8483   case Stmt::DeclRefExprClass:
8484   case Stmt::FloatingLiteralClass:
8485   case Stmt::IntegerLiteralClass:
8486   case Stmt::MemberExprClass:
8487   case Stmt::ObjCArrayLiteralClass:
8488   case Stmt::ObjCBoolLiteralExprClass:
8489   case Stmt::ObjCBoxedExprClass:
8490   case Stmt::ObjCDictionaryLiteralClass:
8491   case Stmt::ObjCEncodeExprClass:
8492   case Stmt::ObjCIvarRefExprClass:
8493   case Stmt::ObjCMessageExprClass:
8494   case Stmt::ObjCPropertyRefExprClass:
8495   case Stmt::ObjCStringLiteralClass:
8496   case Stmt::ObjCSubscriptRefExprClass:
8497   case Stmt::ParenExprClass:
8498   case Stmt::StringLiteralClass:
8499   case Stmt::UnaryOperatorClass:
8500     return false;
8501   default:
8502     return true;
8503   }
8504 }
8505 
8506 static std::pair<QualType, StringRef>
8507 shouldNotPrintDirectly(const ASTContext &Context,
8508                        QualType IntendedTy,
8509                        const Expr *E) {
8510   // Use a 'while' to peel off layers of typedefs.
8511   QualType TyTy = IntendedTy;
8512   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8513     StringRef Name = UserTy->getDecl()->getName();
8514     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8515       .Case("CFIndex", Context.getNSIntegerType())
8516       .Case("NSInteger", Context.getNSIntegerType())
8517       .Case("NSUInteger", Context.getNSUIntegerType())
8518       .Case("SInt32", Context.IntTy)
8519       .Case("UInt32", Context.UnsignedIntTy)
8520       .Default(QualType());
8521 
8522     if (!CastTy.isNull())
8523       return std::make_pair(CastTy, Name);
8524 
8525     TyTy = UserTy->desugar();
8526   }
8527 
8528   // Strip parens if necessary.
8529   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8530     return shouldNotPrintDirectly(Context,
8531                                   PE->getSubExpr()->getType(),
8532                                   PE->getSubExpr());
8533 
8534   // If this is a conditional expression, then its result type is constructed
8535   // via usual arithmetic conversions and thus there might be no necessary
8536   // typedef sugar there.  Recurse to operands to check for NSInteger &
8537   // Co. usage condition.
8538   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8539     QualType TrueTy, FalseTy;
8540     StringRef TrueName, FalseName;
8541 
8542     std::tie(TrueTy, TrueName) =
8543       shouldNotPrintDirectly(Context,
8544                              CO->getTrueExpr()->getType(),
8545                              CO->getTrueExpr());
8546     std::tie(FalseTy, FalseName) =
8547       shouldNotPrintDirectly(Context,
8548                              CO->getFalseExpr()->getType(),
8549                              CO->getFalseExpr());
8550 
8551     if (TrueTy == FalseTy)
8552       return std::make_pair(TrueTy, TrueName);
8553     else if (TrueTy.isNull())
8554       return std::make_pair(FalseTy, FalseName);
8555     else if (FalseTy.isNull())
8556       return std::make_pair(TrueTy, TrueName);
8557   }
8558 
8559   return std::make_pair(QualType(), StringRef());
8560 }
8561 
8562 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8563 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8564 /// type do not count.
8565 static bool
8566 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8567   QualType From = ICE->getSubExpr()->getType();
8568   QualType To = ICE->getType();
8569   // It's an integer promotion if the destination type is the promoted
8570   // source type.
8571   if (ICE->getCastKind() == CK_IntegralCast &&
8572       From->isPromotableIntegerType() &&
8573       S.Context.getPromotedIntegerType(From) == To)
8574     return true;
8575   // Look through vector types, since we do default argument promotion for
8576   // those in OpenCL.
8577   if (const auto *VecTy = From->getAs<ExtVectorType>())
8578     From = VecTy->getElementType();
8579   if (const auto *VecTy = To->getAs<ExtVectorType>())
8580     To = VecTy->getElementType();
8581   // It's a floating promotion if the source type is a lower rank.
8582   return ICE->getCastKind() == CK_FloatingCast &&
8583          S.Context.getFloatingTypeOrder(From, To) < 0;
8584 }
8585 
8586 bool
8587 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8588                                     const char *StartSpecifier,
8589                                     unsigned SpecifierLen,
8590                                     const Expr *E) {
8591   using namespace analyze_format_string;
8592   using namespace analyze_printf;
8593 
8594   // Now type check the data expression that matches the
8595   // format specifier.
8596   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8597   if (!AT.isValid())
8598     return true;
8599 
8600   QualType ExprTy = E->getType();
8601   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8602     ExprTy = TET->getUnderlyingExpr()->getType();
8603   }
8604 
8605   // Diagnose attempts to print a boolean value as a character. Unlike other
8606   // -Wformat diagnostics, this is fine from a type perspective, but it still
8607   // doesn't make sense.
8608   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8609       E->isKnownToHaveBooleanValue()) {
8610     const CharSourceRange &CSR =
8611         getSpecifierRange(StartSpecifier, SpecifierLen);
8612     SmallString<4> FSString;
8613     llvm::raw_svector_ostream os(FSString);
8614     FS.toString(os);
8615     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8616                              << FSString,
8617                          E->getExprLoc(), false, CSR);
8618     return true;
8619   }
8620 
8621   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8622   if (Match == analyze_printf::ArgType::Match)
8623     return true;
8624 
8625   // Look through argument promotions for our error message's reported type.
8626   // This includes the integral and floating promotions, but excludes array
8627   // and function pointer decay (seeing that an argument intended to be a
8628   // string has type 'char [6]' is probably more confusing than 'char *') and
8629   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8630   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8631     if (isArithmeticArgumentPromotion(S, ICE)) {
8632       E = ICE->getSubExpr();
8633       ExprTy = E->getType();
8634 
8635       // Check if we didn't match because of an implicit cast from a 'char'
8636       // or 'short' to an 'int'.  This is done because printf is a varargs
8637       // function.
8638       if (ICE->getType() == S.Context.IntTy ||
8639           ICE->getType() == S.Context.UnsignedIntTy) {
8640         // All further checking is done on the subexpression
8641         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8642             AT.matchesType(S.Context, ExprTy);
8643         if (ImplicitMatch == analyze_printf::ArgType::Match)
8644           return true;
8645         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8646             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8647           Match = ImplicitMatch;
8648       }
8649     }
8650   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8651     // Special case for 'a', which has type 'int' in C.
8652     // Note, however, that we do /not/ want to treat multibyte constants like
8653     // 'MooV' as characters! This form is deprecated but still exists.
8654     if (ExprTy == S.Context.IntTy)
8655       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8656         ExprTy = S.Context.CharTy;
8657   }
8658 
8659   // Look through enums to their underlying type.
8660   bool IsEnum = false;
8661   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8662     ExprTy = EnumTy->getDecl()->getIntegerType();
8663     IsEnum = true;
8664   }
8665 
8666   // %C in an Objective-C context prints a unichar, not a wchar_t.
8667   // If the argument is an integer of some kind, believe the %C and suggest
8668   // a cast instead of changing the conversion specifier.
8669   QualType IntendedTy = ExprTy;
8670   if (isObjCContext() &&
8671       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8672     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8673         !ExprTy->isCharType()) {
8674       // 'unichar' is defined as a typedef of unsigned short, but we should
8675       // prefer using the typedef if it is visible.
8676       IntendedTy = S.Context.UnsignedShortTy;
8677 
8678       // While we are here, check if the value is an IntegerLiteral that happens
8679       // to be within the valid range.
8680       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8681         const llvm::APInt &V = IL->getValue();
8682         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8683           return true;
8684       }
8685 
8686       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8687                           Sema::LookupOrdinaryName);
8688       if (S.LookupName(Result, S.getCurScope())) {
8689         NamedDecl *ND = Result.getFoundDecl();
8690         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8691           if (TD->getUnderlyingType() == IntendedTy)
8692             IntendedTy = S.Context.getTypedefType(TD);
8693       }
8694     }
8695   }
8696 
8697   // Special-case some of Darwin's platform-independence types by suggesting
8698   // casts to primitive types that are known to be large enough.
8699   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8700   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8701     QualType CastTy;
8702     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8703     if (!CastTy.isNull()) {
8704       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8705       // (long in ASTContext). Only complain to pedants.
8706       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8707           (AT.isSizeT() || AT.isPtrdiffT()) &&
8708           AT.matchesType(S.Context, CastTy))
8709         Match = ArgType::NoMatchPedantic;
8710       IntendedTy = CastTy;
8711       ShouldNotPrintDirectly = true;
8712     }
8713   }
8714 
8715   // We may be able to offer a FixItHint if it is a supported type.
8716   PrintfSpecifier fixedFS = FS;
8717   bool Success =
8718       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8719 
8720   if (Success) {
8721     // Get the fix string from the fixed format specifier
8722     SmallString<16> buf;
8723     llvm::raw_svector_ostream os(buf);
8724     fixedFS.toString(os);
8725 
8726     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8727 
8728     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8729       unsigned Diag;
8730       switch (Match) {
8731       case ArgType::Match: llvm_unreachable("expected non-matching");
8732       case ArgType::NoMatchPedantic:
8733         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8734         break;
8735       case ArgType::NoMatchTypeConfusion:
8736         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8737         break;
8738       case ArgType::NoMatch:
8739         Diag = diag::warn_format_conversion_argument_type_mismatch;
8740         break;
8741       }
8742 
8743       // In this case, the specifier is wrong and should be changed to match
8744       // the argument.
8745       EmitFormatDiagnostic(S.PDiag(Diag)
8746                                << AT.getRepresentativeTypeName(S.Context)
8747                                << IntendedTy << IsEnum << E->getSourceRange(),
8748                            E->getBeginLoc(),
8749                            /*IsStringLocation*/ false, SpecRange,
8750                            FixItHint::CreateReplacement(SpecRange, os.str()));
8751     } else {
8752       // The canonical type for formatting this value is different from the
8753       // actual type of the expression. (This occurs, for example, with Darwin's
8754       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8755       // should be printed as 'long' for 64-bit compatibility.)
8756       // Rather than emitting a normal format/argument mismatch, we want to
8757       // add a cast to the recommended type (and correct the format string
8758       // if necessary).
8759       SmallString<16> CastBuf;
8760       llvm::raw_svector_ostream CastFix(CastBuf);
8761       CastFix << "(";
8762       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8763       CastFix << ")";
8764 
8765       SmallVector<FixItHint,4> Hints;
8766       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8767         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8768 
8769       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8770         // If there's already a cast present, just replace it.
8771         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8772         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8773 
8774       } else if (!requiresParensToAddCast(E)) {
8775         // If the expression has high enough precedence,
8776         // just write the C-style cast.
8777         Hints.push_back(
8778             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8779       } else {
8780         // Otherwise, add parens around the expression as well as the cast.
8781         CastFix << "(";
8782         Hints.push_back(
8783             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8784 
8785         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8786         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8787       }
8788 
8789       if (ShouldNotPrintDirectly) {
8790         // The expression has a type that should not be printed directly.
8791         // We extract the name from the typedef because we don't want to show
8792         // the underlying type in the diagnostic.
8793         StringRef Name;
8794         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8795           Name = TypedefTy->getDecl()->getName();
8796         else
8797           Name = CastTyName;
8798         unsigned Diag = Match == ArgType::NoMatchPedantic
8799                             ? diag::warn_format_argument_needs_cast_pedantic
8800                             : diag::warn_format_argument_needs_cast;
8801         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8802                                            << E->getSourceRange(),
8803                              E->getBeginLoc(), /*IsStringLocation=*/false,
8804                              SpecRange, Hints);
8805       } else {
8806         // In this case, the expression could be printed using a different
8807         // specifier, but we've decided that the specifier is probably correct
8808         // and we should cast instead. Just use the normal warning message.
8809         EmitFormatDiagnostic(
8810             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8811                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8812                 << E->getSourceRange(),
8813             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8814       }
8815     }
8816   } else {
8817     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8818                                                    SpecifierLen);
8819     // Since the warning for passing non-POD types to variadic functions
8820     // was deferred until now, we emit a warning for non-POD
8821     // arguments here.
8822     switch (S.isValidVarArgType(ExprTy)) {
8823     case Sema::VAK_Valid:
8824     case Sema::VAK_ValidInCXX11: {
8825       unsigned Diag;
8826       switch (Match) {
8827       case ArgType::Match: llvm_unreachable("expected non-matching");
8828       case ArgType::NoMatchPedantic:
8829         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8830         break;
8831       case ArgType::NoMatchTypeConfusion:
8832         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8833         break;
8834       case ArgType::NoMatch:
8835         Diag = diag::warn_format_conversion_argument_type_mismatch;
8836         break;
8837       }
8838 
8839       EmitFormatDiagnostic(
8840           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8841                         << IsEnum << CSR << E->getSourceRange(),
8842           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8843       break;
8844     }
8845     case Sema::VAK_Undefined:
8846     case Sema::VAK_MSVCUndefined:
8847       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8848                                << S.getLangOpts().CPlusPlus11 << ExprTy
8849                                << CallType
8850                                << AT.getRepresentativeTypeName(S.Context) << CSR
8851                                << E->getSourceRange(),
8852                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8853       checkForCStrMembers(AT, E);
8854       break;
8855 
8856     case Sema::VAK_Invalid:
8857       if (ExprTy->isObjCObjectType())
8858         EmitFormatDiagnostic(
8859             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8860                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8861                 << AT.getRepresentativeTypeName(S.Context) << CSR
8862                 << E->getSourceRange(),
8863             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8864       else
8865         // FIXME: If this is an initializer list, suggest removing the braces
8866         // or inserting a cast to the target type.
8867         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8868             << isa<InitListExpr>(E) << ExprTy << CallType
8869             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8870       break;
8871     }
8872 
8873     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8874            "format string specifier index out of range");
8875     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8876   }
8877 
8878   return true;
8879 }
8880 
8881 //===--- CHECK: Scanf format string checking ------------------------------===//
8882 
8883 namespace {
8884 
8885 class CheckScanfHandler : public CheckFormatHandler {
8886 public:
8887   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8888                     const Expr *origFormatExpr, Sema::FormatStringType type,
8889                     unsigned firstDataArg, unsigned numDataArgs,
8890                     const char *beg, bool hasVAListArg,
8891                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8892                     bool inFunctionCall, Sema::VariadicCallType CallType,
8893                     llvm::SmallBitVector &CheckedVarArgs,
8894                     UncoveredArgHandler &UncoveredArg)
8895       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8896                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8897                            inFunctionCall, CallType, CheckedVarArgs,
8898                            UncoveredArg) {}
8899 
8900   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8901                             const char *startSpecifier,
8902                             unsigned specifierLen) override;
8903 
8904   bool HandleInvalidScanfConversionSpecifier(
8905           const analyze_scanf::ScanfSpecifier &FS,
8906           const char *startSpecifier,
8907           unsigned specifierLen) override;
8908 
8909   void HandleIncompleteScanList(const char *start, const char *end) override;
8910 };
8911 
8912 } // namespace
8913 
8914 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8915                                                  const char *end) {
8916   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8917                        getLocationOfByte(end), /*IsStringLocation*/true,
8918                        getSpecifierRange(start, end - start));
8919 }
8920 
8921 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8922                                         const analyze_scanf::ScanfSpecifier &FS,
8923                                         const char *startSpecifier,
8924                                         unsigned specifierLen) {
8925   const analyze_scanf::ScanfConversionSpecifier &CS =
8926     FS.getConversionSpecifier();
8927 
8928   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8929                                           getLocationOfByte(CS.getStart()),
8930                                           startSpecifier, specifierLen,
8931                                           CS.getStart(), CS.getLength());
8932 }
8933 
8934 bool CheckScanfHandler::HandleScanfSpecifier(
8935                                        const analyze_scanf::ScanfSpecifier &FS,
8936                                        const char *startSpecifier,
8937                                        unsigned specifierLen) {
8938   using namespace analyze_scanf;
8939   using namespace analyze_format_string;
8940 
8941   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8942 
8943   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8944   // be used to decide if we are using positional arguments consistently.
8945   if (FS.consumesDataArgument()) {
8946     if (atFirstArg) {
8947       atFirstArg = false;
8948       usesPositionalArgs = FS.usesPositionalArg();
8949     }
8950     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8951       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8952                                         startSpecifier, specifierLen);
8953       return false;
8954     }
8955   }
8956 
8957   // Check if the field with is non-zero.
8958   const OptionalAmount &Amt = FS.getFieldWidth();
8959   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8960     if (Amt.getConstantAmount() == 0) {
8961       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8962                                                    Amt.getConstantLength());
8963       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8964                            getLocationOfByte(Amt.getStart()),
8965                            /*IsStringLocation*/true, R,
8966                            FixItHint::CreateRemoval(R));
8967     }
8968   }
8969 
8970   if (!FS.consumesDataArgument()) {
8971     // FIXME: Technically specifying a precision or field width here
8972     // makes no sense.  Worth issuing a warning at some point.
8973     return true;
8974   }
8975 
8976   // Consume the argument.
8977   unsigned argIndex = FS.getArgIndex();
8978   if (argIndex < NumDataArgs) {
8979       // The check to see if the argIndex is valid will come later.
8980       // We set the bit here because we may exit early from this
8981       // function if we encounter some other error.
8982     CoveredArgs.set(argIndex);
8983   }
8984 
8985   // Check the length modifier is valid with the given conversion specifier.
8986   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8987                                  S.getLangOpts()))
8988     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8989                                 diag::warn_format_nonsensical_length);
8990   else if (!FS.hasStandardLengthModifier())
8991     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8992   else if (!FS.hasStandardLengthConversionCombination())
8993     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8994                                 diag::warn_format_non_standard_conversion_spec);
8995 
8996   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8997     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8998 
8999   // The remaining checks depend on the data arguments.
9000   if (HasVAListArg)
9001     return true;
9002 
9003   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9004     return false;
9005 
9006   // Check that the argument type matches the format specifier.
9007   const Expr *Ex = getDataArg(argIndex);
9008   if (!Ex)
9009     return true;
9010 
9011   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9012 
9013   if (!AT.isValid()) {
9014     return true;
9015   }
9016 
9017   analyze_format_string::ArgType::MatchKind Match =
9018       AT.matchesType(S.Context, Ex->getType());
9019   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9020   if (Match == analyze_format_string::ArgType::Match)
9021     return true;
9022 
9023   ScanfSpecifier fixedFS = FS;
9024   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9025                                  S.getLangOpts(), S.Context);
9026 
9027   unsigned Diag =
9028       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9029                : diag::warn_format_conversion_argument_type_mismatch;
9030 
9031   if (Success) {
9032     // Get the fix string from the fixed format specifier.
9033     SmallString<128> buf;
9034     llvm::raw_svector_ostream os(buf);
9035     fixedFS.toString(os);
9036 
9037     EmitFormatDiagnostic(
9038         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9039                       << Ex->getType() << false << Ex->getSourceRange(),
9040         Ex->getBeginLoc(),
9041         /*IsStringLocation*/ false,
9042         getSpecifierRange(startSpecifier, specifierLen),
9043         FixItHint::CreateReplacement(
9044             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9045   } else {
9046     EmitFormatDiagnostic(S.PDiag(Diag)
9047                              << AT.getRepresentativeTypeName(S.Context)
9048                              << Ex->getType() << false << Ex->getSourceRange(),
9049                          Ex->getBeginLoc(),
9050                          /*IsStringLocation*/ false,
9051                          getSpecifierRange(startSpecifier, specifierLen));
9052   }
9053 
9054   return true;
9055 }
9056 
9057 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9058                               const Expr *OrigFormatExpr,
9059                               ArrayRef<const Expr *> Args,
9060                               bool HasVAListArg, unsigned format_idx,
9061                               unsigned firstDataArg,
9062                               Sema::FormatStringType Type,
9063                               bool inFunctionCall,
9064                               Sema::VariadicCallType CallType,
9065                               llvm::SmallBitVector &CheckedVarArgs,
9066                               UncoveredArgHandler &UncoveredArg,
9067                               bool IgnoreStringsWithoutSpecifiers) {
9068   // CHECK: is the format string a wide literal?
9069   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9070     CheckFormatHandler::EmitFormatDiagnostic(
9071         S, inFunctionCall, Args[format_idx],
9072         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9073         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9074     return;
9075   }
9076 
9077   // Str - The format string.  NOTE: this is NOT null-terminated!
9078   StringRef StrRef = FExpr->getString();
9079   const char *Str = StrRef.data();
9080   // Account for cases where the string literal is truncated in a declaration.
9081   const ConstantArrayType *T =
9082     S.Context.getAsConstantArrayType(FExpr->getType());
9083   assert(T && "String literal not of constant array type!");
9084   size_t TypeSize = T->getSize().getZExtValue();
9085   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9086   const unsigned numDataArgs = Args.size() - firstDataArg;
9087 
9088   if (IgnoreStringsWithoutSpecifiers &&
9089       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9090           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9091     return;
9092 
9093   // Emit a warning if the string literal is truncated and does not contain an
9094   // embedded null character.
9095   if (TypeSize <= StrRef.size() &&
9096       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9097     CheckFormatHandler::EmitFormatDiagnostic(
9098         S, inFunctionCall, Args[format_idx],
9099         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9100         FExpr->getBeginLoc(),
9101         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9102     return;
9103   }
9104 
9105   // CHECK: empty format string?
9106   if (StrLen == 0 && numDataArgs > 0) {
9107     CheckFormatHandler::EmitFormatDiagnostic(
9108         S, inFunctionCall, Args[format_idx],
9109         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9110         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9111     return;
9112   }
9113 
9114   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9115       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9116       Type == Sema::FST_OSTrace) {
9117     CheckPrintfHandler H(
9118         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9119         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9120         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9121         CheckedVarArgs, UncoveredArg);
9122 
9123     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9124                                                   S.getLangOpts(),
9125                                                   S.Context.getTargetInfo(),
9126                                             Type == Sema::FST_FreeBSDKPrintf))
9127       H.DoneProcessing();
9128   } else if (Type == Sema::FST_Scanf) {
9129     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9130                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9131                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9132 
9133     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9134                                                  S.getLangOpts(),
9135                                                  S.Context.getTargetInfo()))
9136       H.DoneProcessing();
9137   } // TODO: handle other formats
9138 }
9139 
9140 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9141   // Str - The format string.  NOTE: this is NOT null-terminated!
9142   StringRef StrRef = FExpr->getString();
9143   const char *Str = StrRef.data();
9144   // Account for cases where the string literal is truncated in a declaration.
9145   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9146   assert(T && "String literal not of constant array type!");
9147   size_t TypeSize = T->getSize().getZExtValue();
9148   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9149   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9150                                                          getLangOpts(),
9151                                                          Context.getTargetInfo());
9152 }
9153 
9154 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9155 
9156 // Returns the related absolute value function that is larger, of 0 if one
9157 // does not exist.
9158 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9159   switch (AbsFunction) {
9160   default:
9161     return 0;
9162 
9163   case Builtin::BI__builtin_abs:
9164     return Builtin::BI__builtin_labs;
9165   case Builtin::BI__builtin_labs:
9166     return Builtin::BI__builtin_llabs;
9167   case Builtin::BI__builtin_llabs:
9168     return 0;
9169 
9170   case Builtin::BI__builtin_fabsf:
9171     return Builtin::BI__builtin_fabs;
9172   case Builtin::BI__builtin_fabs:
9173     return Builtin::BI__builtin_fabsl;
9174   case Builtin::BI__builtin_fabsl:
9175     return 0;
9176 
9177   case Builtin::BI__builtin_cabsf:
9178     return Builtin::BI__builtin_cabs;
9179   case Builtin::BI__builtin_cabs:
9180     return Builtin::BI__builtin_cabsl;
9181   case Builtin::BI__builtin_cabsl:
9182     return 0;
9183 
9184   case Builtin::BIabs:
9185     return Builtin::BIlabs;
9186   case Builtin::BIlabs:
9187     return Builtin::BIllabs;
9188   case Builtin::BIllabs:
9189     return 0;
9190 
9191   case Builtin::BIfabsf:
9192     return Builtin::BIfabs;
9193   case Builtin::BIfabs:
9194     return Builtin::BIfabsl;
9195   case Builtin::BIfabsl:
9196     return 0;
9197 
9198   case Builtin::BIcabsf:
9199    return Builtin::BIcabs;
9200   case Builtin::BIcabs:
9201     return Builtin::BIcabsl;
9202   case Builtin::BIcabsl:
9203     return 0;
9204   }
9205 }
9206 
9207 // Returns the argument type of the absolute value function.
9208 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9209                                              unsigned AbsType) {
9210   if (AbsType == 0)
9211     return QualType();
9212 
9213   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9214   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9215   if (Error != ASTContext::GE_None)
9216     return QualType();
9217 
9218   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9219   if (!FT)
9220     return QualType();
9221 
9222   if (FT->getNumParams() != 1)
9223     return QualType();
9224 
9225   return FT->getParamType(0);
9226 }
9227 
9228 // Returns the best absolute value function, or zero, based on type and
9229 // current absolute value function.
9230 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9231                                    unsigned AbsFunctionKind) {
9232   unsigned BestKind = 0;
9233   uint64_t ArgSize = Context.getTypeSize(ArgType);
9234   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9235        Kind = getLargerAbsoluteValueFunction(Kind)) {
9236     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9237     if (Context.getTypeSize(ParamType) >= ArgSize) {
9238       if (BestKind == 0)
9239         BestKind = Kind;
9240       else if (Context.hasSameType(ParamType, ArgType)) {
9241         BestKind = Kind;
9242         break;
9243       }
9244     }
9245   }
9246   return BestKind;
9247 }
9248 
9249 enum AbsoluteValueKind {
9250   AVK_Integer,
9251   AVK_Floating,
9252   AVK_Complex
9253 };
9254 
9255 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9256   if (T->isIntegralOrEnumerationType())
9257     return AVK_Integer;
9258   if (T->isRealFloatingType())
9259     return AVK_Floating;
9260   if (T->isAnyComplexType())
9261     return AVK_Complex;
9262 
9263   llvm_unreachable("Type not integer, floating, or complex");
9264 }
9265 
9266 // Changes the absolute value function to a different type.  Preserves whether
9267 // the function is a builtin.
9268 static unsigned changeAbsFunction(unsigned AbsKind,
9269                                   AbsoluteValueKind ValueKind) {
9270   switch (ValueKind) {
9271   case AVK_Integer:
9272     switch (AbsKind) {
9273     default:
9274       return 0;
9275     case Builtin::BI__builtin_fabsf:
9276     case Builtin::BI__builtin_fabs:
9277     case Builtin::BI__builtin_fabsl:
9278     case Builtin::BI__builtin_cabsf:
9279     case Builtin::BI__builtin_cabs:
9280     case Builtin::BI__builtin_cabsl:
9281       return Builtin::BI__builtin_abs;
9282     case Builtin::BIfabsf:
9283     case Builtin::BIfabs:
9284     case Builtin::BIfabsl:
9285     case Builtin::BIcabsf:
9286     case Builtin::BIcabs:
9287     case Builtin::BIcabsl:
9288       return Builtin::BIabs;
9289     }
9290   case AVK_Floating:
9291     switch (AbsKind) {
9292     default:
9293       return 0;
9294     case Builtin::BI__builtin_abs:
9295     case Builtin::BI__builtin_labs:
9296     case Builtin::BI__builtin_llabs:
9297     case Builtin::BI__builtin_cabsf:
9298     case Builtin::BI__builtin_cabs:
9299     case Builtin::BI__builtin_cabsl:
9300       return Builtin::BI__builtin_fabsf;
9301     case Builtin::BIabs:
9302     case Builtin::BIlabs:
9303     case Builtin::BIllabs:
9304     case Builtin::BIcabsf:
9305     case Builtin::BIcabs:
9306     case Builtin::BIcabsl:
9307       return Builtin::BIfabsf;
9308     }
9309   case AVK_Complex:
9310     switch (AbsKind) {
9311     default:
9312       return 0;
9313     case Builtin::BI__builtin_abs:
9314     case Builtin::BI__builtin_labs:
9315     case Builtin::BI__builtin_llabs:
9316     case Builtin::BI__builtin_fabsf:
9317     case Builtin::BI__builtin_fabs:
9318     case Builtin::BI__builtin_fabsl:
9319       return Builtin::BI__builtin_cabsf;
9320     case Builtin::BIabs:
9321     case Builtin::BIlabs:
9322     case Builtin::BIllabs:
9323     case Builtin::BIfabsf:
9324     case Builtin::BIfabs:
9325     case Builtin::BIfabsl:
9326       return Builtin::BIcabsf;
9327     }
9328   }
9329   llvm_unreachable("Unable to convert function");
9330 }
9331 
9332 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9333   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9334   if (!FnInfo)
9335     return 0;
9336 
9337   switch (FDecl->getBuiltinID()) {
9338   default:
9339     return 0;
9340   case Builtin::BI__builtin_abs:
9341   case Builtin::BI__builtin_fabs:
9342   case Builtin::BI__builtin_fabsf:
9343   case Builtin::BI__builtin_fabsl:
9344   case Builtin::BI__builtin_labs:
9345   case Builtin::BI__builtin_llabs:
9346   case Builtin::BI__builtin_cabs:
9347   case Builtin::BI__builtin_cabsf:
9348   case Builtin::BI__builtin_cabsl:
9349   case Builtin::BIabs:
9350   case Builtin::BIlabs:
9351   case Builtin::BIllabs:
9352   case Builtin::BIfabs:
9353   case Builtin::BIfabsf:
9354   case Builtin::BIfabsl:
9355   case Builtin::BIcabs:
9356   case Builtin::BIcabsf:
9357   case Builtin::BIcabsl:
9358     return FDecl->getBuiltinID();
9359   }
9360   llvm_unreachable("Unknown Builtin type");
9361 }
9362 
9363 // If the replacement is valid, emit a note with replacement function.
9364 // Additionally, suggest including the proper header if not already included.
9365 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9366                             unsigned AbsKind, QualType ArgType) {
9367   bool EmitHeaderHint = true;
9368   const char *HeaderName = nullptr;
9369   const char *FunctionName = nullptr;
9370   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9371     FunctionName = "std::abs";
9372     if (ArgType->isIntegralOrEnumerationType()) {
9373       HeaderName = "cstdlib";
9374     } else if (ArgType->isRealFloatingType()) {
9375       HeaderName = "cmath";
9376     } else {
9377       llvm_unreachable("Invalid Type");
9378     }
9379 
9380     // Lookup all std::abs
9381     if (NamespaceDecl *Std = S.getStdNamespace()) {
9382       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9383       R.suppressDiagnostics();
9384       S.LookupQualifiedName(R, Std);
9385 
9386       for (const auto *I : R) {
9387         const FunctionDecl *FDecl = nullptr;
9388         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9389           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9390         } else {
9391           FDecl = dyn_cast<FunctionDecl>(I);
9392         }
9393         if (!FDecl)
9394           continue;
9395 
9396         // Found std::abs(), check that they are the right ones.
9397         if (FDecl->getNumParams() != 1)
9398           continue;
9399 
9400         // Check that the parameter type can handle the argument.
9401         QualType ParamType = FDecl->getParamDecl(0)->getType();
9402         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9403             S.Context.getTypeSize(ArgType) <=
9404                 S.Context.getTypeSize(ParamType)) {
9405           // Found a function, don't need the header hint.
9406           EmitHeaderHint = false;
9407           break;
9408         }
9409       }
9410     }
9411   } else {
9412     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9413     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9414 
9415     if (HeaderName) {
9416       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9417       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9418       R.suppressDiagnostics();
9419       S.LookupName(R, S.getCurScope());
9420 
9421       if (R.isSingleResult()) {
9422         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9423         if (FD && FD->getBuiltinID() == AbsKind) {
9424           EmitHeaderHint = false;
9425         } else {
9426           return;
9427         }
9428       } else if (!R.empty()) {
9429         return;
9430       }
9431     }
9432   }
9433 
9434   S.Diag(Loc, diag::note_replace_abs_function)
9435       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9436 
9437   if (!HeaderName)
9438     return;
9439 
9440   if (!EmitHeaderHint)
9441     return;
9442 
9443   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9444                                                     << FunctionName;
9445 }
9446 
9447 template <std::size_t StrLen>
9448 static bool IsStdFunction(const FunctionDecl *FDecl,
9449                           const char (&Str)[StrLen]) {
9450   if (!FDecl)
9451     return false;
9452   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9453     return false;
9454   if (!FDecl->isInStdNamespace())
9455     return false;
9456 
9457   return true;
9458 }
9459 
9460 // Warn when using the wrong abs() function.
9461 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9462                                       const FunctionDecl *FDecl) {
9463   if (Call->getNumArgs() != 1)
9464     return;
9465 
9466   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9467   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9468   if (AbsKind == 0 && !IsStdAbs)
9469     return;
9470 
9471   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9472   QualType ParamType = Call->getArg(0)->getType();
9473 
9474   // Unsigned types cannot be negative.  Suggest removing the absolute value
9475   // function call.
9476   if (ArgType->isUnsignedIntegerType()) {
9477     const char *FunctionName =
9478         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9479     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9480     Diag(Call->getExprLoc(), diag::note_remove_abs)
9481         << FunctionName
9482         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9483     return;
9484   }
9485 
9486   // Taking the absolute value of a pointer is very suspicious, they probably
9487   // wanted to index into an array, dereference a pointer, call a function, etc.
9488   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9489     unsigned DiagType = 0;
9490     if (ArgType->isFunctionType())
9491       DiagType = 1;
9492     else if (ArgType->isArrayType())
9493       DiagType = 2;
9494 
9495     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9496     return;
9497   }
9498 
9499   // std::abs has overloads which prevent most of the absolute value problems
9500   // from occurring.
9501   if (IsStdAbs)
9502     return;
9503 
9504   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9505   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9506 
9507   // The argument and parameter are the same kind.  Check if they are the right
9508   // size.
9509   if (ArgValueKind == ParamValueKind) {
9510     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9511       return;
9512 
9513     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9514     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9515         << FDecl << ArgType << ParamType;
9516 
9517     if (NewAbsKind == 0)
9518       return;
9519 
9520     emitReplacement(*this, Call->getExprLoc(),
9521                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9522     return;
9523   }
9524 
9525   // ArgValueKind != ParamValueKind
9526   // The wrong type of absolute value function was used.  Attempt to find the
9527   // proper one.
9528   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9529   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9530   if (NewAbsKind == 0)
9531     return;
9532 
9533   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9534       << FDecl << ParamValueKind << ArgValueKind;
9535 
9536   emitReplacement(*this, Call->getExprLoc(),
9537                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9538 }
9539 
9540 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9541 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9542                                 const FunctionDecl *FDecl) {
9543   if (!Call || !FDecl) return;
9544 
9545   // Ignore template specializations and macros.
9546   if (inTemplateInstantiation()) return;
9547   if (Call->getExprLoc().isMacroID()) return;
9548 
9549   // Only care about the one template argument, two function parameter std::max
9550   if (Call->getNumArgs() != 2) return;
9551   if (!IsStdFunction(FDecl, "max")) return;
9552   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9553   if (!ArgList) return;
9554   if (ArgList->size() != 1) return;
9555 
9556   // Check that template type argument is unsigned integer.
9557   const auto& TA = ArgList->get(0);
9558   if (TA.getKind() != TemplateArgument::Type) return;
9559   QualType ArgType = TA.getAsType();
9560   if (!ArgType->isUnsignedIntegerType()) return;
9561 
9562   // See if either argument is a literal zero.
9563   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9564     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9565     if (!MTE) return false;
9566     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9567     if (!Num) return false;
9568     if (Num->getValue() != 0) return false;
9569     return true;
9570   };
9571 
9572   const Expr *FirstArg = Call->getArg(0);
9573   const Expr *SecondArg = Call->getArg(1);
9574   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9575   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9576 
9577   // Only warn when exactly one argument is zero.
9578   if (IsFirstArgZero == IsSecondArgZero) return;
9579 
9580   SourceRange FirstRange = FirstArg->getSourceRange();
9581   SourceRange SecondRange = SecondArg->getSourceRange();
9582 
9583   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9584 
9585   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9586       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9587 
9588   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9589   SourceRange RemovalRange;
9590   if (IsFirstArgZero) {
9591     RemovalRange = SourceRange(FirstRange.getBegin(),
9592                                SecondRange.getBegin().getLocWithOffset(-1));
9593   } else {
9594     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9595                                SecondRange.getEnd());
9596   }
9597 
9598   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9599         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9600         << FixItHint::CreateRemoval(RemovalRange);
9601 }
9602 
9603 //===--- CHECK: Standard memory functions ---------------------------------===//
9604 
9605 /// Takes the expression passed to the size_t parameter of functions
9606 /// such as memcmp, strncat, etc and warns if it's a comparison.
9607 ///
9608 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9609 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9610                                            IdentifierInfo *FnName,
9611                                            SourceLocation FnLoc,
9612                                            SourceLocation RParenLoc) {
9613   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9614   if (!Size)
9615     return false;
9616 
9617   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9618   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9619     return false;
9620 
9621   SourceRange SizeRange = Size->getSourceRange();
9622   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9623       << SizeRange << FnName;
9624   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9625       << FnName
9626       << FixItHint::CreateInsertion(
9627              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9628       << FixItHint::CreateRemoval(RParenLoc);
9629   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9630       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9631       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9632                                     ")");
9633 
9634   return true;
9635 }
9636 
9637 /// Determine whether the given type is or contains a dynamic class type
9638 /// (e.g., whether it has a vtable).
9639 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9640                                                      bool &IsContained) {
9641   // Look through array types while ignoring qualifiers.
9642   const Type *Ty = T->getBaseElementTypeUnsafe();
9643   IsContained = false;
9644 
9645   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9646   RD = RD ? RD->getDefinition() : nullptr;
9647   if (!RD || RD->isInvalidDecl())
9648     return nullptr;
9649 
9650   if (RD->isDynamicClass())
9651     return RD;
9652 
9653   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9654   // It's impossible for a class to transitively contain itself by value, so
9655   // infinite recursion is impossible.
9656   for (auto *FD : RD->fields()) {
9657     bool SubContained;
9658     if (const CXXRecordDecl *ContainedRD =
9659             getContainedDynamicClass(FD->getType(), SubContained)) {
9660       IsContained = true;
9661       return ContainedRD;
9662     }
9663   }
9664 
9665   return nullptr;
9666 }
9667 
9668 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9669   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9670     if (Unary->getKind() == UETT_SizeOf)
9671       return Unary;
9672   return nullptr;
9673 }
9674 
9675 /// If E is a sizeof expression, returns its argument expression,
9676 /// otherwise returns NULL.
9677 static const Expr *getSizeOfExprArg(const Expr *E) {
9678   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9679     if (!SizeOf->isArgumentType())
9680       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9681   return nullptr;
9682 }
9683 
9684 /// If E is a sizeof expression, returns its argument type.
9685 static QualType getSizeOfArgType(const Expr *E) {
9686   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9687     return SizeOf->getTypeOfArgument();
9688   return QualType();
9689 }
9690 
9691 namespace {
9692 
9693 struct SearchNonTrivialToInitializeField
9694     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9695   using Super =
9696       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9697 
9698   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9699 
9700   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9701                      SourceLocation SL) {
9702     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9703       asDerived().visitArray(PDIK, AT, SL);
9704       return;
9705     }
9706 
9707     Super::visitWithKind(PDIK, FT, SL);
9708   }
9709 
9710   void visitARCStrong(QualType FT, SourceLocation SL) {
9711     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9712   }
9713   void visitARCWeak(QualType FT, SourceLocation SL) {
9714     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9715   }
9716   void visitStruct(QualType FT, SourceLocation SL) {
9717     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9718       visit(FD->getType(), FD->getLocation());
9719   }
9720   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9721                   const ArrayType *AT, SourceLocation SL) {
9722     visit(getContext().getBaseElementType(AT), SL);
9723   }
9724   void visitTrivial(QualType FT, SourceLocation SL) {}
9725 
9726   static void diag(QualType RT, const Expr *E, Sema &S) {
9727     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9728   }
9729 
9730   ASTContext &getContext() { return S.getASTContext(); }
9731 
9732   const Expr *E;
9733   Sema &S;
9734 };
9735 
9736 struct SearchNonTrivialToCopyField
9737     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9738   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9739 
9740   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9741 
9742   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9743                      SourceLocation SL) {
9744     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9745       asDerived().visitArray(PCK, AT, SL);
9746       return;
9747     }
9748 
9749     Super::visitWithKind(PCK, FT, SL);
9750   }
9751 
9752   void visitARCStrong(QualType FT, SourceLocation SL) {
9753     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9754   }
9755   void visitARCWeak(QualType FT, SourceLocation SL) {
9756     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9757   }
9758   void visitStruct(QualType FT, SourceLocation SL) {
9759     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9760       visit(FD->getType(), FD->getLocation());
9761   }
9762   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9763                   SourceLocation SL) {
9764     visit(getContext().getBaseElementType(AT), SL);
9765   }
9766   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9767                 SourceLocation SL) {}
9768   void visitTrivial(QualType FT, SourceLocation SL) {}
9769   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9770 
9771   static void diag(QualType RT, const Expr *E, Sema &S) {
9772     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9773   }
9774 
9775   ASTContext &getContext() { return S.getASTContext(); }
9776 
9777   const Expr *E;
9778   Sema &S;
9779 };
9780 
9781 }
9782 
9783 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9784 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9785   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9786 
9787   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9788     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9789       return false;
9790 
9791     return doesExprLikelyComputeSize(BO->getLHS()) ||
9792            doesExprLikelyComputeSize(BO->getRHS());
9793   }
9794 
9795   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9796 }
9797 
9798 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9799 ///
9800 /// \code
9801 ///   #define MACRO 0
9802 ///   foo(MACRO);
9803 ///   foo(0);
9804 /// \endcode
9805 ///
9806 /// This should return true for the first call to foo, but not for the second
9807 /// (regardless of whether foo is a macro or function).
9808 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9809                                         SourceLocation CallLoc,
9810                                         SourceLocation ArgLoc) {
9811   if (!CallLoc.isMacroID())
9812     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9813 
9814   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9815          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9816 }
9817 
9818 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9819 /// last two arguments transposed.
9820 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9821   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9822     return;
9823 
9824   const Expr *SizeArg =
9825     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9826 
9827   auto isLiteralZero = [](const Expr *E) {
9828     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9829   };
9830 
9831   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9832   SourceLocation CallLoc = Call->getRParenLoc();
9833   SourceManager &SM = S.getSourceManager();
9834   if (isLiteralZero(SizeArg) &&
9835       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9836 
9837     SourceLocation DiagLoc = SizeArg->getExprLoc();
9838 
9839     // Some platforms #define bzero to __builtin_memset. See if this is the
9840     // case, and if so, emit a better diagnostic.
9841     if (BId == Builtin::BIbzero ||
9842         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9843                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9844       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9845       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9846     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9847       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9848       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9849     }
9850     return;
9851   }
9852 
9853   // If the second argument to a memset is a sizeof expression and the third
9854   // isn't, this is also likely an error. This should catch
9855   // 'memset(buf, sizeof(buf), 0xff)'.
9856   if (BId == Builtin::BImemset &&
9857       doesExprLikelyComputeSize(Call->getArg(1)) &&
9858       !doesExprLikelyComputeSize(Call->getArg(2))) {
9859     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9860     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9861     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9862     return;
9863   }
9864 }
9865 
9866 /// Check for dangerous or invalid arguments to memset().
9867 ///
9868 /// This issues warnings on known problematic, dangerous or unspecified
9869 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9870 /// function calls.
9871 ///
9872 /// \param Call The call expression to diagnose.
9873 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9874                                    unsigned BId,
9875                                    IdentifierInfo *FnName) {
9876   assert(BId != 0);
9877 
9878   // It is possible to have a non-standard definition of memset.  Validate
9879   // we have enough arguments, and if not, abort further checking.
9880   unsigned ExpectedNumArgs =
9881       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9882   if (Call->getNumArgs() < ExpectedNumArgs)
9883     return;
9884 
9885   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9886                       BId == Builtin::BIstrndup ? 1 : 2);
9887   unsigned LenArg =
9888       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9889   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9890 
9891   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9892                                      Call->getBeginLoc(), Call->getRParenLoc()))
9893     return;
9894 
9895   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9896   CheckMemaccessSize(*this, BId, Call);
9897 
9898   // We have special checking when the length is a sizeof expression.
9899   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9900   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9901   llvm::FoldingSetNodeID SizeOfArgID;
9902 
9903   // Although widely used, 'bzero' is not a standard function. Be more strict
9904   // with the argument types before allowing diagnostics and only allow the
9905   // form bzero(ptr, sizeof(...)).
9906   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9907   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9908     return;
9909 
9910   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9911     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9912     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9913 
9914     QualType DestTy = Dest->getType();
9915     QualType PointeeTy;
9916     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9917       PointeeTy = DestPtrTy->getPointeeType();
9918 
9919       // Never warn about void type pointers. This can be used to suppress
9920       // false positives.
9921       if (PointeeTy->isVoidType())
9922         continue;
9923 
9924       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9925       // actually comparing the expressions for equality. Because computing the
9926       // expression IDs can be expensive, we only do this if the diagnostic is
9927       // enabled.
9928       if (SizeOfArg &&
9929           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9930                            SizeOfArg->getExprLoc())) {
9931         // We only compute IDs for expressions if the warning is enabled, and
9932         // cache the sizeof arg's ID.
9933         if (SizeOfArgID == llvm::FoldingSetNodeID())
9934           SizeOfArg->Profile(SizeOfArgID, Context, true);
9935         llvm::FoldingSetNodeID DestID;
9936         Dest->Profile(DestID, Context, true);
9937         if (DestID == SizeOfArgID) {
9938           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9939           //       over sizeof(src) as well.
9940           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9941           StringRef ReadableName = FnName->getName();
9942 
9943           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9944             if (UnaryOp->getOpcode() == UO_AddrOf)
9945               ActionIdx = 1; // If its an address-of operator, just remove it.
9946           if (!PointeeTy->isIncompleteType() &&
9947               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9948             ActionIdx = 2; // If the pointee's size is sizeof(char),
9949                            // suggest an explicit length.
9950 
9951           // If the function is defined as a builtin macro, do not show macro
9952           // expansion.
9953           SourceLocation SL = SizeOfArg->getExprLoc();
9954           SourceRange DSR = Dest->getSourceRange();
9955           SourceRange SSR = SizeOfArg->getSourceRange();
9956           SourceManager &SM = getSourceManager();
9957 
9958           if (SM.isMacroArgExpansion(SL)) {
9959             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9960             SL = SM.getSpellingLoc(SL);
9961             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9962                              SM.getSpellingLoc(DSR.getEnd()));
9963             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9964                              SM.getSpellingLoc(SSR.getEnd()));
9965           }
9966 
9967           DiagRuntimeBehavior(SL, SizeOfArg,
9968                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9969                                 << ReadableName
9970                                 << PointeeTy
9971                                 << DestTy
9972                                 << DSR
9973                                 << SSR);
9974           DiagRuntimeBehavior(SL, SizeOfArg,
9975                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9976                                 << ActionIdx
9977                                 << SSR);
9978 
9979           break;
9980         }
9981       }
9982 
9983       // Also check for cases where the sizeof argument is the exact same
9984       // type as the memory argument, and where it points to a user-defined
9985       // record type.
9986       if (SizeOfArgTy != QualType()) {
9987         if (PointeeTy->isRecordType() &&
9988             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9989           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9990                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9991                                 << FnName << SizeOfArgTy << ArgIdx
9992                                 << PointeeTy << Dest->getSourceRange()
9993                                 << LenExpr->getSourceRange());
9994           break;
9995         }
9996       }
9997     } else if (DestTy->isArrayType()) {
9998       PointeeTy = DestTy;
9999     }
10000 
10001     if (PointeeTy == QualType())
10002       continue;
10003 
10004     // Always complain about dynamic classes.
10005     bool IsContained;
10006     if (const CXXRecordDecl *ContainedRD =
10007             getContainedDynamicClass(PointeeTy, IsContained)) {
10008 
10009       unsigned OperationType = 0;
10010       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10011       // "overwritten" if we're warning about the destination for any call
10012       // but memcmp; otherwise a verb appropriate to the call.
10013       if (ArgIdx != 0 || IsCmp) {
10014         if (BId == Builtin::BImemcpy)
10015           OperationType = 1;
10016         else if(BId == Builtin::BImemmove)
10017           OperationType = 2;
10018         else if (IsCmp)
10019           OperationType = 3;
10020       }
10021 
10022       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10023                           PDiag(diag::warn_dyn_class_memaccess)
10024                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10025                               << IsContained << ContainedRD << OperationType
10026                               << Call->getCallee()->getSourceRange());
10027     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10028              BId != Builtin::BImemset)
10029       DiagRuntimeBehavior(
10030         Dest->getExprLoc(), Dest,
10031         PDiag(diag::warn_arc_object_memaccess)
10032           << ArgIdx << FnName << PointeeTy
10033           << Call->getCallee()->getSourceRange());
10034     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10035       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10036           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10037         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10038                             PDiag(diag::warn_cstruct_memaccess)
10039                                 << ArgIdx << FnName << PointeeTy << 0);
10040         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10041       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10042                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10043         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10044                             PDiag(diag::warn_cstruct_memaccess)
10045                                 << ArgIdx << FnName << PointeeTy << 1);
10046         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10047       } else {
10048         continue;
10049       }
10050     } else
10051       continue;
10052 
10053     DiagRuntimeBehavior(
10054       Dest->getExprLoc(), Dest,
10055       PDiag(diag::note_bad_memaccess_silence)
10056         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10057     break;
10058   }
10059 }
10060 
10061 // A little helper routine: ignore addition and subtraction of integer literals.
10062 // This intentionally does not ignore all integer constant expressions because
10063 // we don't want to remove sizeof().
10064 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10065   Ex = Ex->IgnoreParenCasts();
10066 
10067   while (true) {
10068     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10069     if (!BO || !BO->isAdditiveOp())
10070       break;
10071 
10072     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10073     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10074 
10075     if (isa<IntegerLiteral>(RHS))
10076       Ex = LHS;
10077     else if (isa<IntegerLiteral>(LHS))
10078       Ex = RHS;
10079     else
10080       break;
10081   }
10082 
10083   return Ex;
10084 }
10085 
10086 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10087                                                       ASTContext &Context) {
10088   // Only handle constant-sized or VLAs, but not flexible members.
10089   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10090     // Only issue the FIXIT for arrays of size > 1.
10091     if (CAT->getSize().getSExtValue() <= 1)
10092       return false;
10093   } else if (!Ty->isVariableArrayType()) {
10094     return false;
10095   }
10096   return true;
10097 }
10098 
10099 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10100 // be the size of the source, instead of the destination.
10101 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10102                                     IdentifierInfo *FnName) {
10103 
10104   // Don't crash if the user has the wrong number of arguments
10105   unsigned NumArgs = Call->getNumArgs();
10106   if ((NumArgs != 3) && (NumArgs != 4))
10107     return;
10108 
10109   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10110   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10111   const Expr *CompareWithSrc = nullptr;
10112 
10113   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10114                                      Call->getBeginLoc(), Call->getRParenLoc()))
10115     return;
10116 
10117   // Look for 'strlcpy(dst, x, sizeof(x))'
10118   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10119     CompareWithSrc = Ex;
10120   else {
10121     // Look for 'strlcpy(dst, x, strlen(x))'
10122     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10123       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10124           SizeCall->getNumArgs() == 1)
10125         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10126     }
10127   }
10128 
10129   if (!CompareWithSrc)
10130     return;
10131 
10132   // Determine if the argument to sizeof/strlen is equal to the source
10133   // argument.  In principle there's all kinds of things you could do
10134   // here, for instance creating an == expression and evaluating it with
10135   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10136   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10137   if (!SrcArgDRE)
10138     return;
10139 
10140   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10141   if (!CompareWithSrcDRE ||
10142       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10143     return;
10144 
10145   const Expr *OriginalSizeArg = Call->getArg(2);
10146   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10147       << OriginalSizeArg->getSourceRange() << FnName;
10148 
10149   // Output a FIXIT hint if the destination is an array (rather than a
10150   // pointer to an array).  This could be enhanced to handle some
10151   // pointers if we know the actual size, like if DstArg is 'array+2'
10152   // we could say 'sizeof(array)-2'.
10153   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10154   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10155     return;
10156 
10157   SmallString<128> sizeString;
10158   llvm::raw_svector_ostream OS(sizeString);
10159   OS << "sizeof(";
10160   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10161   OS << ")";
10162 
10163   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10164       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10165                                       OS.str());
10166 }
10167 
10168 /// Check if two expressions refer to the same declaration.
10169 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10170   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10171     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10172       return D1->getDecl() == D2->getDecl();
10173   return false;
10174 }
10175 
10176 static const Expr *getStrlenExprArg(const Expr *E) {
10177   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10178     const FunctionDecl *FD = CE->getDirectCallee();
10179     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10180       return nullptr;
10181     return CE->getArg(0)->IgnoreParenCasts();
10182   }
10183   return nullptr;
10184 }
10185 
10186 // Warn on anti-patterns as the 'size' argument to strncat.
10187 // The correct size argument should look like following:
10188 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10189 void Sema::CheckStrncatArguments(const CallExpr *CE,
10190                                  IdentifierInfo *FnName) {
10191   // Don't crash if the user has the wrong number of arguments.
10192   if (CE->getNumArgs() < 3)
10193     return;
10194   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10195   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10196   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10197 
10198   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10199                                      CE->getRParenLoc()))
10200     return;
10201 
10202   // Identify common expressions, which are wrongly used as the size argument
10203   // to strncat and may lead to buffer overflows.
10204   unsigned PatternType = 0;
10205   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10206     // - sizeof(dst)
10207     if (referToTheSameDecl(SizeOfArg, DstArg))
10208       PatternType = 1;
10209     // - sizeof(src)
10210     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10211       PatternType = 2;
10212   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10213     if (BE->getOpcode() == BO_Sub) {
10214       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10215       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10216       // - sizeof(dst) - strlen(dst)
10217       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10218           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10219         PatternType = 1;
10220       // - sizeof(src) - (anything)
10221       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10222         PatternType = 2;
10223     }
10224   }
10225 
10226   if (PatternType == 0)
10227     return;
10228 
10229   // Generate the diagnostic.
10230   SourceLocation SL = LenArg->getBeginLoc();
10231   SourceRange SR = LenArg->getSourceRange();
10232   SourceManager &SM = getSourceManager();
10233 
10234   // If the function is defined as a builtin macro, do not show macro expansion.
10235   if (SM.isMacroArgExpansion(SL)) {
10236     SL = SM.getSpellingLoc(SL);
10237     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10238                      SM.getSpellingLoc(SR.getEnd()));
10239   }
10240 
10241   // Check if the destination is an array (rather than a pointer to an array).
10242   QualType DstTy = DstArg->getType();
10243   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10244                                                                     Context);
10245   if (!isKnownSizeArray) {
10246     if (PatternType == 1)
10247       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10248     else
10249       Diag(SL, diag::warn_strncat_src_size) << SR;
10250     return;
10251   }
10252 
10253   if (PatternType == 1)
10254     Diag(SL, diag::warn_strncat_large_size) << SR;
10255   else
10256     Diag(SL, diag::warn_strncat_src_size) << SR;
10257 
10258   SmallString<128> sizeString;
10259   llvm::raw_svector_ostream OS(sizeString);
10260   OS << "sizeof(";
10261   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10262   OS << ") - ";
10263   OS << "strlen(";
10264   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10265   OS << ") - 1";
10266 
10267   Diag(SL, diag::note_strncat_wrong_size)
10268     << FixItHint::CreateReplacement(SR, OS.str());
10269 }
10270 
10271 namespace {
10272 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10273                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10274   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10275     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10276         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10277     return;
10278   }
10279 }
10280 
10281 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10282                                  const UnaryOperator *UnaryExpr) {
10283   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10284     const Decl *D = Lvalue->getDecl();
10285     if (isa<VarDecl, FunctionDecl>(D))
10286       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10287   }
10288 
10289   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10290     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10291                                       Lvalue->getMemberDecl());
10292 }
10293 
10294 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10295                             const UnaryOperator *UnaryExpr) {
10296   const auto *Lambda = dyn_cast<LambdaExpr>(
10297       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10298   if (!Lambda)
10299     return;
10300 
10301   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10302       << CalleeName << 2 /*object: lambda expression*/;
10303 }
10304 
10305 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10306                                   const DeclRefExpr *Lvalue) {
10307   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10308   if (Var == nullptr)
10309     return;
10310 
10311   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10312       << CalleeName << 0 /*object: */ << Var;
10313 }
10314 
10315 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10316                             const CastExpr *Cast) {
10317   SmallString<128> SizeString;
10318   llvm::raw_svector_ostream OS(SizeString);
10319 
10320   clang::CastKind Kind = Cast->getCastKind();
10321   if (Kind == clang::CK_BitCast &&
10322       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10323     return;
10324   if (Kind == clang::CK_IntegralToPointer &&
10325       !isa<IntegerLiteral>(
10326           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10327     return;
10328 
10329   switch (Cast->getCastKind()) {
10330   case clang::CK_BitCast:
10331   case clang::CK_IntegralToPointer:
10332   case clang::CK_FunctionToPointerDecay:
10333     OS << '\'';
10334     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10335     OS << '\'';
10336     break;
10337   default:
10338     return;
10339   }
10340 
10341   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10342       << CalleeName << 0 /*object: */ << OS.str();
10343 }
10344 } // namespace
10345 
10346 /// Alerts the user that they are attempting to free a non-malloc'd object.
10347 void Sema::CheckFreeArguments(const CallExpr *E) {
10348   const std::string CalleeName =
10349       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10350 
10351   { // Prefer something that doesn't involve a cast to make things simpler.
10352     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10353     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10354       switch (UnaryExpr->getOpcode()) {
10355       case UnaryOperator::Opcode::UO_AddrOf:
10356         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10357       case UnaryOperator::Opcode::UO_Plus:
10358         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10359       default:
10360         break;
10361       }
10362 
10363     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10364       if (Lvalue->getType()->isArrayType())
10365         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10366 
10367     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10368       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10369           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10370       return;
10371     }
10372 
10373     if (isa<BlockExpr>(Arg)) {
10374       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10375           << CalleeName << 1 /*object: block*/;
10376       return;
10377     }
10378   }
10379   // Maybe the cast was important, check after the other cases.
10380   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10381     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10382 }
10383 
10384 void
10385 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10386                          SourceLocation ReturnLoc,
10387                          bool isObjCMethod,
10388                          const AttrVec *Attrs,
10389                          const FunctionDecl *FD) {
10390   // Check if the return value is null but should not be.
10391   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10392        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10393       CheckNonNullExpr(*this, RetValExp))
10394     Diag(ReturnLoc, diag::warn_null_ret)
10395       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10396 
10397   // C++11 [basic.stc.dynamic.allocation]p4:
10398   //   If an allocation function declared with a non-throwing
10399   //   exception-specification fails to allocate storage, it shall return
10400   //   a null pointer. Any other allocation function that fails to allocate
10401   //   storage shall indicate failure only by throwing an exception [...]
10402   if (FD) {
10403     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10404     if (Op == OO_New || Op == OO_Array_New) {
10405       const FunctionProtoType *Proto
10406         = FD->getType()->castAs<FunctionProtoType>();
10407       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10408           CheckNonNullExpr(*this, RetValExp))
10409         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10410           << FD << getLangOpts().CPlusPlus11;
10411     }
10412   }
10413 
10414   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10415   // here prevent the user from using a PPC MMA type as trailing return type.
10416   if (Context.getTargetInfo().getTriple().isPPC64())
10417     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10418 }
10419 
10420 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10421 
10422 /// Check for comparisons of floating point operands using != and ==.
10423 /// Issue a warning if these are no self-comparisons, as they are not likely
10424 /// to do what the programmer intended.
10425 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10426   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10427   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10428 
10429   // Special case: check for x == x (which is OK).
10430   // Do not emit warnings for such cases.
10431   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10432     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10433       if (DRL->getDecl() == DRR->getDecl())
10434         return;
10435 
10436   // Special case: check for comparisons against literals that can be exactly
10437   //  represented by APFloat.  In such cases, do not emit a warning.  This
10438   //  is a heuristic: often comparison against such literals are used to
10439   //  detect if a value in a variable has not changed.  This clearly can
10440   //  lead to false negatives.
10441   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10442     if (FLL->isExact())
10443       return;
10444   } else
10445     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10446       if (FLR->isExact())
10447         return;
10448 
10449   // Check for comparisons with builtin types.
10450   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10451     if (CL->getBuiltinCallee())
10452       return;
10453 
10454   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10455     if (CR->getBuiltinCallee())
10456       return;
10457 
10458   // Emit the diagnostic.
10459   Diag(Loc, diag::warn_floatingpoint_eq)
10460     << LHS->getSourceRange() << RHS->getSourceRange();
10461 }
10462 
10463 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10464 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10465 
10466 namespace {
10467 
10468 /// Structure recording the 'active' range of an integer-valued
10469 /// expression.
10470 struct IntRange {
10471   /// The number of bits active in the int. Note that this includes exactly one
10472   /// sign bit if !NonNegative.
10473   unsigned Width;
10474 
10475   /// True if the int is known not to have negative values. If so, all leading
10476   /// bits before Width are known zero, otherwise they are known to be the
10477   /// same as the MSB within Width.
10478   bool NonNegative;
10479 
10480   IntRange(unsigned Width, bool NonNegative)
10481       : Width(Width), NonNegative(NonNegative) {}
10482 
10483   /// Number of bits excluding the sign bit.
10484   unsigned valueBits() const {
10485     return NonNegative ? Width : Width - 1;
10486   }
10487 
10488   /// Returns the range of the bool type.
10489   static IntRange forBoolType() {
10490     return IntRange(1, true);
10491   }
10492 
10493   /// Returns the range of an opaque value of the given integral type.
10494   static IntRange forValueOfType(ASTContext &C, QualType T) {
10495     return forValueOfCanonicalType(C,
10496                           T->getCanonicalTypeInternal().getTypePtr());
10497   }
10498 
10499   /// Returns the range of an opaque value of a canonical integral type.
10500   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10501     assert(T->isCanonicalUnqualified());
10502 
10503     if (const VectorType *VT = dyn_cast<VectorType>(T))
10504       T = VT->getElementType().getTypePtr();
10505     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10506       T = CT->getElementType().getTypePtr();
10507     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10508       T = AT->getValueType().getTypePtr();
10509 
10510     if (!C.getLangOpts().CPlusPlus) {
10511       // For enum types in C code, use the underlying datatype.
10512       if (const EnumType *ET = dyn_cast<EnumType>(T))
10513         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10514     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10515       // For enum types in C++, use the known bit width of the enumerators.
10516       EnumDecl *Enum = ET->getDecl();
10517       // In C++11, enums can have a fixed underlying type. Use this type to
10518       // compute the range.
10519       if (Enum->isFixed()) {
10520         return IntRange(C.getIntWidth(QualType(T, 0)),
10521                         !ET->isSignedIntegerOrEnumerationType());
10522       }
10523 
10524       unsigned NumPositive = Enum->getNumPositiveBits();
10525       unsigned NumNegative = Enum->getNumNegativeBits();
10526 
10527       if (NumNegative == 0)
10528         return IntRange(NumPositive, true/*NonNegative*/);
10529       else
10530         return IntRange(std::max(NumPositive + 1, NumNegative),
10531                         false/*NonNegative*/);
10532     }
10533 
10534     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10535       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10536 
10537     const BuiltinType *BT = cast<BuiltinType>(T);
10538     assert(BT->isInteger());
10539 
10540     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10541   }
10542 
10543   /// Returns the "target" range of a canonical integral type, i.e.
10544   /// the range of values expressible in the type.
10545   ///
10546   /// This matches forValueOfCanonicalType except that enums have the
10547   /// full range of their type, not the range of their enumerators.
10548   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10549     assert(T->isCanonicalUnqualified());
10550 
10551     if (const VectorType *VT = dyn_cast<VectorType>(T))
10552       T = VT->getElementType().getTypePtr();
10553     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10554       T = CT->getElementType().getTypePtr();
10555     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10556       T = AT->getValueType().getTypePtr();
10557     if (const EnumType *ET = dyn_cast<EnumType>(T))
10558       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10559 
10560     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10561       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10562 
10563     const BuiltinType *BT = cast<BuiltinType>(T);
10564     assert(BT->isInteger());
10565 
10566     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10567   }
10568 
10569   /// Returns the supremum of two ranges: i.e. their conservative merge.
10570   static IntRange join(IntRange L, IntRange R) {
10571     bool Unsigned = L.NonNegative && R.NonNegative;
10572     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10573                     L.NonNegative && R.NonNegative);
10574   }
10575 
10576   /// Return the range of a bitwise-AND of the two ranges.
10577   static IntRange bit_and(IntRange L, IntRange R) {
10578     unsigned Bits = std::max(L.Width, R.Width);
10579     bool NonNegative = false;
10580     if (L.NonNegative) {
10581       Bits = std::min(Bits, L.Width);
10582       NonNegative = true;
10583     }
10584     if (R.NonNegative) {
10585       Bits = std::min(Bits, R.Width);
10586       NonNegative = true;
10587     }
10588     return IntRange(Bits, NonNegative);
10589   }
10590 
10591   /// Return the range of a sum of the two ranges.
10592   static IntRange sum(IntRange L, IntRange R) {
10593     bool Unsigned = L.NonNegative && R.NonNegative;
10594     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10595                     Unsigned);
10596   }
10597 
10598   /// Return the range of a difference of the two ranges.
10599   static IntRange difference(IntRange L, IntRange R) {
10600     // We need a 1-bit-wider range if:
10601     //   1) LHS can be negative: least value can be reduced.
10602     //   2) RHS can be negative: greatest value can be increased.
10603     bool CanWiden = !L.NonNegative || !R.NonNegative;
10604     bool Unsigned = L.NonNegative && R.Width == 0;
10605     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10606                         !Unsigned,
10607                     Unsigned);
10608   }
10609 
10610   /// Return the range of a product of the two ranges.
10611   static IntRange product(IntRange L, IntRange R) {
10612     // If both LHS and RHS can be negative, we can form
10613     //   -2^L * -2^R = 2^(L + R)
10614     // which requires L + R + 1 value bits to represent.
10615     bool CanWiden = !L.NonNegative && !R.NonNegative;
10616     bool Unsigned = L.NonNegative && R.NonNegative;
10617     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10618                     Unsigned);
10619   }
10620 
10621   /// Return the range of a remainder operation between the two ranges.
10622   static IntRange rem(IntRange L, IntRange R) {
10623     // The result of a remainder can't be larger than the result of
10624     // either side. The sign of the result is the sign of the LHS.
10625     bool Unsigned = L.NonNegative;
10626     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10627                     Unsigned);
10628   }
10629 };
10630 
10631 } // namespace
10632 
10633 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10634                               unsigned MaxWidth) {
10635   if (value.isSigned() && value.isNegative())
10636     return IntRange(value.getMinSignedBits(), false);
10637 
10638   if (value.getBitWidth() > MaxWidth)
10639     value = value.trunc(MaxWidth);
10640 
10641   // isNonNegative() just checks the sign bit without considering
10642   // signedness.
10643   return IntRange(value.getActiveBits(), true);
10644 }
10645 
10646 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10647                               unsigned MaxWidth) {
10648   if (result.isInt())
10649     return GetValueRange(C, result.getInt(), MaxWidth);
10650 
10651   if (result.isVector()) {
10652     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10653     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10654       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10655       R = IntRange::join(R, El);
10656     }
10657     return R;
10658   }
10659 
10660   if (result.isComplexInt()) {
10661     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10662     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10663     return IntRange::join(R, I);
10664   }
10665 
10666   // This can happen with lossless casts to intptr_t of "based" lvalues.
10667   // Assume it might use arbitrary bits.
10668   // FIXME: The only reason we need to pass the type in here is to get
10669   // the sign right on this one case.  It would be nice if APValue
10670   // preserved this.
10671   assert(result.isLValue() || result.isAddrLabelDiff());
10672   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10673 }
10674 
10675 static QualType GetExprType(const Expr *E) {
10676   QualType Ty = E->getType();
10677   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10678     Ty = AtomicRHS->getValueType();
10679   return Ty;
10680 }
10681 
10682 /// Pseudo-evaluate the given integer expression, estimating the
10683 /// range of values it might take.
10684 ///
10685 /// \param MaxWidth The width to which the value will be truncated.
10686 /// \param Approximate If \c true, return a likely range for the result: in
10687 ///        particular, assume that aritmetic on narrower types doesn't leave
10688 ///        those types. If \c false, return a range including all possible
10689 ///        result values.
10690 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10691                              bool InConstantContext, bool Approximate) {
10692   E = E->IgnoreParens();
10693 
10694   // Try a full evaluation first.
10695   Expr::EvalResult result;
10696   if (E->EvaluateAsRValue(result, C, InConstantContext))
10697     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10698 
10699   // I think we only want to look through implicit casts here; if the
10700   // user has an explicit widening cast, we should treat the value as
10701   // being of the new, wider type.
10702   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10703     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10704       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10705                           Approximate);
10706 
10707     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10708 
10709     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10710                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10711 
10712     // Assume that non-integer casts can span the full range of the type.
10713     if (!isIntegerCast)
10714       return OutputTypeRange;
10715 
10716     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10717                                      std::min(MaxWidth, OutputTypeRange.Width),
10718                                      InConstantContext, Approximate);
10719 
10720     // Bail out if the subexpr's range is as wide as the cast type.
10721     if (SubRange.Width >= OutputTypeRange.Width)
10722       return OutputTypeRange;
10723 
10724     // Otherwise, we take the smaller width, and we're non-negative if
10725     // either the output type or the subexpr is.
10726     return IntRange(SubRange.Width,
10727                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10728   }
10729 
10730   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10731     // If we can fold the condition, just take that operand.
10732     bool CondResult;
10733     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10734       return GetExprRange(C,
10735                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10736                           MaxWidth, InConstantContext, Approximate);
10737 
10738     // Otherwise, conservatively merge.
10739     // GetExprRange requires an integer expression, but a throw expression
10740     // results in a void type.
10741     Expr *E = CO->getTrueExpr();
10742     IntRange L = E->getType()->isVoidType()
10743                      ? IntRange{0, true}
10744                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10745     E = CO->getFalseExpr();
10746     IntRange R = E->getType()->isVoidType()
10747                      ? IntRange{0, true}
10748                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10749     return IntRange::join(L, R);
10750   }
10751 
10752   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10753     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10754 
10755     switch (BO->getOpcode()) {
10756     case BO_Cmp:
10757       llvm_unreachable("builtin <=> should have class type");
10758 
10759     // Boolean-valued operations are single-bit and positive.
10760     case BO_LAnd:
10761     case BO_LOr:
10762     case BO_LT:
10763     case BO_GT:
10764     case BO_LE:
10765     case BO_GE:
10766     case BO_EQ:
10767     case BO_NE:
10768       return IntRange::forBoolType();
10769 
10770     // The type of the assignments is the type of the LHS, so the RHS
10771     // is not necessarily the same type.
10772     case BO_MulAssign:
10773     case BO_DivAssign:
10774     case BO_RemAssign:
10775     case BO_AddAssign:
10776     case BO_SubAssign:
10777     case BO_XorAssign:
10778     case BO_OrAssign:
10779       // TODO: bitfields?
10780       return IntRange::forValueOfType(C, GetExprType(E));
10781 
10782     // Simple assignments just pass through the RHS, which will have
10783     // been coerced to the LHS type.
10784     case BO_Assign:
10785       // TODO: bitfields?
10786       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10787                           Approximate);
10788 
10789     // Operations with opaque sources are black-listed.
10790     case BO_PtrMemD:
10791     case BO_PtrMemI:
10792       return IntRange::forValueOfType(C, GetExprType(E));
10793 
10794     // Bitwise-and uses the *infinum* of the two source ranges.
10795     case BO_And:
10796     case BO_AndAssign:
10797       Combine = IntRange::bit_and;
10798       break;
10799 
10800     // Left shift gets black-listed based on a judgement call.
10801     case BO_Shl:
10802       // ...except that we want to treat '1 << (blah)' as logically
10803       // positive.  It's an important idiom.
10804       if (IntegerLiteral *I
10805             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10806         if (I->getValue() == 1) {
10807           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10808           return IntRange(R.Width, /*NonNegative*/ true);
10809         }
10810       }
10811       LLVM_FALLTHROUGH;
10812 
10813     case BO_ShlAssign:
10814       return IntRange::forValueOfType(C, GetExprType(E));
10815 
10816     // Right shift by a constant can narrow its left argument.
10817     case BO_Shr:
10818     case BO_ShrAssign: {
10819       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10820                                 Approximate);
10821 
10822       // If the shift amount is a positive constant, drop the width by
10823       // that much.
10824       if (Optional<llvm::APSInt> shift =
10825               BO->getRHS()->getIntegerConstantExpr(C)) {
10826         if (shift->isNonNegative()) {
10827           unsigned zext = shift->getZExtValue();
10828           if (zext >= L.Width)
10829             L.Width = (L.NonNegative ? 0 : 1);
10830           else
10831             L.Width -= zext;
10832         }
10833       }
10834 
10835       return L;
10836     }
10837 
10838     // Comma acts as its right operand.
10839     case BO_Comma:
10840       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10841                           Approximate);
10842 
10843     case BO_Add:
10844       if (!Approximate)
10845         Combine = IntRange::sum;
10846       break;
10847 
10848     case BO_Sub:
10849       if (BO->getLHS()->getType()->isPointerType())
10850         return IntRange::forValueOfType(C, GetExprType(E));
10851       if (!Approximate)
10852         Combine = IntRange::difference;
10853       break;
10854 
10855     case BO_Mul:
10856       if (!Approximate)
10857         Combine = IntRange::product;
10858       break;
10859 
10860     // The width of a division result is mostly determined by the size
10861     // of the LHS.
10862     case BO_Div: {
10863       // Don't 'pre-truncate' the operands.
10864       unsigned opWidth = C.getIntWidth(GetExprType(E));
10865       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10866                                 Approximate);
10867 
10868       // If the divisor is constant, use that.
10869       if (Optional<llvm::APSInt> divisor =
10870               BO->getRHS()->getIntegerConstantExpr(C)) {
10871         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10872         if (log2 >= L.Width)
10873           L.Width = (L.NonNegative ? 0 : 1);
10874         else
10875           L.Width = std::min(L.Width - log2, MaxWidth);
10876         return L;
10877       }
10878 
10879       // Otherwise, just use the LHS's width.
10880       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10881       // could be -1.
10882       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10883                                 Approximate);
10884       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10885     }
10886 
10887     case BO_Rem:
10888       Combine = IntRange::rem;
10889       break;
10890 
10891     // The default behavior is okay for these.
10892     case BO_Xor:
10893     case BO_Or:
10894       break;
10895     }
10896 
10897     // Combine the two ranges, but limit the result to the type in which we
10898     // performed the computation.
10899     QualType T = GetExprType(E);
10900     unsigned opWidth = C.getIntWidth(T);
10901     IntRange L =
10902         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10903     IntRange R =
10904         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10905     IntRange C = Combine(L, R);
10906     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10907     C.Width = std::min(C.Width, MaxWidth);
10908     return C;
10909   }
10910 
10911   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10912     switch (UO->getOpcode()) {
10913     // Boolean-valued operations are white-listed.
10914     case UO_LNot:
10915       return IntRange::forBoolType();
10916 
10917     // Operations with opaque sources are black-listed.
10918     case UO_Deref:
10919     case UO_AddrOf: // should be impossible
10920       return IntRange::forValueOfType(C, GetExprType(E));
10921 
10922     default:
10923       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10924                           Approximate);
10925     }
10926   }
10927 
10928   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10929     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10930                         Approximate);
10931 
10932   if (const auto *BitField = E->getSourceBitField())
10933     return IntRange(BitField->getBitWidthValue(C),
10934                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10935 
10936   return IntRange::forValueOfType(C, GetExprType(E));
10937 }
10938 
10939 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10940                              bool InConstantContext, bool Approximate) {
10941   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10942                       Approximate);
10943 }
10944 
10945 /// Checks whether the given value, which currently has the given
10946 /// source semantics, has the same value when coerced through the
10947 /// target semantics.
10948 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10949                                  const llvm::fltSemantics &Src,
10950                                  const llvm::fltSemantics &Tgt) {
10951   llvm::APFloat truncated = value;
10952 
10953   bool ignored;
10954   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10955   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10956 
10957   return truncated.bitwiseIsEqual(value);
10958 }
10959 
10960 /// Checks whether the given value, which currently has the given
10961 /// source semantics, has the same value when coerced through the
10962 /// target semantics.
10963 ///
10964 /// The value might be a vector of floats (or a complex number).
10965 static bool IsSameFloatAfterCast(const APValue &value,
10966                                  const llvm::fltSemantics &Src,
10967                                  const llvm::fltSemantics &Tgt) {
10968   if (value.isFloat())
10969     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10970 
10971   if (value.isVector()) {
10972     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10973       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10974         return false;
10975     return true;
10976   }
10977 
10978   assert(value.isComplexFloat());
10979   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10980           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10981 }
10982 
10983 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10984                                        bool IsListInit = false);
10985 
10986 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10987   // Suppress cases where we are comparing against an enum constant.
10988   if (const DeclRefExpr *DR =
10989       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10990     if (isa<EnumConstantDecl>(DR->getDecl()))
10991       return true;
10992 
10993   // Suppress cases where the value is expanded from a macro, unless that macro
10994   // is how a language represents a boolean literal. This is the case in both C
10995   // and Objective-C.
10996   SourceLocation BeginLoc = E->getBeginLoc();
10997   if (BeginLoc.isMacroID()) {
10998     StringRef MacroName = Lexer::getImmediateMacroName(
10999         BeginLoc, S.getSourceManager(), S.getLangOpts());
11000     return MacroName != "YES" && MacroName != "NO" &&
11001            MacroName != "true" && MacroName != "false";
11002   }
11003 
11004   return false;
11005 }
11006 
11007 static bool isKnownToHaveUnsignedValue(Expr *E) {
11008   return E->getType()->isIntegerType() &&
11009          (!E->getType()->isSignedIntegerType() ||
11010           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11011 }
11012 
11013 namespace {
11014 /// The promoted range of values of a type. In general this has the
11015 /// following structure:
11016 ///
11017 ///     |-----------| . . . |-----------|
11018 ///     ^           ^       ^           ^
11019 ///    Min       HoleMin  HoleMax      Max
11020 ///
11021 /// ... where there is only a hole if a signed type is promoted to unsigned
11022 /// (in which case Min and Max are the smallest and largest representable
11023 /// values).
11024 struct PromotedRange {
11025   // Min, or HoleMax if there is a hole.
11026   llvm::APSInt PromotedMin;
11027   // Max, or HoleMin if there is a hole.
11028   llvm::APSInt PromotedMax;
11029 
11030   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11031     if (R.Width == 0)
11032       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11033     else if (R.Width >= BitWidth && !Unsigned) {
11034       // Promotion made the type *narrower*. This happens when promoting
11035       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11036       // Treat all values of 'signed int' as being in range for now.
11037       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11038       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11039     } else {
11040       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11041                         .extOrTrunc(BitWidth);
11042       PromotedMin.setIsUnsigned(Unsigned);
11043 
11044       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11045                         .extOrTrunc(BitWidth);
11046       PromotedMax.setIsUnsigned(Unsigned);
11047     }
11048   }
11049 
11050   // Determine whether this range is contiguous (has no hole).
11051   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11052 
11053   // Where a constant value is within the range.
11054   enum ComparisonResult {
11055     LT = 0x1,
11056     LE = 0x2,
11057     GT = 0x4,
11058     GE = 0x8,
11059     EQ = 0x10,
11060     NE = 0x20,
11061     InRangeFlag = 0x40,
11062 
11063     Less = LE | LT | NE,
11064     Min = LE | InRangeFlag,
11065     InRange = InRangeFlag,
11066     Max = GE | InRangeFlag,
11067     Greater = GE | GT | NE,
11068 
11069     OnlyValue = LE | GE | EQ | InRangeFlag,
11070     InHole = NE
11071   };
11072 
11073   ComparisonResult compare(const llvm::APSInt &Value) const {
11074     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11075            Value.isUnsigned() == PromotedMin.isUnsigned());
11076     if (!isContiguous()) {
11077       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11078       if (Value.isMinValue()) return Min;
11079       if (Value.isMaxValue()) return Max;
11080       if (Value >= PromotedMin) return InRange;
11081       if (Value <= PromotedMax) return InRange;
11082       return InHole;
11083     }
11084 
11085     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11086     case -1: return Less;
11087     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11088     case 1:
11089       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11090       case -1: return InRange;
11091       case 0: return Max;
11092       case 1: return Greater;
11093       }
11094     }
11095 
11096     llvm_unreachable("impossible compare result");
11097   }
11098 
11099   static llvm::Optional<StringRef>
11100   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11101     if (Op == BO_Cmp) {
11102       ComparisonResult LTFlag = LT, GTFlag = GT;
11103       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11104 
11105       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11106       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11107       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11108       return llvm::None;
11109     }
11110 
11111     ComparisonResult TrueFlag, FalseFlag;
11112     if (Op == BO_EQ) {
11113       TrueFlag = EQ;
11114       FalseFlag = NE;
11115     } else if (Op == BO_NE) {
11116       TrueFlag = NE;
11117       FalseFlag = EQ;
11118     } else {
11119       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11120         TrueFlag = LT;
11121         FalseFlag = GE;
11122       } else {
11123         TrueFlag = GT;
11124         FalseFlag = LE;
11125       }
11126       if (Op == BO_GE || Op == BO_LE)
11127         std::swap(TrueFlag, FalseFlag);
11128     }
11129     if (R & TrueFlag)
11130       return StringRef("true");
11131     if (R & FalseFlag)
11132       return StringRef("false");
11133     return llvm::None;
11134   }
11135 };
11136 }
11137 
11138 static bool HasEnumType(Expr *E) {
11139   // Strip off implicit integral promotions.
11140   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11141     if (ICE->getCastKind() != CK_IntegralCast &&
11142         ICE->getCastKind() != CK_NoOp)
11143       break;
11144     E = ICE->getSubExpr();
11145   }
11146 
11147   return E->getType()->isEnumeralType();
11148 }
11149 
11150 static int classifyConstantValue(Expr *Constant) {
11151   // The values of this enumeration are used in the diagnostics
11152   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11153   enum ConstantValueKind {
11154     Miscellaneous = 0,
11155     LiteralTrue,
11156     LiteralFalse
11157   };
11158   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11159     return BL->getValue() ? ConstantValueKind::LiteralTrue
11160                           : ConstantValueKind::LiteralFalse;
11161   return ConstantValueKind::Miscellaneous;
11162 }
11163 
11164 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11165                                         Expr *Constant, Expr *Other,
11166                                         const llvm::APSInt &Value,
11167                                         bool RhsConstant) {
11168   if (S.inTemplateInstantiation())
11169     return false;
11170 
11171   Expr *OriginalOther = Other;
11172 
11173   Constant = Constant->IgnoreParenImpCasts();
11174   Other = Other->IgnoreParenImpCasts();
11175 
11176   // Suppress warnings on tautological comparisons between values of the same
11177   // enumeration type. There are only two ways we could warn on this:
11178   //  - If the constant is outside the range of representable values of
11179   //    the enumeration. In such a case, we should warn about the cast
11180   //    to enumeration type, not about the comparison.
11181   //  - If the constant is the maximum / minimum in-range value. For an
11182   //    enumeratin type, such comparisons can be meaningful and useful.
11183   if (Constant->getType()->isEnumeralType() &&
11184       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11185     return false;
11186 
11187   IntRange OtherValueRange = GetExprRange(
11188       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11189 
11190   QualType OtherT = Other->getType();
11191   if (const auto *AT = OtherT->getAs<AtomicType>())
11192     OtherT = AT->getValueType();
11193   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11194 
11195   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11196   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11197   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11198                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11199                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11200 
11201   // Whether we're treating Other as being a bool because of the form of
11202   // expression despite it having another type (typically 'int' in C).
11203   bool OtherIsBooleanDespiteType =
11204       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11205   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11206     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11207 
11208   // Check if all values in the range of possible values of this expression
11209   // lead to the same comparison outcome.
11210   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11211                                         Value.isUnsigned());
11212   auto Cmp = OtherPromotedValueRange.compare(Value);
11213   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11214   if (!Result)
11215     return false;
11216 
11217   // Also consider the range determined by the type alone. This allows us to
11218   // classify the warning under the proper diagnostic group.
11219   bool TautologicalTypeCompare = false;
11220   {
11221     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11222                                          Value.isUnsigned());
11223     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11224     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11225                                                        RhsConstant)) {
11226       TautologicalTypeCompare = true;
11227       Cmp = TypeCmp;
11228       Result = TypeResult;
11229     }
11230   }
11231 
11232   // Don't warn if the non-constant operand actually always evaluates to the
11233   // same value.
11234   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11235     return false;
11236 
11237   // Suppress the diagnostic for an in-range comparison if the constant comes
11238   // from a macro or enumerator. We don't want to diagnose
11239   //
11240   //   some_long_value <= INT_MAX
11241   //
11242   // when sizeof(int) == sizeof(long).
11243   bool InRange = Cmp & PromotedRange::InRangeFlag;
11244   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11245     return false;
11246 
11247   // A comparison of an unsigned bit-field against 0 is really a type problem,
11248   // even though at the type level the bit-field might promote to 'signed int'.
11249   if (Other->refersToBitField() && InRange && Value == 0 &&
11250       Other->getType()->isUnsignedIntegerOrEnumerationType())
11251     TautologicalTypeCompare = true;
11252 
11253   // If this is a comparison to an enum constant, include that
11254   // constant in the diagnostic.
11255   const EnumConstantDecl *ED = nullptr;
11256   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11257     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11258 
11259   // Should be enough for uint128 (39 decimal digits)
11260   SmallString<64> PrettySourceValue;
11261   llvm::raw_svector_ostream OS(PrettySourceValue);
11262   if (ED) {
11263     OS << '\'' << *ED << "' (" << Value << ")";
11264   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11265                Constant->IgnoreParenImpCasts())) {
11266     OS << (BL->getValue() ? "YES" : "NO");
11267   } else {
11268     OS << Value;
11269   }
11270 
11271   if (!TautologicalTypeCompare) {
11272     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11273         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11274         << E->getOpcodeStr() << OS.str() << *Result
11275         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11276     return true;
11277   }
11278 
11279   if (IsObjCSignedCharBool) {
11280     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11281                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11282                               << OS.str() << *Result);
11283     return true;
11284   }
11285 
11286   // FIXME: We use a somewhat different formatting for the in-range cases and
11287   // cases involving boolean values for historical reasons. We should pick a
11288   // consistent way of presenting these diagnostics.
11289   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11290 
11291     S.DiagRuntimeBehavior(
11292         E->getOperatorLoc(), E,
11293         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11294                          : diag::warn_tautological_bool_compare)
11295             << OS.str() << classifyConstantValue(Constant) << OtherT
11296             << OtherIsBooleanDespiteType << *Result
11297             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11298   } else {
11299     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11300                         ? (HasEnumType(OriginalOther)
11301                                ? diag::warn_unsigned_enum_always_true_comparison
11302                                : diag::warn_unsigned_always_true_comparison)
11303                         : diag::warn_tautological_constant_compare;
11304 
11305     S.Diag(E->getOperatorLoc(), Diag)
11306         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11307         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11308   }
11309 
11310   return true;
11311 }
11312 
11313 /// Analyze the operands of the given comparison.  Implements the
11314 /// fallback case from AnalyzeComparison.
11315 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11316   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11317   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11318 }
11319 
11320 /// Implements -Wsign-compare.
11321 ///
11322 /// \param E the binary operator to check for warnings
11323 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11324   // The type the comparison is being performed in.
11325   QualType T = E->getLHS()->getType();
11326 
11327   // Only analyze comparison operators where both sides have been converted to
11328   // the same type.
11329   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11330     return AnalyzeImpConvsInComparison(S, E);
11331 
11332   // Don't analyze value-dependent comparisons directly.
11333   if (E->isValueDependent())
11334     return AnalyzeImpConvsInComparison(S, E);
11335 
11336   Expr *LHS = E->getLHS();
11337   Expr *RHS = E->getRHS();
11338 
11339   if (T->isIntegralType(S.Context)) {
11340     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11341     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11342 
11343     // We don't care about expressions whose result is a constant.
11344     if (RHSValue && LHSValue)
11345       return AnalyzeImpConvsInComparison(S, E);
11346 
11347     // We only care about expressions where just one side is literal
11348     if ((bool)RHSValue ^ (bool)LHSValue) {
11349       // Is the constant on the RHS or LHS?
11350       const bool RhsConstant = (bool)RHSValue;
11351       Expr *Const = RhsConstant ? RHS : LHS;
11352       Expr *Other = RhsConstant ? LHS : RHS;
11353       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11354 
11355       // Check whether an integer constant comparison results in a value
11356       // of 'true' or 'false'.
11357       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11358         return AnalyzeImpConvsInComparison(S, E);
11359     }
11360   }
11361 
11362   if (!T->hasUnsignedIntegerRepresentation()) {
11363     // We don't do anything special if this isn't an unsigned integral
11364     // comparison:  we're only interested in integral comparisons, and
11365     // signed comparisons only happen in cases we don't care to warn about.
11366     return AnalyzeImpConvsInComparison(S, E);
11367   }
11368 
11369   LHS = LHS->IgnoreParenImpCasts();
11370   RHS = RHS->IgnoreParenImpCasts();
11371 
11372   if (!S.getLangOpts().CPlusPlus) {
11373     // Avoid warning about comparison of integers with different signs when
11374     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11375     // the type of `E`.
11376     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11377       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11378     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11379       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11380   }
11381 
11382   // Check to see if one of the (unmodified) operands is of different
11383   // signedness.
11384   Expr *signedOperand, *unsignedOperand;
11385   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11386     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11387            "unsigned comparison between two signed integer expressions?");
11388     signedOperand = LHS;
11389     unsignedOperand = RHS;
11390   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11391     signedOperand = RHS;
11392     unsignedOperand = LHS;
11393   } else {
11394     return AnalyzeImpConvsInComparison(S, E);
11395   }
11396 
11397   // Otherwise, calculate the effective range of the signed operand.
11398   IntRange signedRange = GetExprRange(
11399       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11400 
11401   // Go ahead and analyze implicit conversions in the operands.  Note
11402   // that we skip the implicit conversions on both sides.
11403   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11404   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11405 
11406   // If the signed range is non-negative, -Wsign-compare won't fire.
11407   if (signedRange.NonNegative)
11408     return;
11409 
11410   // For (in)equality comparisons, if the unsigned operand is a
11411   // constant which cannot collide with a overflowed signed operand,
11412   // then reinterpreting the signed operand as unsigned will not
11413   // change the result of the comparison.
11414   if (E->isEqualityOp()) {
11415     unsigned comparisonWidth = S.Context.getIntWidth(T);
11416     IntRange unsignedRange =
11417         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11418                      /*Approximate*/ true);
11419 
11420     // We should never be unable to prove that the unsigned operand is
11421     // non-negative.
11422     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11423 
11424     if (unsignedRange.Width < comparisonWidth)
11425       return;
11426   }
11427 
11428   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11429                         S.PDiag(diag::warn_mixed_sign_comparison)
11430                             << LHS->getType() << RHS->getType()
11431                             << LHS->getSourceRange() << RHS->getSourceRange());
11432 }
11433 
11434 /// Analyzes an attempt to assign the given value to a bitfield.
11435 ///
11436 /// Returns true if there was something fishy about the attempt.
11437 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11438                                       SourceLocation InitLoc) {
11439   assert(Bitfield->isBitField());
11440   if (Bitfield->isInvalidDecl())
11441     return false;
11442 
11443   // White-list bool bitfields.
11444   QualType BitfieldType = Bitfield->getType();
11445   if (BitfieldType->isBooleanType())
11446      return false;
11447 
11448   if (BitfieldType->isEnumeralType()) {
11449     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11450     // If the underlying enum type was not explicitly specified as an unsigned
11451     // type and the enum contain only positive values, MSVC++ will cause an
11452     // inconsistency by storing this as a signed type.
11453     if (S.getLangOpts().CPlusPlus11 &&
11454         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11455         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11456         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11457       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11458           << BitfieldEnumDecl;
11459     }
11460   }
11461 
11462   if (Bitfield->getType()->isBooleanType())
11463     return false;
11464 
11465   // Ignore value- or type-dependent expressions.
11466   if (Bitfield->getBitWidth()->isValueDependent() ||
11467       Bitfield->getBitWidth()->isTypeDependent() ||
11468       Init->isValueDependent() ||
11469       Init->isTypeDependent())
11470     return false;
11471 
11472   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11473   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11474 
11475   Expr::EvalResult Result;
11476   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11477                                    Expr::SE_AllowSideEffects)) {
11478     // The RHS is not constant.  If the RHS has an enum type, make sure the
11479     // bitfield is wide enough to hold all the values of the enum without
11480     // truncation.
11481     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11482       EnumDecl *ED = EnumTy->getDecl();
11483       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11484 
11485       // Enum types are implicitly signed on Windows, so check if there are any
11486       // negative enumerators to see if the enum was intended to be signed or
11487       // not.
11488       bool SignedEnum = ED->getNumNegativeBits() > 0;
11489 
11490       // Check for surprising sign changes when assigning enum values to a
11491       // bitfield of different signedness.  If the bitfield is signed and we
11492       // have exactly the right number of bits to store this unsigned enum,
11493       // suggest changing the enum to an unsigned type. This typically happens
11494       // on Windows where unfixed enums always use an underlying type of 'int'.
11495       unsigned DiagID = 0;
11496       if (SignedEnum && !SignedBitfield) {
11497         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11498       } else if (SignedBitfield && !SignedEnum &&
11499                  ED->getNumPositiveBits() == FieldWidth) {
11500         DiagID = diag::warn_signed_bitfield_enum_conversion;
11501       }
11502 
11503       if (DiagID) {
11504         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11505         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11506         SourceRange TypeRange =
11507             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11508         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11509             << SignedEnum << TypeRange;
11510       }
11511 
11512       // Compute the required bitwidth. If the enum has negative values, we need
11513       // one more bit than the normal number of positive bits to represent the
11514       // sign bit.
11515       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11516                                                   ED->getNumNegativeBits())
11517                                        : ED->getNumPositiveBits();
11518 
11519       // Check the bitwidth.
11520       if (BitsNeeded > FieldWidth) {
11521         Expr *WidthExpr = Bitfield->getBitWidth();
11522         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11523             << Bitfield << ED;
11524         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11525             << BitsNeeded << ED << WidthExpr->getSourceRange();
11526       }
11527     }
11528 
11529     return false;
11530   }
11531 
11532   llvm::APSInt Value = Result.Val.getInt();
11533 
11534   unsigned OriginalWidth = Value.getBitWidth();
11535 
11536   if (!Value.isSigned() || Value.isNegative())
11537     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11538       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11539         OriginalWidth = Value.getMinSignedBits();
11540 
11541   if (OriginalWidth <= FieldWidth)
11542     return false;
11543 
11544   // Compute the value which the bitfield will contain.
11545   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11546   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11547 
11548   // Check whether the stored value is equal to the original value.
11549   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11550   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11551     return false;
11552 
11553   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11554   // therefore don't strictly fit into a signed bitfield of width 1.
11555   if (FieldWidth == 1 && Value == 1)
11556     return false;
11557 
11558   std::string PrettyValue = Value.toString(10);
11559   std::string PrettyTrunc = TruncatedValue.toString(10);
11560 
11561   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11562     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11563     << Init->getSourceRange();
11564 
11565   return true;
11566 }
11567 
11568 /// Analyze the given simple or compound assignment for warning-worthy
11569 /// operations.
11570 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11571   // Just recurse on the LHS.
11572   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11573 
11574   // We want to recurse on the RHS as normal unless we're assigning to
11575   // a bitfield.
11576   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11577     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11578                                   E->getOperatorLoc())) {
11579       // Recurse, ignoring any implicit conversions on the RHS.
11580       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11581                                         E->getOperatorLoc());
11582     }
11583   }
11584 
11585   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11586 
11587   // Diagnose implicitly sequentially-consistent atomic assignment.
11588   if (E->getLHS()->getType()->isAtomicType())
11589     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11590 }
11591 
11592 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11593 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11594                             SourceLocation CContext, unsigned diag,
11595                             bool pruneControlFlow = false) {
11596   if (pruneControlFlow) {
11597     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11598                           S.PDiag(diag)
11599                               << SourceType << T << E->getSourceRange()
11600                               << SourceRange(CContext));
11601     return;
11602   }
11603   S.Diag(E->getExprLoc(), diag)
11604     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11605 }
11606 
11607 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11608 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11609                             SourceLocation CContext,
11610                             unsigned diag, bool pruneControlFlow = false) {
11611   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11612 }
11613 
11614 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11615   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11616       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11617 }
11618 
11619 static void adornObjCBoolConversionDiagWithTernaryFixit(
11620     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11621   Expr *Ignored = SourceExpr->IgnoreImplicit();
11622   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11623     Ignored = OVE->getSourceExpr();
11624   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11625                      isa<BinaryOperator>(Ignored) ||
11626                      isa<CXXOperatorCallExpr>(Ignored);
11627   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11628   if (NeedsParens)
11629     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11630             << FixItHint::CreateInsertion(EndLoc, ")");
11631   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11632 }
11633 
11634 /// Diagnose an implicit cast from a floating point value to an integer value.
11635 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11636                                     SourceLocation CContext) {
11637   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11638   const bool PruneWarnings = S.inTemplateInstantiation();
11639 
11640   Expr *InnerE = E->IgnoreParenImpCasts();
11641   // We also want to warn on, e.g., "int i = -1.234"
11642   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11643     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11644       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11645 
11646   const bool IsLiteral =
11647       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11648 
11649   llvm::APFloat Value(0.0);
11650   bool IsConstant =
11651     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11652   if (!IsConstant) {
11653     if (isObjCSignedCharBool(S, T)) {
11654       return adornObjCBoolConversionDiagWithTernaryFixit(
11655           S, E,
11656           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11657               << E->getType());
11658     }
11659 
11660     return DiagnoseImpCast(S, E, T, CContext,
11661                            diag::warn_impcast_float_integer, PruneWarnings);
11662   }
11663 
11664   bool isExact = false;
11665 
11666   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11667                             T->hasUnsignedIntegerRepresentation());
11668   llvm::APFloat::opStatus Result = Value.convertToInteger(
11669       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11670 
11671   // FIXME: Force the precision of the source value down so we don't print
11672   // digits which are usually useless (we don't really care here if we
11673   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11674   // would automatically print the shortest representation, but it's a bit
11675   // tricky to implement.
11676   SmallString<16> PrettySourceValue;
11677   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11678   precision = (precision * 59 + 195) / 196;
11679   Value.toString(PrettySourceValue, precision);
11680 
11681   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11682     return adornObjCBoolConversionDiagWithTernaryFixit(
11683         S, E,
11684         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11685             << PrettySourceValue);
11686   }
11687 
11688   if (Result == llvm::APFloat::opOK && isExact) {
11689     if (IsLiteral) return;
11690     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11691                            PruneWarnings);
11692   }
11693 
11694   // Conversion of a floating-point value to a non-bool integer where the
11695   // integral part cannot be represented by the integer type is undefined.
11696   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11697     return DiagnoseImpCast(
11698         S, E, T, CContext,
11699         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11700                   : diag::warn_impcast_float_to_integer_out_of_range,
11701         PruneWarnings);
11702 
11703   unsigned DiagID = 0;
11704   if (IsLiteral) {
11705     // Warn on floating point literal to integer.
11706     DiagID = diag::warn_impcast_literal_float_to_integer;
11707   } else if (IntegerValue == 0) {
11708     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11709       return DiagnoseImpCast(S, E, T, CContext,
11710                              diag::warn_impcast_float_integer, PruneWarnings);
11711     }
11712     // Warn on non-zero to zero conversion.
11713     DiagID = diag::warn_impcast_float_to_integer_zero;
11714   } else {
11715     if (IntegerValue.isUnsigned()) {
11716       if (!IntegerValue.isMaxValue()) {
11717         return DiagnoseImpCast(S, E, T, CContext,
11718                                diag::warn_impcast_float_integer, PruneWarnings);
11719       }
11720     } else {  // IntegerValue.isSigned()
11721       if (!IntegerValue.isMaxSignedValue() &&
11722           !IntegerValue.isMinSignedValue()) {
11723         return DiagnoseImpCast(S, E, T, CContext,
11724                                diag::warn_impcast_float_integer, PruneWarnings);
11725       }
11726     }
11727     // Warn on evaluatable floating point expression to integer conversion.
11728     DiagID = diag::warn_impcast_float_to_integer;
11729   }
11730 
11731   SmallString<16> PrettyTargetValue;
11732   if (IsBool)
11733     PrettyTargetValue = Value.isZero() ? "false" : "true";
11734   else
11735     IntegerValue.toString(PrettyTargetValue);
11736 
11737   if (PruneWarnings) {
11738     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11739                           S.PDiag(DiagID)
11740                               << E->getType() << T.getUnqualifiedType()
11741                               << PrettySourceValue << PrettyTargetValue
11742                               << E->getSourceRange() << SourceRange(CContext));
11743   } else {
11744     S.Diag(E->getExprLoc(), DiagID)
11745         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11746         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11747   }
11748 }
11749 
11750 /// Analyze the given compound assignment for the possible losing of
11751 /// floating-point precision.
11752 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11753   assert(isa<CompoundAssignOperator>(E) &&
11754          "Must be compound assignment operation");
11755   // Recurse on the LHS and RHS in here
11756   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11757   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11758 
11759   if (E->getLHS()->getType()->isAtomicType())
11760     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11761 
11762   // Now check the outermost expression
11763   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11764   const auto *RBT = cast<CompoundAssignOperator>(E)
11765                         ->getComputationResultType()
11766                         ->getAs<BuiltinType>();
11767 
11768   // The below checks assume source is floating point.
11769   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11770 
11771   // If source is floating point but target is an integer.
11772   if (ResultBT->isInteger())
11773     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11774                            E->getExprLoc(), diag::warn_impcast_float_integer);
11775 
11776   if (!ResultBT->isFloatingPoint())
11777     return;
11778 
11779   // If both source and target are floating points, warn about losing precision.
11780   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11781       QualType(ResultBT, 0), QualType(RBT, 0));
11782   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11783     // warn about dropping FP rank.
11784     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11785                     diag::warn_impcast_float_result_precision);
11786 }
11787 
11788 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11789                                       IntRange Range) {
11790   if (!Range.Width) return "0";
11791 
11792   llvm::APSInt ValueInRange = Value;
11793   ValueInRange.setIsSigned(!Range.NonNegative);
11794   ValueInRange = ValueInRange.trunc(Range.Width);
11795   return ValueInRange.toString(10);
11796 }
11797 
11798 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11799   if (!isa<ImplicitCastExpr>(Ex))
11800     return false;
11801 
11802   Expr *InnerE = Ex->IgnoreParenImpCasts();
11803   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11804   const Type *Source =
11805     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11806   if (Target->isDependentType())
11807     return false;
11808 
11809   const BuiltinType *FloatCandidateBT =
11810     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11811   const Type *BoolCandidateType = ToBool ? Target : Source;
11812 
11813   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11814           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11815 }
11816 
11817 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11818                                              SourceLocation CC) {
11819   unsigned NumArgs = TheCall->getNumArgs();
11820   for (unsigned i = 0; i < NumArgs; ++i) {
11821     Expr *CurrA = TheCall->getArg(i);
11822     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11823       continue;
11824 
11825     bool IsSwapped = ((i > 0) &&
11826         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11827     IsSwapped |= ((i < (NumArgs - 1)) &&
11828         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11829     if (IsSwapped) {
11830       // Warn on this floating-point to bool conversion.
11831       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11832                       CurrA->getType(), CC,
11833                       diag::warn_impcast_floating_point_to_bool);
11834     }
11835   }
11836 }
11837 
11838 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11839                                    SourceLocation CC) {
11840   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11841                         E->getExprLoc()))
11842     return;
11843 
11844   // Don't warn on functions which have return type nullptr_t.
11845   if (isa<CallExpr>(E))
11846     return;
11847 
11848   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11849   const Expr::NullPointerConstantKind NullKind =
11850       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11851   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11852     return;
11853 
11854   // Return if target type is a safe conversion.
11855   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11856       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11857     return;
11858 
11859   SourceLocation Loc = E->getSourceRange().getBegin();
11860 
11861   // Venture through the macro stacks to get to the source of macro arguments.
11862   // The new location is a better location than the complete location that was
11863   // passed in.
11864   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11865   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11866 
11867   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11868   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11869     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11870         Loc, S.SourceMgr, S.getLangOpts());
11871     if (MacroName == "NULL")
11872       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11873   }
11874 
11875   // Only warn if the null and context location are in the same macro expansion.
11876   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11877     return;
11878 
11879   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11880       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11881       << FixItHint::CreateReplacement(Loc,
11882                                       S.getFixItZeroLiteralForType(T, Loc));
11883 }
11884 
11885 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11886                                   ObjCArrayLiteral *ArrayLiteral);
11887 
11888 static void
11889 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11890                            ObjCDictionaryLiteral *DictionaryLiteral);
11891 
11892 /// Check a single element within a collection literal against the
11893 /// target element type.
11894 static void checkObjCCollectionLiteralElement(Sema &S,
11895                                               QualType TargetElementType,
11896                                               Expr *Element,
11897                                               unsigned ElementKind) {
11898   // Skip a bitcast to 'id' or qualified 'id'.
11899   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11900     if (ICE->getCastKind() == CK_BitCast &&
11901         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11902       Element = ICE->getSubExpr();
11903   }
11904 
11905   QualType ElementType = Element->getType();
11906   ExprResult ElementResult(Element);
11907   if (ElementType->getAs<ObjCObjectPointerType>() &&
11908       S.CheckSingleAssignmentConstraints(TargetElementType,
11909                                          ElementResult,
11910                                          false, false)
11911         != Sema::Compatible) {
11912     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11913         << ElementType << ElementKind << TargetElementType
11914         << Element->getSourceRange();
11915   }
11916 
11917   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11918     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11919   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11920     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11921 }
11922 
11923 /// Check an Objective-C array literal being converted to the given
11924 /// target type.
11925 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11926                                   ObjCArrayLiteral *ArrayLiteral) {
11927   if (!S.NSArrayDecl)
11928     return;
11929 
11930   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11931   if (!TargetObjCPtr)
11932     return;
11933 
11934   if (TargetObjCPtr->isUnspecialized() ||
11935       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11936         != S.NSArrayDecl->getCanonicalDecl())
11937     return;
11938 
11939   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11940   if (TypeArgs.size() != 1)
11941     return;
11942 
11943   QualType TargetElementType = TypeArgs[0];
11944   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11945     checkObjCCollectionLiteralElement(S, TargetElementType,
11946                                       ArrayLiteral->getElement(I),
11947                                       0);
11948   }
11949 }
11950 
11951 /// Check an Objective-C dictionary literal being converted to the given
11952 /// target type.
11953 static void
11954 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11955                            ObjCDictionaryLiteral *DictionaryLiteral) {
11956   if (!S.NSDictionaryDecl)
11957     return;
11958 
11959   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11960   if (!TargetObjCPtr)
11961     return;
11962 
11963   if (TargetObjCPtr->isUnspecialized() ||
11964       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11965         != S.NSDictionaryDecl->getCanonicalDecl())
11966     return;
11967 
11968   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11969   if (TypeArgs.size() != 2)
11970     return;
11971 
11972   QualType TargetKeyType = TypeArgs[0];
11973   QualType TargetObjectType = TypeArgs[1];
11974   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11975     auto Element = DictionaryLiteral->getKeyValueElement(I);
11976     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11977     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11978   }
11979 }
11980 
11981 // Helper function to filter out cases for constant width constant conversion.
11982 // Don't warn on char array initialization or for non-decimal values.
11983 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11984                                           SourceLocation CC) {
11985   // If initializing from a constant, and the constant starts with '0',
11986   // then it is a binary, octal, or hexadecimal.  Allow these constants
11987   // to fill all the bits, even if there is a sign change.
11988   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11989     const char FirstLiteralCharacter =
11990         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11991     if (FirstLiteralCharacter == '0')
11992       return false;
11993   }
11994 
11995   // If the CC location points to a '{', and the type is char, then assume
11996   // assume it is an array initialization.
11997   if (CC.isValid() && T->isCharType()) {
11998     const char FirstContextCharacter =
11999         S.getSourceManager().getCharacterData(CC)[0];
12000     if (FirstContextCharacter == '{')
12001       return false;
12002   }
12003 
12004   return true;
12005 }
12006 
12007 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12008   const auto *IL = dyn_cast<IntegerLiteral>(E);
12009   if (!IL) {
12010     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12011       if (UO->getOpcode() == UO_Minus)
12012         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12013     }
12014   }
12015 
12016   return IL;
12017 }
12018 
12019 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12020   E = E->IgnoreParenImpCasts();
12021   SourceLocation ExprLoc = E->getExprLoc();
12022 
12023   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12024     BinaryOperator::Opcode Opc = BO->getOpcode();
12025     Expr::EvalResult Result;
12026     // Do not diagnose unsigned shifts.
12027     if (Opc == BO_Shl) {
12028       const auto *LHS = getIntegerLiteral(BO->getLHS());
12029       const auto *RHS = getIntegerLiteral(BO->getRHS());
12030       if (LHS && LHS->getValue() == 0)
12031         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12032       else if (!E->isValueDependent() && LHS && RHS &&
12033                RHS->getValue().isNonNegative() &&
12034                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12035         S.Diag(ExprLoc, diag::warn_left_shift_always)
12036             << (Result.Val.getInt() != 0);
12037       else if (E->getType()->isSignedIntegerType())
12038         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12039     }
12040   }
12041 
12042   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12043     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12044     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12045     if (!LHS || !RHS)
12046       return;
12047     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12048         (RHS->getValue() == 0 || RHS->getValue() == 1))
12049       // Do not diagnose common idioms.
12050       return;
12051     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12052       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12053   }
12054 }
12055 
12056 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12057                                     SourceLocation CC,
12058                                     bool *ICContext = nullptr,
12059                                     bool IsListInit = false) {
12060   if (E->isTypeDependent() || E->isValueDependent()) return;
12061 
12062   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12063   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12064   if (Source == Target) return;
12065   if (Target->isDependentType()) return;
12066 
12067   // If the conversion context location is invalid don't complain. We also
12068   // don't want to emit a warning if the issue occurs from the expansion of
12069   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12070   // delay this check as long as possible. Once we detect we are in that
12071   // scenario, we just return.
12072   if (CC.isInvalid())
12073     return;
12074 
12075   if (Source->isAtomicType())
12076     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12077 
12078   // Diagnose implicit casts to bool.
12079   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12080     if (isa<StringLiteral>(E))
12081       // Warn on string literal to bool.  Checks for string literals in logical
12082       // and expressions, for instance, assert(0 && "error here"), are
12083       // prevented by a check in AnalyzeImplicitConversions().
12084       return DiagnoseImpCast(S, E, T, CC,
12085                              diag::warn_impcast_string_literal_to_bool);
12086     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12087         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12088       // This covers the literal expressions that evaluate to Objective-C
12089       // objects.
12090       return DiagnoseImpCast(S, E, T, CC,
12091                              diag::warn_impcast_objective_c_literal_to_bool);
12092     }
12093     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12094       // Warn on pointer to bool conversion that is always true.
12095       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12096                                      SourceRange(CC));
12097     }
12098   }
12099 
12100   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12101   // is a typedef for signed char (macOS), then that constant value has to be 1
12102   // or 0.
12103   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12104     Expr::EvalResult Result;
12105     if (E->EvaluateAsInt(Result, S.getASTContext(),
12106                          Expr::SE_AllowSideEffects)) {
12107       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12108         adornObjCBoolConversionDiagWithTernaryFixit(
12109             S, E,
12110             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12111                 << Result.Val.getInt().toString(10));
12112       }
12113       return;
12114     }
12115   }
12116 
12117   // Check implicit casts from Objective-C collection literals to specialized
12118   // collection types, e.g., NSArray<NSString *> *.
12119   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12120     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12121   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12122     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12123 
12124   // Strip vector types.
12125   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12126     if (Target->isVLSTBuiltinType()) {
12127       auto SourceVectorKind = SourceVT->getVectorKind();
12128       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12129           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12130           (SourceVectorKind == VectorType::GenericVector &&
12131            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12132         return;
12133     }
12134 
12135     if (!isa<VectorType>(Target)) {
12136       if (S.SourceMgr.isInSystemMacro(CC))
12137         return;
12138       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12139     }
12140 
12141     // If the vector cast is cast between two vectors of the same size, it is
12142     // a bitcast, not a conversion.
12143     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12144       return;
12145 
12146     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12147     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12148   }
12149   if (auto VecTy = dyn_cast<VectorType>(Target))
12150     Target = VecTy->getElementType().getTypePtr();
12151 
12152   // Strip complex types.
12153   if (isa<ComplexType>(Source)) {
12154     if (!isa<ComplexType>(Target)) {
12155       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12156         return;
12157 
12158       return DiagnoseImpCast(S, E, T, CC,
12159                              S.getLangOpts().CPlusPlus
12160                                  ? diag::err_impcast_complex_scalar
12161                                  : diag::warn_impcast_complex_scalar);
12162     }
12163 
12164     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12165     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12166   }
12167 
12168   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12169   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12170 
12171   // If the source is floating point...
12172   if (SourceBT && SourceBT->isFloatingPoint()) {
12173     // ...and the target is floating point...
12174     if (TargetBT && TargetBT->isFloatingPoint()) {
12175       // ...then warn if we're dropping FP rank.
12176 
12177       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12178           QualType(SourceBT, 0), QualType(TargetBT, 0));
12179       if (Order > 0) {
12180         // Don't warn about float constants that are precisely
12181         // representable in the target type.
12182         Expr::EvalResult result;
12183         if (E->EvaluateAsRValue(result, S.Context)) {
12184           // Value might be a float, a float vector, or a float complex.
12185           if (IsSameFloatAfterCast(result.Val,
12186                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12187                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12188             return;
12189         }
12190 
12191         if (S.SourceMgr.isInSystemMacro(CC))
12192           return;
12193 
12194         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12195       }
12196       // ... or possibly if we're increasing rank, too
12197       else if (Order < 0) {
12198         if (S.SourceMgr.isInSystemMacro(CC))
12199           return;
12200 
12201         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12202       }
12203       return;
12204     }
12205 
12206     // If the target is integral, always warn.
12207     if (TargetBT && TargetBT->isInteger()) {
12208       if (S.SourceMgr.isInSystemMacro(CC))
12209         return;
12210 
12211       DiagnoseFloatingImpCast(S, E, T, CC);
12212     }
12213 
12214     // Detect the case where a call result is converted from floating-point to
12215     // to bool, and the final argument to the call is converted from bool, to
12216     // discover this typo:
12217     //
12218     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12219     //
12220     // FIXME: This is an incredibly special case; is there some more general
12221     // way to detect this class of misplaced-parentheses bug?
12222     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12223       // Check last argument of function call to see if it is an
12224       // implicit cast from a type matching the type the result
12225       // is being cast to.
12226       CallExpr *CEx = cast<CallExpr>(E);
12227       if (unsigned NumArgs = CEx->getNumArgs()) {
12228         Expr *LastA = CEx->getArg(NumArgs - 1);
12229         Expr *InnerE = LastA->IgnoreParenImpCasts();
12230         if (isa<ImplicitCastExpr>(LastA) &&
12231             InnerE->getType()->isBooleanType()) {
12232           // Warn on this floating-point to bool conversion
12233           DiagnoseImpCast(S, E, T, CC,
12234                           diag::warn_impcast_floating_point_to_bool);
12235         }
12236       }
12237     }
12238     return;
12239   }
12240 
12241   // Valid casts involving fixed point types should be accounted for here.
12242   if (Source->isFixedPointType()) {
12243     if (Target->isUnsaturatedFixedPointType()) {
12244       Expr::EvalResult Result;
12245       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12246                                   S.isConstantEvaluated())) {
12247         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12248         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12249         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12250         if (Value > MaxVal || Value < MinVal) {
12251           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12252                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12253                                     << Value.toString() << T
12254                                     << E->getSourceRange()
12255                                     << clang::SourceRange(CC));
12256           return;
12257         }
12258       }
12259     } else if (Target->isIntegerType()) {
12260       Expr::EvalResult Result;
12261       if (!S.isConstantEvaluated() &&
12262           E->EvaluateAsFixedPoint(Result, S.Context,
12263                                   Expr::SE_AllowSideEffects)) {
12264         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12265 
12266         bool Overflowed;
12267         llvm::APSInt IntResult = FXResult.convertToInt(
12268             S.Context.getIntWidth(T),
12269             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12270 
12271         if (Overflowed) {
12272           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12273                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12274                                     << FXResult.toString() << T
12275                                     << E->getSourceRange()
12276                                     << clang::SourceRange(CC));
12277           return;
12278         }
12279       }
12280     }
12281   } else if (Target->isUnsaturatedFixedPointType()) {
12282     if (Source->isIntegerType()) {
12283       Expr::EvalResult Result;
12284       if (!S.isConstantEvaluated() &&
12285           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12286         llvm::APSInt Value = Result.Val.getInt();
12287 
12288         bool Overflowed;
12289         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12290             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12291 
12292         if (Overflowed) {
12293           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12294                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12295                                     << Value.toString(/*Radix=*/10) << T
12296                                     << E->getSourceRange()
12297                                     << clang::SourceRange(CC));
12298           return;
12299         }
12300       }
12301     }
12302   }
12303 
12304   // If we are casting an integer type to a floating point type without
12305   // initialization-list syntax, we might lose accuracy if the floating
12306   // point type has a narrower significand than the integer type.
12307   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12308       TargetBT->isFloatingType() && !IsListInit) {
12309     // Determine the number of precision bits in the source integer type.
12310     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12311                                         /*Approximate*/ true);
12312     unsigned int SourcePrecision = SourceRange.Width;
12313 
12314     // Determine the number of precision bits in the
12315     // target floating point type.
12316     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12317         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12318 
12319     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12320         SourcePrecision > TargetPrecision) {
12321 
12322       if (Optional<llvm::APSInt> SourceInt =
12323               E->getIntegerConstantExpr(S.Context)) {
12324         // If the source integer is a constant, convert it to the target
12325         // floating point type. Issue a warning if the value changes
12326         // during the whole conversion.
12327         llvm::APFloat TargetFloatValue(
12328             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12329         llvm::APFloat::opStatus ConversionStatus =
12330             TargetFloatValue.convertFromAPInt(
12331                 *SourceInt, SourceBT->isSignedInteger(),
12332                 llvm::APFloat::rmNearestTiesToEven);
12333 
12334         if (ConversionStatus != llvm::APFloat::opOK) {
12335           std::string PrettySourceValue = SourceInt->toString(10);
12336           SmallString<32> PrettyTargetValue;
12337           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12338 
12339           S.DiagRuntimeBehavior(
12340               E->getExprLoc(), E,
12341               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12342                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12343                   << E->getSourceRange() << clang::SourceRange(CC));
12344         }
12345       } else {
12346         // Otherwise, the implicit conversion may lose precision.
12347         DiagnoseImpCast(S, E, T, CC,
12348                         diag::warn_impcast_integer_float_precision);
12349       }
12350     }
12351   }
12352 
12353   DiagnoseNullConversion(S, E, T, CC);
12354 
12355   S.DiscardMisalignedMemberAddress(Target, E);
12356 
12357   if (Target->isBooleanType())
12358     DiagnoseIntInBoolContext(S, E);
12359 
12360   if (!Source->isIntegerType() || !Target->isIntegerType())
12361     return;
12362 
12363   // TODO: remove this early return once the false positives for constant->bool
12364   // in templates, macros, etc, are reduced or removed.
12365   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12366     return;
12367 
12368   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12369       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12370     return adornObjCBoolConversionDiagWithTernaryFixit(
12371         S, E,
12372         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12373             << E->getType());
12374   }
12375 
12376   IntRange SourceTypeRange =
12377       IntRange::forTargetOfCanonicalType(S.Context, Source);
12378   IntRange LikelySourceRange =
12379       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12380   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12381 
12382   if (LikelySourceRange.Width > TargetRange.Width) {
12383     // If the source is a constant, use a default-on diagnostic.
12384     // TODO: this should happen for bitfield stores, too.
12385     Expr::EvalResult Result;
12386     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12387                          S.isConstantEvaluated())) {
12388       llvm::APSInt Value(32);
12389       Value = Result.Val.getInt();
12390 
12391       if (S.SourceMgr.isInSystemMacro(CC))
12392         return;
12393 
12394       std::string PrettySourceValue = Value.toString(10);
12395       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12396 
12397       S.DiagRuntimeBehavior(
12398           E->getExprLoc(), E,
12399           S.PDiag(diag::warn_impcast_integer_precision_constant)
12400               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12401               << E->getSourceRange() << SourceRange(CC));
12402       return;
12403     }
12404 
12405     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12406     if (S.SourceMgr.isInSystemMacro(CC))
12407       return;
12408 
12409     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12410       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12411                              /* pruneControlFlow */ true);
12412     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12413   }
12414 
12415   if (TargetRange.Width > SourceTypeRange.Width) {
12416     if (auto *UO = dyn_cast<UnaryOperator>(E))
12417       if (UO->getOpcode() == UO_Minus)
12418         if (Source->isUnsignedIntegerType()) {
12419           if (Target->isUnsignedIntegerType())
12420             return DiagnoseImpCast(S, E, T, CC,
12421                                    diag::warn_impcast_high_order_zero_bits);
12422           if (Target->isSignedIntegerType())
12423             return DiagnoseImpCast(S, E, T, CC,
12424                                    diag::warn_impcast_nonnegative_result);
12425         }
12426   }
12427 
12428   if (TargetRange.Width == LikelySourceRange.Width &&
12429       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12430       Source->isSignedIntegerType()) {
12431     // Warn when doing a signed to signed conversion, warn if the positive
12432     // source value is exactly the width of the target type, which will
12433     // cause a negative value to be stored.
12434 
12435     Expr::EvalResult Result;
12436     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12437         !S.SourceMgr.isInSystemMacro(CC)) {
12438       llvm::APSInt Value = Result.Val.getInt();
12439       if (isSameWidthConstantConversion(S, E, T, CC)) {
12440         std::string PrettySourceValue = Value.toString(10);
12441         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12442 
12443         S.DiagRuntimeBehavior(
12444             E->getExprLoc(), E,
12445             S.PDiag(diag::warn_impcast_integer_precision_constant)
12446                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12447                 << E->getSourceRange() << SourceRange(CC));
12448         return;
12449       }
12450     }
12451 
12452     // Fall through for non-constants to give a sign conversion warning.
12453   }
12454 
12455   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12456       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12457        LikelySourceRange.Width == TargetRange.Width)) {
12458     if (S.SourceMgr.isInSystemMacro(CC))
12459       return;
12460 
12461     unsigned DiagID = diag::warn_impcast_integer_sign;
12462 
12463     // Traditionally, gcc has warned about this under -Wsign-compare.
12464     // We also want to warn about it in -Wconversion.
12465     // So if -Wconversion is off, use a completely identical diagnostic
12466     // in the sign-compare group.
12467     // The conditional-checking code will
12468     if (ICContext) {
12469       DiagID = diag::warn_impcast_integer_sign_conditional;
12470       *ICContext = true;
12471     }
12472 
12473     return DiagnoseImpCast(S, E, T, CC, DiagID);
12474   }
12475 
12476   // Diagnose conversions between different enumeration types.
12477   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12478   // type, to give us better diagnostics.
12479   QualType SourceType = E->getType();
12480   if (!S.getLangOpts().CPlusPlus) {
12481     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12482       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12483         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12484         SourceType = S.Context.getTypeDeclType(Enum);
12485         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12486       }
12487   }
12488 
12489   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12490     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12491       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12492           TargetEnum->getDecl()->hasNameForLinkage() &&
12493           SourceEnum != TargetEnum) {
12494         if (S.SourceMgr.isInSystemMacro(CC))
12495           return;
12496 
12497         return DiagnoseImpCast(S, E, SourceType, T, CC,
12498                                diag::warn_impcast_different_enum_types);
12499       }
12500 }
12501 
12502 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12503                                      SourceLocation CC, QualType T);
12504 
12505 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12506                                     SourceLocation CC, bool &ICContext) {
12507   E = E->IgnoreParenImpCasts();
12508 
12509   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12510     return CheckConditionalOperator(S, CO, CC, T);
12511 
12512   AnalyzeImplicitConversions(S, E, CC);
12513   if (E->getType() != T)
12514     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12515 }
12516 
12517 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12518                                      SourceLocation CC, QualType T) {
12519   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12520 
12521   Expr *TrueExpr = E->getTrueExpr();
12522   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12523     TrueExpr = BCO->getCommon();
12524 
12525   bool Suspicious = false;
12526   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12527   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12528 
12529   if (T->isBooleanType())
12530     DiagnoseIntInBoolContext(S, E);
12531 
12532   // If -Wconversion would have warned about either of the candidates
12533   // for a signedness conversion to the context type...
12534   if (!Suspicious) return;
12535 
12536   // ...but it's currently ignored...
12537   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12538     return;
12539 
12540   // ...then check whether it would have warned about either of the
12541   // candidates for a signedness conversion to the condition type.
12542   if (E->getType() == T) return;
12543 
12544   Suspicious = false;
12545   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12546                           E->getType(), CC, &Suspicious);
12547   if (!Suspicious)
12548     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12549                             E->getType(), CC, &Suspicious);
12550 }
12551 
12552 /// Check conversion of given expression to boolean.
12553 /// Input argument E is a logical expression.
12554 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12555   if (S.getLangOpts().Bool)
12556     return;
12557   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12558     return;
12559   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12560 }
12561 
12562 namespace {
12563 struct AnalyzeImplicitConversionsWorkItem {
12564   Expr *E;
12565   SourceLocation CC;
12566   bool IsListInit;
12567 };
12568 }
12569 
12570 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12571 /// that should be visited are added to WorkList.
12572 static void AnalyzeImplicitConversions(
12573     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12574     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12575   Expr *OrigE = Item.E;
12576   SourceLocation CC = Item.CC;
12577 
12578   QualType T = OrigE->getType();
12579   Expr *E = OrigE->IgnoreParenImpCasts();
12580 
12581   // Propagate whether we are in a C++ list initialization expression.
12582   // If so, we do not issue warnings for implicit int-float conversion
12583   // precision loss, because C++11 narrowing already handles it.
12584   bool IsListInit = Item.IsListInit ||
12585                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12586 
12587   if (E->isTypeDependent() || E->isValueDependent())
12588     return;
12589 
12590   Expr *SourceExpr = E;
12591   // Examine, but don't traverse into the source expression of an
12592   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12593   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12594   // evaluate it in the context of checking the specific conversion to T though.
12595   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12596     if (auto *Src = OVE->getSourceExpr())
12597       SourceExpr = Src;
12598 
12599   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12600     if (UO->getOpcode() == UO_Not &&
12601         UO->getSubExpr()->isKnownToHaveBooleanValue())
12602       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12603           << OrigE->getSourceRange() << T->isBooleanType()
12604           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12605 
12606   // For conditional operators, we analyze the arguments as if they
12607   // were being fed directly into the output.
12608   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12609     CheckConditionalOperator(S, CO, CC, T);
12610     return;
12611   }
12612 
12613   // Check implicit argument conversions for function calls.
12614   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12615     CheckImplicitArgumentConversions(S, Call, CC);
12616 
12617   // Go ahead and check any implicit conversions we might have skipped.
12618   // The non-canonical typecheck is just an optimization;
12619   // CheckImplicitConversion will filter out dead implicit conversions.
12620   if (SourceExpr->getType() != T)
12621     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12622 
12623   // Now continue drilling into this expression.
12624 
12625   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12626     // The bound subexpressions in a PseudoObjectExpr are not reachable
12627     // as transitive children.
12628     // FIXME: Use a more uniform representation for this.
12629     for (auto *SE : POE->semantics())
12630       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12631         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12632   }
12633 
12634   // Skip past explicit casts.
12635   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12636     E = CE->getSubExpr()->IgnoreParenImpCasts();
12637     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12638       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12639     WorkList.push_back({E, CC, IsListInit});
12640     return;
12641   }
12642 
12643   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12644     // Do a somewhat different check with comparison operators.
12645     if (BO->isComparisonOp())
12646       return AnalyzeComparison(S, BO);
12647 
12648     // And with simple assignments.
12649     if (BO->getOpcode() == BO_Assign)
12650       return AnalyzeAssignment(S, BO);
12651     // And with compound assignments.
12652     if (BO->isAssignmentOp())
12653       return AnalyzeCompoundAssignment(S, BO);
12654   }
12655 
12656   // These break the otherwise-useful invariant below.  Fortunately,
12657   // we don't really need to recurse into them, because any internal
12658   // expressions should have been analyzed already when they were
12659   // built into statements.
12660   if (isa<StmtExpr>(E)) return;
12661 
12662   // Don't descend into unevaluated contexts.
12663   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12664 
12665   // Now just recurse over the expression's children.
12666   CC = E->getExprLoc();
12667   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12668   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12669   for (Stmt *SubStmt : E->children()) {
12670     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12671     if (!ChildExpr)
12672       continue;
12673 
12674     if (IsLogicalAndOperator &&
12675         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12676       // Ignore checking string literals that are in logical and operators.
12677       // This is a common pattern for asserts.
12678       continue;
12679     WorkList.push_back({ChildExpr, CC, IsListInit});
12680   }
12681 
12682   if (BO && BO->isLogicalOp()) {
12683     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12684     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12685       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12686 
12687     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12688     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12689       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12690   }
12691 
12692   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12693     if (U->getOpcode() == UO_LNot) {
12694       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12695     } else if (U->getOpcode() != UO_AddrOf) {
12696       if (U->getSubExpr()->getType()->isAtomicType())
12697         S.Diag(U->getSubExpr()->getBeginLoc(),
12698                diag::warn_atomic_implicit_seq_cst);
12699     }
12700   }
12701 }
12702 
12703 /// AnalyzeImplicitConversions - Find and report any interesting
12704 /// implicit conversions in the given expression.  There are a couple
12705 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12706 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12707                                        bool IsListInit/*= false*/) {
12708   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12709   WorkList.push_back({OrigE, CC, IsListInit});
12710   while (!WorkList.empty())
12711     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12712 }
12713 
12714 /// Diagnose integer type and any valid implicit conversion to it.
12715 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12716   // Taking into account implicit conversions,
12717   // allow any integer.
12718   if (!E->getType()->isIntegerType()) {
12719     S.Diag(E->getBeginLoc(),
12720            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12721     return true;
12722   }
12723   // Potentially emit standard warnings for implicit conversions if enabled
12724   // using -Wconversion.
12725   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12726   return false;
12727 }
12728 
12729 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12730 // Returns true when emitting a warning about taking the address of a reference.
12731 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12732                               const PartialDiagnostic &PD) {
12733   E = E->IgnoreParenImpCasts();
12734 
12735   const FunctionDecl *FD = nullptr;
12736 
12737   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12738     if (!DRE->getDecl()->getType()->isReferenceType())
12739       return false;
12740   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12741     if (!M->getMemberDecl()->getType()->isReferenceType())
12742       return false;
12743   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12744     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12745       return false;
12746     FD = Call->getDirectCallee();
12747   } else {
12748     return false;
12749   }
12750 
12751   SemaRef.Diag(E->getExprLoc(), PD);
12752 
12753   // If possible, point to location of function.
12754   if (FD) {
12755     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12756   }
12757 
12758   return true;
12759 }
12760 
12761 // Returns true if the SourceLocation is expanded from any macro body.
12762 // Returns false if the SourceLocation is invalid, is from not in a macro
12763 // expansion, or is from expanded from a top-level macro argument.
12764 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12765   if (Loc.isInvalid())
12766     return false;
12767 
12768   while (Loc.isMacroID()) {
12769     if (SM.isMacroBodyExpansion(Loc))
12770       return true;
12771     Loc = SM.getImmediateMacroCallerLoc(Loc);
12772   }
12773 
12774   return false;
12775 }
12776 
12777 /// Diagnose pointers that are always non-null.
12778 /// \param E the expression containing the pointer
12779 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12780 /// compared to a null pointer
12781 /// \param IsEqual True when the comparison is equal to a null pointer
12782 /// \param Range Extra SourceRange to highlight in the diagnostic
12783 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12784                                         Expr::NullPointerConstantKind NullKind,
12785                                         bool IsEqual, SourceRange Range) {
12786   if (!E)
12787     return;
12788 
12789   // Don't warn inside macros.
12790   if (E->getExprLoc().isMacroID()) {
12791     const SourceManager &SM = getSourceManager();
12792     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12793         IsInAnyMacroBody(SM, Range.getBegin()))
12794       return;
12795   }
12796   E = E->IgnoreImpCasts();
12797 
12798   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12799 
12800   if (isa<CXXThisExpr>(E)) {
12801     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12802                                 : diag::warn_this_bool_conversion;
12803     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12804     return;
12805   }
12806 
12807   bool IsAddressOf = false;
12808 
12809   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12810     if (UO->getOpcode() != UO_AddrOf)
12811       return;
12812     IsAddressOf = true;
12813     E = UO->getSubExpr();
12814   }
12815 
12816   if (IsAddressOf) {
12817     unsigned DiagID = IsCompare
12818                           ? diag::warn_address_of_reference_null_compare
12819                           : diag::warn_address_of_reference_bool_conversion;
12820     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12821                                          << IsEqual;
12822     if (CheckForReference(*this, E, PD)) {
12823       return;
12824     }
12825   }
12826 
12827   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12828     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12829     std::string Str;
12830     llvm::raw_string_ostream S(Str);
12831     E->printPretty(S, nullptr, getPrintingPolicy());
12832     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12833                                 : diag::warn_cast_nonnull_to_bool;
12834     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12835       << E->getSourceRange() << Range << IsEqual;
12836     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12837   };
12838 
12839   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12840   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12841     if (auto *Callee = Call->getDirectCallee()) {
12842       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12843         ComplainAboutNonnullParamOrCall(A);
12844         return;
12845       }
12846     }
12847   }
12848 
12849   // Expect to find a single Decl.  Skip anything more complicated.
12850   ValueDecl *D = nullptr;
12851   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12852     D = R->getDecl();
12853   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12854     D = M->getMemberDecl();
12855   }
12856 
12857   // Weak Decls can be null.
12858   if (!D || D->isWeak())
12859     return;
12860 
12861   // Check for parameter decl with nonnull attribute
12862   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12863     if (getCurFunction() &&
12864         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12865       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12866         ComplainAboutNonnullParamOrCall(A);
12867         return;
12868       }
12869 
12870       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12871         // Skip function template not specialized yet.
12872         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12873           return;
12874         auto ParamIter = llvm::find(FD->parameters(), PV);
12875         assert(ParamIter != FD->param_end());
12876         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12877 
12878         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12879           if (!NonNull->args_size()) {
12880               ComplainAboutNonnullParamOrCall(NonNull);
12881               return;
12882           }
12883 
12884           for (const ParamIdx &ArgNo : NonNull->args()) {
12885             if (ArgNo.getASTIndex() == ParamNo) {
12886               ComplainAboutNonnullParamOrCall(NonNull);
12887               return;
12888             }
12889           }
12890         }
12891       }
12892     }
12893   }
12894 
12895   QualType T = D->getType();
12896   const bool IsArray = T->isArrayType();
12897   const bool IsFunction = T->isFunctionType();
12898 
12899   // Address of function is used to silence the function warning.
12900   if (IsAddressOf && IsFunction) {
12901     return;
12902   }
12903 
12904   // Found nothing.
12905   if (!IsAddressOf && !IsFunction && !IsArray)
12906     return;
12907 
12908   // Pretty print the expression for the diagnostic.
12909   std::string Str;
12910   llvm::raw_string_ostream S(Str);
12911   E->printPretty(S, nullptr, getPrintingPolicy());
12912 
12913   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12914                               : diag::warn_impcast_pointer_to_bool;
12915   enum {
12916     AddressOf,
12917     FunctionPointer,
12918     ArrayPointer
12919   } DiagType;
12920   if (IsAddressOf)
12921     DiagType = AddressOf;
12922   else if (IsFunction)
12923     DiagType = FunctionPointer;
12924   else if (IsArray)
12925     DiagType = ArrayPointer;
12926   else
12927     llvm_unreachable("Could not determine diagnostic.");
12928   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12929                                 << Range << IsEqual;
12930 
12931   if (!IsFunction)
12932     return;
12933 
12934   // Suggest '&' to silence the function warning.
12935   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12936       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12937 
12938   // Check to see if '()' fixit should be emitted.
12939   QualType ReturnType;
12940   UnresolvedSet<4> NonTemplateOverloads;
12941   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12942   if (ReturnType.isNull())
12943     return;
12944 
12945   if (IsCompare) {
12946     // There are two cases here.  If there is null constant, the only suggest
12947     // for a pointer return type.  If the null is 0, then suggest if the return
12948     // type is a pointer or an integer type.
12949     if (!ReturnType->isPointerType()) {
12950       if (NullKind == Expr::NPCK_ZeroExpression ||
12951           NullKind == Expr::NPCK_ZeroLiteral) {
12952         if (!ReturnType->isIntegerType())
12953           return;
12954       } else {
12955         return;
12956       }
12957     }
12958   } else { // !IsCompare
12959     // For function to bool, only suggest if the function pointer has bool
12960     // return type.
12961     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12962       return;
12963   }
12964   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12965       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12966 }
12967 
12968 /// Diagnoses "dangerous" implicit conversions within the given
12969 /// expression (which is a full expression).  Implements -Wconversion
12970 /// and -Wsign-compare.
12971 ///
12972 /// \param CC the "context" location of the implicit conversion, i.e.
12973 ///   the most location of the syntactic entity requiring the implicit
12974 ///   conversion
12975 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12976   // Don't diagnose in unevaluated contexts.
12977   if (isUnevaluatedContext())
12978     return;
12979 
12980   // Don't diagnose for value- or type-dependent expressions.
12981   if (E->isTypeDependent() || E->isValueDependent())
12982     return;
12983 
12984   // Check for array bounds violations in cases where the check isn't triggered
12985   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12986   // ArraySubscriptExpr is on the RHS of a variable initialization.
12987   CheckArrayAccess(E);
12988 
12989   // This is not the right CC for (e.g.) a variable initialization.
12990   AnalyzeImplicitConversions(*this, E, CC);
12991 }
12992 
12993 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12994 /// Input argument E is a logical expression.
12995 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12996   ::CheckBoolLikeConversion(*this, E, CC);
12997 }
12998 
12999 /// Diagnose when expression is an integer constant expression and its evaluation
13000 /// results in integer overflow
13001 void Sema::CheckForIntOverflow (Expr *E) {
13002   // Use a work list to deal with nested struct initializers.
13003   SmallVector<Expr *, 2> Exprs(1, E);
13004 
13005   do {
13006     Expr *OriginalE = Exprs.pop_back_val();
13007     Expr *E = OriginalE->IgnoreParenCasts();
13008 
13009     if (isa<BinaryOperator>(E)) {
13010       E->EvaluateForOverflow(Context);
13011       continue;
13012     }
13013 
13014     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13015       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13016     else if (isa<ObjCBoxedExpr>(OriginalE))
13017       E->EvaluateForOverflow(Context);
13018     else if (auto Call = dyn_cast<CallExpr>(E))
13019       Exprs.append(Call->arg_begin(), Call->arg_end());
13020     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13021       Exprs.append(Message->arg_begin(), Message->arg_end());
13022   } while (!Exprs.empty());
13023 }
13024 
13025 namespace {
13026 
13027 /// Visitor for expressions which looks for unsequenced operations on the
13028 /// same object.
13029 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13030   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13031 
13032   /// A tree of sequenced regions within an expression. Two regions are
13033   /// unsequenced if one is an ancestor or a descendent of the other. When we
13034   /// finish processing an expression with sequencing, such as a comma
13035   /// expression, we fold its tree nodes into its parent, since they are
13036   /// unsequenced with respect to nodes we will visit later.
13037   class SequenceTree {
13038     struct Value {
13039       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13040       unsigned Parent : 31;
13041       unsigned Merged : 1;
13042     };
13043     SmallVector<Value, 8> Values;
13044 
13045   public:
13046     /// A region within an expression which may be sequenced with respect
13047     /// to some other region.
13048     class Seq {
13049       friend class SequenceTree;
13050 
13051       unsigned Index;
13052 
13053       explicit Seq(unsigned N) : Index(N) {}
13054 
13055     public:
13056       Seq() : Index(0) {}
13057     };
13058 
13059     SequenceTree() { Values.push_back(Value(0)); }
13060     Seq root() const { return Seq(0); }
13061 
13062     /// Create a new sequence of operations, which is an unsequenced
13063     /// subset of \p Parent. This sequence of operations is sequenced with
13064     /// respect to other children of \p Parent.
13065     Seq allocate(Seq Parent) {
13066       Values.push_back(Value(Parent.Index));
13067       return Seq(Values.size() - 1);
13068     }
13069 
13070     /// Merge a sequence of operations into its parent.
13071     void merge(Seq S) {
13072       Values[S.Index].Merged = true;
13073     }
13074 
13075     /// Determine whether two operations are unsequenced. This operation
13076     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13077     /// should have been merged into its parent as appropriate.
13078     bool isUnsequenced(Seq Cur, Seq Old) {
13079       unsigned C = representative(Cur.Index);
13080       unsigned Target = representative(Old.Index);
13081       while (C >= Target) {
13082         if (C == Target)
13083           return true;
13084         C = Values[C].Parent;
13085       }
13086       return false;
13087     }
13088 
13089   private:
13090     /// Pick a representative for a sequence.
13091     unsigned representative(unsigned K) {
13092       if (Values[K].Merged)
13093         // Perform path compression as we go.
13094         return Values[K].Parent = representative(Values[K].Parent);
13095       return K;
13096     }
13097   };
13098 
13099   /// An object for which we can track unsequenced uses.
13100   using Object = const NamedDecl *;
13101 
13102   /// Different flavors of object usage which we track. We only track the
13103   /// least-sequenced usage of each kind.
13104   enum UsageKind {
13105     /// A read of an object. Multiple unsequenced reads are OK.
13106     UK_Use,
13107 
13108     /// A modification of an object which is sequenced before the value
13109     /// computation of the expression, such as ++n in C++.
13110     UK_ModAsValue,
13111 
13112     /// A modification of an object which is not sequenced before the value
13113     /// computation of the expression, such as n++.
13114     UK_ModAsSideEffect,
13115 
13116     UK_Count = UK_ModAsSideEffect + 1
13117   };
13118 
13119   /// Bundle together a sequencing region and the expression corresponding
13120   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13121   struct Usage {
13122     const Expr *UsageExpr;
13123     SequenceTree::Seq Seq;
13124 
13125     Usage() : UsageExpr(nullptr), Seq() {}
13126   };
13127 
13128   struct UsageInfo {
13129     Usage Uses[UK_Count];
13130 
13131     /// Have we issued a diagnostic for this object already?
13132     bool Diagnosed;
13133 
13134     UsageInfo() : Uses(), Diagnosed(false) {}
13135   };
13136   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13137 
13138   Sema &SemaRef;
13139 
13140   /// Sequenced regions within the expression.
13141   SequenceTree Tree;
13142 
13143   /// Declaration modifications and references which we have seen.
13144   UsageInfoMap UsageMap;
13145 
13146   /// The region we are currently within.
13147   SequenceTree::Seq Region;
13148 
13149   /// Filled in with declarations which were modified as a side-effect
13150   /// (that is, post-increment operations).
13151   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13152 
13153   /// Expressions to check later. We defer checking these to reduce
13154   /// stack usage.
13155   SmallVectorImpl<const Expr *> &WorkList;
13156 
13157   /// RAII object wrapping the visitation of a sequenced subexpression of an
13158   /// expression. At the end of this process, the side-effects of the evaluation
13159   /// become sequenced with respect to the value computation of the result, so
13160   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13161   /// UK_ModAsValue.
13162   struct SequencedSubexpression {
13163     SequencedSubexpression(SequenceChecker &Self)
13164       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13165       Self.ModAsSideEffect = &ModAsSideEffect;
13166     }
13167 
13168     ~SequencedSubexpression() {
13169       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13170         // Add a new usage with usage kind UK_ModAsValue, and then restore
13171         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13172         // the previous one was empty).
13173         UsageInfo &UI = Self.UsageMap[M.first];
13174         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13175         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13176         SideEffectUsage = M.second;
13177       }
13178       Self.ModAsSideEffect = OldModAsSideEffect;
13179     }
13180 
13181     SequenceChecker &Self;
13182     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13183     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13184   };
13185 
13186   /// RAII object wrapping the visitation of a subexpression which we might
13187   /// choose to evaluate as a constant. If any subexpression is evaluated and
13188   /// found to be non-constant, this allows us to suppress the evaluation of
13189   /// the outer expression.
13190   class EvaluationTracker {
13191   public:
13192     EvaluationTracker(SequenceChecker &Self)
13193         : Self(Self), Prev(Self.EvalTracker) {
13194       Self.EvalTracker = this;
13195     }
13196 
13197     ~EvaluationTracker() {
13198       Self.EvalTracker = Prev;
13199       if (Prev)
13200         Prev->EvalOK &= EvalOK;
13201     }
13202 
13203     bool evaluate(const Expr *E, bool &Result) {
13204       if (!EvalOK || E->isValueDependent())
13205         return false;
13206       EvalOK = E->EvaluateAsBooleanCondition(
13207           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13208       return EvalOK;
13209     }
13210 
13211   private:
13212     SequenceChecker &Self;
13213     EvaluationTracker *Prev;
13214     bool EvalOK = true;
13215   } *EvalTracker = nullptr;
13216 
13217   /// Find the object which is produced by the specified expression,
13218   /// if any.
13219   Object getObject(const Expr *E, bool Mod) const {
13220     E = E->IgnoreParenCasts();
13221     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13222       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13223         return getObject(UO->getSubExpr(), Mod);
13224     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13225       if (BO->getOpcode() == BO_Comma)
13226         return getObject(BO->getRHS(), Mod);
13227       if (Mod && BO->isAssignmentOp())
13228         return getObject(BO->getLHS(), Mod);
13229     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13230       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13231       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13232         return ME->getMemberDecl();
13233     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13234       // FIXME: If this is a reference, map through to its value.
13235       return DRE->getDecl();
13236     return nullptr;
13237   }
13238 
13239   /// Note that an object \p O was modified or used by an expression
13240   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13241   /// the object \p O as obtained via the \p UsageMap.
13242   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13243     // Get the old usage for the given object and usage kind.
13244     Usage &U = UI.Uses[UK];
13245     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13246       // If we have a modification as side effect and are in a sequenced
13247       // subexpression, save the old Usage so that we can restore it later
13248       // in SequencedSubexpression::~SequencedSubexpression.
13249       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13250         ModAsSideEffect->push_back(std::make_pair(O, U));
13251       // Then record the new usage with the current sequencing region.
13252       U.UsageExpr = UsageExpr;
13253       U.Seq = Region;
13254     }
13255   }
13256 
13257   /// Check whether a modification or use of an object \p O in an expression
13258   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13259   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13260   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13261   /// usage and false we are checking for a mod-use unsequenced usage.
13262   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13263                   UsageKind OtherKind, bool IsModMod) {
13264     if (UI.Diagnosed)
13265       return;
13266 
13267     const Usage &U = UI.Uses[OtherKind];
13268     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13269       return;
13270 
13271     const Expr *Mod = U.UsageExpr;
13272     const Expr *ModOrUse = UsageExpr;
13273     if (OtherKind == UK_Use)
13274       std::swap(Mod, ModOrUse);
13275 
13276     SemaRef.DiagRuntimeBehavior(
13277         Mod->getExprLoc(), {Mod, ModOrUse},
13278         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13279                                : diag::warn_unsequenced_mod_use)
13280             << O << SourceRange(ModOrUse->getExprLoc()));
13281     UI.Diagnosed = true;
13282   }
13283 
13284   // A note on note{Pre, Post}{Use, Mod}:
13285   //
13286   // (It helps to follow the algorithm with an expression such as
13287   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13288   //  operations before C++17 and both are well-defined in C++17).
13289   //
13290   // When visiting a node which uses/modify an object we first call notePreUse
13291   // or notePreMod before visiting its sub-expression(s). At this point the
13292   // children of the current node have not yet been visited and so the eventual
13293   // uses/modifications resulting from the children of the current node have not
13294   // been recorded yet.
13295   //
13296   // We then visit the children of the current node. After that notePostUse or
13297   // notePostMod is called. These will 1) detect an unsequenced modification
13298   // as side effect (as in "k++ + k") and 2) add a new usage with the
13299   // appropriate usage kind.
13300   //
13301   // We also have to be careful that some operation sequences modification as
13302   // side effect as well (for example: || or ,). To account for this we wrap
13303   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13304   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13305   // which record usages which are modifications as side effect, and then
13306   // downgrade them (or more accurately restore the previous usage which was a
13307   // modification as side effect) when exiting the scope of the sequenced
13308   // subexpression.
13309 
13310   void notePreUse(Object O, const Expr *UseExpr) {
13311     UsageInfo &UI = UsageMap[O];
13312     // Uses conflict with other modifications.
13313     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13314   }
13315 
13316   void notePostUse(Object O, const Expr *UseExpr) {
13317     UsageInfo &UI = UsageMap[O];
13318     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13319                /*IsModMod=*/false);
13320     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13321   }
13322 
13323   void notePreMod(Object O, const Expr *ModExpr) {
13324     UsageInfo &UI = UsageMap[O];
13325     // Modifications conflict with other modifications and with uses.
13326     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13327     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13328   }
13329 
13330   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13331     UsageInfo &UI = UsageMap[O];
13332     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13333                /*IsModMod=*/true);
13334     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13335   }
13336 
13337 public:
13338   SequenceChecker(Sema &S, const Expr *E,
13339                   SmallVectorImpl<const Expr *> &WorkList)
13340       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13341     Visit(E);
13342     // Silence a -Wunused-private-field since WorkList is now unused.
13343     // TODO: Evaluate if it can be used, and if not remove it.
13344     (void)this->WorkList;
13345   }
13346 
13347   void VisitStmt(const Stmt *S) {
13348     // Skip all statements which aren't expressions for now.
13349   }
13350 
13351   void VisitExpr(const Expr *E) {
13352     // By default, just recurse to evaluated subexpressions.
13353     Base::VisitStmt(E);
13354   }
13355 
13356   void VisitCastExpr(const CastExpr *E) {
13357     Object O = Object();
13358     if (E->getCastKind() == CK_LValueToRValue)
13359       O = getObject(E->getSubExpr(), false);
13360 
13361     if (O)
13362       notePreUse(O, E);
13363     VisitExpr(E);
13364     if (O)
13365       notePostUse(O, E);
13366   }
13367 
13368   void VisitSequencedExpressions(const Expr *SequencedBefore,
13369                                  const Expr *SequencedAfter) {
13370     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13371     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13372     SequenceTree::Seq OldRegion = Region;
13373 
13374     {
13375       SequencedSubexpression SeqBefore(*this);
13376       Region = BeforeRegion;
13377       Visit(SequencedBefore);
13378     }
13379 
13380     Region = AfterRegion;
13381     Visit(SequencedAfter);
13382 
13383     Region = OldRegion;
13384 
13385     Tree.merge(BeforeRegion);
13386     Tree.merge(AfterRegion);
13387   }
13388 
13389   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13390     // C++17 [expr.sub]p1:
13391     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13392     //   expression E1 is sequenced before the expression E2.
13393     if (SemaRef.getLangOpts().CPlusPlus17)
13394       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13395     else {
13396       Visit(ASE->getLHS());
13397       Visit(ASE->getRHS());
13398     }
13399   }
13400 
13401   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13402   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13403   void VisitBinPtrMem(const BinaryOperator *BO) {
13404     // C++17 [expr.mptr.oper]p4:
13405     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13406     //  the expression E1 is sequenced before the expression E2.
13407     if (SemaRef.getLangOpts().CPlusPlus17)
13408       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13409     else {
13410       Visit(BO->getLHS());
13411       Visit(BO->getRHS());
13412     }
13413   }
13414 
13415   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13416   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13417   void VisitBinShlShr(const BinaryOperator *BO) {
13418     // C++17 [expr.shift]p4:
13419     //  The expression E1 is sequenced before the expression E2.
13420     if (SemaRef.getLangOpts().CPlusPlus17)
13421       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13422     else {
13423       Visit(BO->getLHS());
13424       Visit(BO->getRHS());
13425     }
13426   }
13427 
13428   void VisitBinComma(const BinaryOperator *BO) {
13429     // C++11 [expr.comma]p1:
13430     //   Every value computation and side effect associated with the left
13431     //   expression is sequenced before every value computation and side
13432     //   effect associated with the right expression.
13433     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13434   }
13435 
13436   void VisitBinAssign(const BinaryOperator *BO) {
13437     SequenceTree::Seq RHSRegion;
13438     SequenceTree::Seq LHSRegion;
13439     if (SemaRef.getLangOpts().CPlusPlus17) {
13440       RHSRegion = Tree.allocate(Region);
13441       LHSRegion = Tree.allocate(Region);
13442     } else {
13443       RHSRegion = Region;
13444       LHSRegion = Region;
13445     }
13446     SequenceTree::Seq OldRegion = Region;
13447 
13448     // C++11 [expr.ass]p1:
13449     //  [...] the assignment is sequenced after the value computation
13450     //  of the right and left operands, [...]
13451     //
13452     // so check it before inspecting the operands and update the
13453     // map afterwards.
13454     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13455     if (O)
13456       notePreMod(O, BO);
13457 
13458     if (SemaRef.getLangOpts().CPlusPlus17) {
13459       // C++17 [expr.ass]p1:
13460       //  [...] The right operand is sequenced before the left operand. [...]
13461       {
13462         SequencedSubexpression SeqBefore(*this);
13463         Region = RHSRegion;
13464         Visit(BO->getRHS());
13465       }
13466 
13467       Region = LHSRegion;
13468       Visit(BO->getLHS());
13469 
13470       if (O && isa<CompoundAssignOperator>(BO))
13471         notePostUse(O, BO);
13472 
13473     } else {
13474       // C++11 does not specify any sequencing between the LHS and RHS.
13475       Region = LHSRegion;
13476       Visit(BO->getLHS());
13477 
13478       if (O && isa<CompoundAssignOperator>(BO))
13479         notePostUse(O, BO);
13480 
13481       Region = RHSRegion;
13482       Visit(BO->getRHS());
13483     }
13484 
13485     // C++11 [expr.ass]p1:
13486     //  the assignment is sequenced [...] before the value computation of the
13487     //  assignment expression.
13488     // C11 6.5.16/3 has no such rule.
13489     Region = OldRegion;
13490     if (O)
13491       notePostMod(O, BO,
13492                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13493                                                   : UK_ModAsSideEffect);
13494     if (SemaRef.getLangOpts().CPlusPlus17) {
13495       Tree.merge(RHSRegion);
13496       Tree.merge(LHSRegion);
13497     }
13498   }
13499 
13500   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13501     VisitBinAssign(CAO);
13502   }
13503 
13504   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13505   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13506   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13507     Object O = getObject(UO->getSubExpr(), true);
13508     if (!O)
13509       return VisitExpr(UO);
13510 
13511     notePreMod(O, UO);
13512     Visit(UO->getSubExpr());
13513     // C++11 [expr.pre.incr]p1:
13514     //   the expression ++x is equivalent to x+=1
13515     notePostMod(O, UO,
13516                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13517                                                 : UK_ModAsSideEffect);
13518   }
13519 
13520   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13521   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13522   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13523     Object O = getObject(UO->getSubExpr(), true);
13524     if (!O)
13525       return VisitExpr(UO);
13526 
13527     notePreMod(O, UO);
13528     Visit(UO->getSubExpr());
13529     notePostMod(O, UO, UK_ModAsSideEffect);
13530   }
13531 
13532   void VisitBinLOr(const BinaryOperator *BO) {
13533     // C++11 [expr.log.or]p2:
13534     //  If the second expression is evaluated, every value computation and
13535     //  side effect associated with the first expression is sequenced before
13536     //  every value computation and side effect associated with the
13537     //  second expression.
13538     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13539     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13540     SequenceTree::Seq OldRegion = Region;
13541 
13542     EvaluationTracker Eval(*this);
13543     {
13544       SequencedSubexpression Sequenced(*this);
13545       Region = LHSRegion;
13546       Visit(BO->getLHS());
13547     }
13548 
13549     // C++11 [expr.log.or]p1:
13550     //  [...] the second operand is not evaluated if the first operand
13551     //  evaluates to true.
13552     bool EvalResult = false;
13553     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13554     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13555     if (ShouldVisitRHS) {
13556       Region = RHSRegion;
13557       Visit(BO->getRHS());
13558     }
13559 
13560     Region = OldRegion;
13561     Tree.merge(LHSRegion);
13562     Tree.merge(RHSRegion);
13563   }
13564 
13565   void VisitBinLAnd(const BinaryOperator *BO) {
13566     // C++11 [expr.log.and]p2:
13567     //  If the second expression is evaluated, every value computation and
13568     //  side effect associated with the first expression is sequenced before
13569     //  every value computation and side effect associated with the
13570     //  second expression.
13571     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13572     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13573     SequenceTree::Seq OldRegion = Region;
13574 
13575     EvaluationTracker Eval(*this);
13576     {
13577       SequencedSubexpression Sequenced(*this);
13578       Region = LHSRegion;
13579       Visit(BO->getLHS());
13580     }
13581 
13582     // C++11 [expr.log.and]p1:
13583     //  [...] the second operand is not evaluated if the first operand is false.
13584     bool EvalResult = false;
13585     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13586     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13587     if (ShouldVisitRHS) {
13588       Region = RHSRegion;
13589       Visit(BO->getRHS());
13590     }
13591 
13592     Region = OldRegion;
13593     Tree.merge(LHSRegion);
13594     Tree.merge(RHSRegion);
13595   }
13596 
13597   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13598     // C++11 [expr.cond]p1:
13599     //  [...] Every value computation and side effect associated with the first
13600     //  expression is sequenced before every value computation and side effect
13601     //  associated with the second or third expression.
13602     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13603 
13604     // No sequencing is specified between the true and false expression.
13605     // However since exactly one of both is going to be evaluated we can
13606     // consider them to be sequenced. This is needed to avoid warning on
13607     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13608     // both the true and false expressions because we can't evaluate x.
13609     // This will still allow us to detect an expression like (pre C++17)
13610     // "(x ? y += 1 : y += 2) = y".
13611     //
13612     // We don't wrap the visitation of the true and false expression with
13613     // SequencedSubexpression because we don't want to downgrade modifications
13614     // as side effect in the true and false expressions after the visition
13615     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13616     // not warn between the two "y++", but we should warn between the "y++"
13617     // and the "y".
13618     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13619     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13620     SequenceTree::Seq OldRegion = Region;
13621 
13622     EvaluationTracker Eval(*this);
13623     {
13624       SequencedSubexpression Sequenced(*this);
13625       Region = ConditionRegion;
13626       Visit(CO->getCond());
13627     }
13628 
13629     // C++11 [expr.cond]p1:
13630     // [...] The first expression is contextually converted to bool (Clause 4).
13631     // It is evaluated and if it is true, the result of the conditional
13632     // expression is the value of the second expression, otherwise that of the
13633     // third expression. Only one of the second and third expressions is
13634     // evaluated. [...]
13635     bool EvalResult = false;
13636     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13637     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13638     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13639     if (ShouldVisitTrueExpr) {
13640       Region = TrueRegion;
13641       Visit(CO->getTrueExpr());
13642     }
13643     if (ShouldVisitFalseExpr) {
13644       Region = FalseRegion;
13645       Visit(CO->getFalseExpr());
13646     }
13647 
13648     Region = OldRegion;
13649     Tree.merge(ConditionRegion);
13650     Tree.merge(TrueRegion);
13651     Tree.merge(FalseRegion);
13652   }
13653 
13654   void VisitCallExpr(const CallExpr *CE) {
13655     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13656 
13657     if (CE->isUnevaluatedBuiltinCall(Context))
13658       return;
13659 
13660     // C++11 [intro.execution]p15:
13661     //   When calling a function [...], every value computation and side effect
13662     //   associated with any argument expression, or with the postfix expression
13663     //   designating the called function, is sequenced before execution of every
13664     //   expression or statement in the body of the function [and thus before
13665     //   the value computation of its result].
13666     SequencedSubexpression Sequenced(*this);
13667     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13668       // C++17 [expr.call]p5
13669       //   The postfix-expression is sequenced before each expression in the
13670       //   expression-list and any default argument. [...]
13671       SequenceTree::Seq CalleeRegion;
13672       SequenceTree::Seq OtherRegion;
13673       if (SemaRef.getLangOpts().CPlusPlus17) {
13674         CalleeRegion = Tree.allocate(Region);
13675         OtherRegion = Tree.allocate(Region);
13676       } else {
13677         CalleeRegion = Region;
13678         OtherRegion = Region;
13679       }
13680       SequenceTree::Seq OldRegion = Region;
13681 
13682       // Visit the callee expression first.
13683       Region = CalleeRegion;
13684       if (SemaRef.getLangOpts().CPlusPlus17) {
13685         SequencedSubexpression Sequenced(*this);
13686         Visit(CE->getCallee());
13687       } else {
13688         Visit(CE->getCallee());
13689       }
13690 
13691       // Then visit the argument expressions.
13692       Region = OtherRegion;
13693       for (const Expr *Argument : CE->arguments())
13694         Visit(Argument);
13695 
13696       Region = OldRegion;
13697       if (SemaRef.getLangOpts().CPlusPlus17) {
13698         Tree.merge(CalleeRegion);
13699         Tree.merge(OtherRegion);
13700       }
13701     });
13702   }
13703 
13704   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13705     // C++17 [over.match.oper]p2:
13706     //   [...] the operator notation is first transformed to the equivalent
13707     //   function-call notation as summarized in Table 12 (where @ denotes one
13708     //   of the operators covered in the specified subclause). However, the
13709     //   operands are sequenced in the order prescribed for the built-in
13710     //   operator (Clause 8).
13711     //
13712     // From the above only overloaded binary operators and overloaded call
13713     // operators have sequencing rules in C++17 that we need to handle
13714     // separately.
13715     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13716         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13717       return VisitCallExpr(CXXOCE);
13718 
13719     enum {
13720       NoSequencing,
13721       LHSBeforeRHS,
13722       RHSBeforeLHS,
13723       LHSBeforeRest
13724     } SequencingKind;
13725     switch (CXXOCE->getOperator()) {
13726     case OO_Equal:
13727     case OO_PlusEqual:
13728     case OO_MinusEqual:
13729     case OO_StarEqual:
13730     case OO_SlashEqual:
13731     case OO_PercentEqual:
13732     case OO_CaretEqual:
13733     case OO_AmpEqual:
13734     case OO_PipeEqual:
13735     case OO_LessLessEqual:
13736     case OO_GreaterGreaterEqual:
13737       SequencingKind = RHSBeforeLHS;
13738       break;
13739 
13740     case OO_LessLess:
13741     case OO_GreaterGreater:
13742     case OO_AmpAmp:
13743     case OO_PipePipe:
13744     case OO_Comma:
13745     case OO_ArrowStar:
13746     case OO_Subscript:
13747       SequencingKind = LHSBeforeRHS;
13748       break;
13749 
13750     case OO_Call:
13751       SequencingKind = LHSBeforeRest;
13752       break;
13753 
13754     default:
13755       SequencingKind = NoSequencing;
13756       break;
13757     }
13758 
13759     if (SequencingKind == NoSequencing)
13760       return VisitCallExpr(CXXOCE);
13761 
13762     // This is a call, so all subexpressions are sequenced before the result.
13763     SequencedSubexpression Sequenced(*this);
13764 
13765     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13766       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13767              "Should only get there with C++17 and above!");
13768       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13769              "Should only get there with an overloaded binary operator"
13770              " or an overloaded call operator!");
13771 
13772       if (SequencingKind == LHSBeforeRest) {
13773         assert(CXXOCE->getOperator() == OO_Call &&
13774                "We should only have an overloaded call operator here!");
13775 
13776         // This is very similar to VisitCallExpr, except that we only have the
13777         // C++17 case. The postfix-expression is the first argument of the
13778         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13779         // are in the following arguments.
13780         //
13781         // Note that we intentionally do not visit the callee expression since
13782         // it is just a decayed reference to a function.
13783         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13784         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13785         SequenceTree::Seq OldRegion = Region;
13786 
13787         assert(CXXOCE->getNumArgs() >= 1 &&
13788                "An overloaded call operator must have at least one argument"
13789                " for the postfix-expression!");
13790         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13791         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13792                                           CXXOCE->getNumArgs() - 1);
13793 
13794         // Visit the postfix-expression first.
13795         {
13796           Region = PostfixExprRegion;
13797           SequencedSubexpression Sequenced(*this);
13798           Visit(PostfixExpr);
13799         }
13800 
13801         // Then visit the argument expressions.
13802         Region = ArgsRegion;
13803         for (const Expr *Arg : Args)
13804           Visit(Arg);
13805 
13806         Region = OldRegion;
13807         Tree.merge(PostfixExprRegion);
13808         Tree.merge(ArgsRegion);
13809       } else {
13810         assert(CXXOCE->getNumArgs() == 2 &&
13811                "Should only have two arguments here!");
13812         assert((SequencingKind == LHSBeforeRHS ||
13813                 SequencingKind == RHSBeforeLHS) &&
13814                "Unexpected sequencing kind!");
13815 
13816         // We do not visit the callee expression since it is just a decayed
13817         // reference to a function.
13818         const Expr *E1 = CXXOCE->getArg(0);
13819         const Expr *E2 = CXXOCE->getArg(1);
13820         if (SequencingKind == RHSBeforeLHS)
13821           std::swap(E1, E2);
13822 
13823         return VisitSequencedExpressions(E1, E2);
13824       }
13825     });
13826   }
13827 
13828   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13829     // This is a call, so all subexpressions are sequenced before the result.
13830     SequencedSubexpression Sequenced(*this);
13831 
13832     if (!CCE->isListInitialization())
13833       return VisitExpr(CCE);
13834 
13835     // In C++11, list initializations are sequenced.
13836     SmallVector<SequenceTree::Seq, 32> Elts;
13837     SequenceTree::Seq Parent = Region;
13838     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13839                                               E = CCE->arg_end();
13840          I != E; ++I) {
13841       Region = Tree.allocate(Parent);
13842       Elts.push_back(Region);
13843       Visit(*I);
13844     }
13845 
13846     // Forget that the initializers are sequenced.
13847     Region = Parent;
13848     for (unsigned I = 0; I < Elts.size(); ++I)
13849       Tree.merge(Elts[I]);
13850   }
13851 
13852   void VisitInitListExpr(const InitListExpr *ILE) {
13853     if (!SemaRef.getLangOpts().CPlusPlus11)
13854       return VisitExpr(ILE);
13855 
13856     // In C++11, list initializations are sequenced.
13857     SmallVector<SequenceTree::Seq, 32> Elts;
13858     SequenceTree::Seq Parent = Region;
13859     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13860       const Expr *E = ILE->getInit(I);
13861       if (!E)
13862         continue;
13863       Region = Tree.allocate(Parent);
13864       Elts.push_back(Region);
13865       Visit(E);
13866     }
13867 
13868     // Forget that the initializers are sequenced.
13869     Region = Parent;
13870     for (unsigned I = 0; I < Elts.size(); ++I)
13871       Tree.merge(Elts[I]);
13872   }
13873 };
13874 
13875 } // namespace
13876 
13877 void Sema::CheckUnsequencedOperations(const Expr *E) {
13878   SmallVector<const Expr *, 8> WorkList;
13879   WorkList.push_back(E);
13880   while (!WorkList.empty()) {
13881     const Expr *Item = WorkList.pop_back_val();
13882     SequenceChecker(*this, Item, WorkList);
13883   }
13884 }
13885 
13886 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13887                               bool IsConstexpr) {
13888   llvm::SaveAndRestore<bool> ConstantContext(
13889       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13890   CheckImplicitConversions(E, CheckLoc);
13891   if (!E->isInstantiationDependent())
13892     CheckUnsequencedOperations(E);
13893   if (!IsConstexpr && !E->isValueDependent())
13894     CheckForIntOverflow(E);
13895   DiagnoseMisalignedMembers();
13896 }
13897 
13898 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13899                                        FieldDecl *BitField,
13900                                        Expr *Init) {
13901   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13902 }
13903 
13904 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13905                                          SourceLocation Loc) {
13906   if (!PType->isVariablyModifiedType())
13907     return;
13908   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13909     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13910     return;
13911   }
13912   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13913     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13914     return;
13915   }
13916   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13917     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13918     return;
13919   }
13920 
13921   const ArrayType *AT = S.Context.getAsArrayType(PType);
13922   if (!AT)
13923     return;
13924 
13925   if (AT->getSizeModifier() != ArrayType::Star) {
13926     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13927     return;
13928   }
13929 
13930   S.Diag(Loc, diag::err_array_star_in_function_definition);
13931 }
13932 
13933 /// CheckParmsForFunctionDef - Check that the parameters of the given
13934 /// function are appropriate for the definition of a function. This
13935 /// takes care of any checks that cannot be performed on the
13936 /// declaration itself, e.g., that the types of each of the function
13937 /// parameters are complete.
13938 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13939                                     bool CheckParameterNames) {
13940   bool HasInvalidParm = false;
13941   for (ParmVarDecl *Param : Parameters) {
13942     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13943     // function declarator that is part of a function definition of
13944     // that function shall not have incomplete type.
13945     //
13946     // This is also C++ [dcl.fct]p6.
13947     if (!Param->isInvalidDecl() &&
13948         RequireCompleteType(Param->getLocation(), Param->getType(),
13949                             diag::err_typecheck_decl_incomplete_type)) {
13950       Param->setInvalidDecl();
13951       HasInvalidParm = true;
13952     }
13953 
13954     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13955     // declaration of each parameter shall include an identifier.
13956     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13957         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13958       // Diagnose this as an extension in C17 and earlier.
13959       if (!getLangOpts().C2x)
13960         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13961     }
13962 
13963     // C99 6.7.5.3p12:
13964     //   If the function declarator is not part of a definition of that
13965     //   function, parameters may have incomplete type and may use the [*]
13966     //   notation in their sequences of declarator specifiers to specify
13967     //   variable length array types.
13968     QualType PType = Param->getOriginalType();
13969     // FIXME: This diagnostic should point the '[*]' if source-location
13970     // information is added for it.
13971     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13972 
13973     // If the parameter is a c++ class type and it has to be destructed in the
13974     // callee function, declare the destructor so that it can be called by the
13975     // callee function. Do not perform any direct access check on the dtor here.
13976     if (!Param->isInvalidDecl()) {
13977       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13978         if (!ClassDecl->isInvalidDecl() &&
13979             !ClassDecl->hasIrrelevantDestructor() &&
13980             !ClassDecl->isDependentContext() &&
13981             ClassDecl->isParamDestroyedInCallee()) {
13982           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13983           MarkFunctionReferenced(Param->getLocation(), Destructor);
13984           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13985         }
13986       }
13987     }
13988 
13989     // Parameters with the pass_object_size attribute only need to be marked
13990     // constant at function definitions. Because we lack information about
13991     // whether we're on a declaration or definition when we're instantiating the
13992     // attribute, we need to check for constness here.
13993     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13994       if (!Param->getType().isConstQualified())
13995         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13996             << Attr->getSpelling() << 1;
13997 
13998     // Check for parameter names shadowing fields from the class.
13999     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14000       // The owning context for the parameter should be the function, but we
14001       // want to see if this function's declaration context is a record.
14002       DeclContext *DC = Param->getDeclContext();
14003       if (DC && DC->isFunctionOrMethod()) {
14004         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14005           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14006                                      RD, /*DeclIsField*/ false);
14007       }
14008     }
14009   }
14010 
14011   return HasInvalidParm;
14012 }
14013 
14014 Optional<std::pair<CharUnits, CharUnits>>
14015 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14016 
14017 /// Compute the alignment and offset of the base class object given the
14018 /// derived-to-base cast expression and the alignment and offset of the derived
14019 /// class object.
14020 static std::pair<CharUnits, CharUnits>
14021 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14022                                    CharUnits BaseAlignment, CharUnits Offset,
14023                                    ASTContext &Ctx) {
14024   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14025        ++PathI) {
14026     const CXXBaseSpecifier *Base = *PathI;
14027     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14028     if (Base->isVirtual()) {
14029       // The complete object may have a lower alignment than the non-virtual
14030       // alignment of the base, in which case the base may be misaligned. Choose
14031       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14032       // conservative lower bound of the complete object alignment.
14033       CharUnits NonVirtualAlignment =
14034           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14035       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14036       Offset = CharUnits::Zero();
14037     } else {
14038       const ASTRecordLayout &RL =
14039           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14040       Offset += RL.getBaseClassOffset(BaseDecl);
14041     }
14042     DerivedType = Base->getType();
14043   }
14044 
14045   return std::make_pair(BaseAlignment, Offset);
14046 }
14047 
14048 /// Compute the alignment and offset of a binary additive operator.
14049 static Optional<std::pair<CharUnits, CharUnits>>
14050 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14051                                      bool IsSub, ASTContext &Ctx) {
14052   QualType PointeeType = PtrE->getType()->getPointeeType();
14053 
14054   if (!PointeeType->isConstantSizeType())
14055     return llvm::None;
14056 
14057   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14058 
14059   if (!P)
14060     return llvm::None;
14061 
14062   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14063   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14064     CharUnits Offset = EltSize * IdxRes->getExtValue();
14065     if (IsSub)
14066       Offset = -Offset;
14067     return std::make_pair(P->first, P->second + Offset);
14068   }
14069 
14070   // If the integer expression isn't a constant expression, compute the lower
14071   // bound of the alignment using the alignment and offset of the pointer
14072   // expression and the element size.
14073   return std::make_pair(
14074       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14075       CharUnits::Zero());
14076 }
14077 
14078 /// This helper function takes an lvalue expression and returns the alignment of
14079 /// a VarDecl and a constant offset from the VarDecl.
14080 Optional<std::pair<CharUnits, CharUnits>>
14081 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14082   E = E->IgnoreParens();
14083   switch (E->getStmtClass()) {
14084   default:
14085     break;
14086   case Stmt::CStyleCastExprClass:
14087   case Stmt::CXXStaticCastExprClass:
14088   case Stmt::ImplicitCastExprClass: {
14089     auto *CE = cast<CastExpr>(E);
14090     const Expr *From = CE->getSubExpr();
14091     switch (CE->getCastKind()) {
14092     default:
14093       break;
14094     case CK_NoOp:
14095       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14096     case CK_UncheckedDerivedToBase:
14097     case CK_DerivedToBase: {
14098       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14099       if (!P)
14100         break;
14101       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14102                                                 P->second, Ctx);
14103     }
14104     }
14105     break;
14106   }
14107   case Stmt::ArraySubscriptExprClass: {
14108     auto *ASE = cast<ArraySubscriptExpr>(E);
14109     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14110                                                 false, Ctx);
14111   }
14112   case Stmt::DeclRefExprClass: {
14113     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14114       // FIXME: If VD is captured by copy or is an escaping __block variable,
14115       // use the alignment of VD's type.
14116       if (!VD->getType()->isReferenceType())
14117         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14118       if (VD->hasInit())
14119         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14120     }
14121     break;
14122   }
14123   case Stmt::MemberExprClass: {
14124     auto *ME = cast<MemberExpr>(E);
14125     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14126     if (!FD || FD->getType()->isReferenceType())
14127       break;
14128     Optional<std::pair<CharUnits, CharUnits>> P;
14129     if (ME->isArrow())
14130       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14131     else
14132       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14133     if (!P)
14134       break;
14135     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14136     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14137     return std::make_pair(P->first,
14138                           P->second + CharUnits::fromQuantity(Offset));
14139   }
14140   case Stmt::UnaryOperatorClass: {
14141     auto *UO = cast<UnaryOperator>(E);
14142     switch (UO->getOpcode()) {
14143     default:
14144       break;
14145     case UO_Deref:
14146       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14147     }
14148     break;
14149   }
14150   case Stmt::BinaryOperatorClass: {
14151     auto *BO = cast<BinaryOperator>(E);
14152     auto Opcode = BO->getOpcode();
14153     switch (Opcode) {
14154     default:
14155       break;
14156     case BO_Comma:
14157       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14158     }
14159     break;
14160   }
14161   }
14162   return llvm::None;
14163 }
14164 
14165 /// This helper function takes a pointer expression and returns the alignment of
14166 /// a VarDecl and a constant offset from the VarDecl.
14167 Optional<std::pair<CharUnits, CharUnits>>
14168 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14169   E = E->IgnoreParens();
14170   switch (E->getStmtClass()) {
14171   default:
14172     break;
14173   case Stmt::CStyleCastExprClass:
14174   case Stmt::CXXStaticCastExprClass:
14175   case Stmt::ImplicitCastExprClass: {
14176     auto *CE = cast<CastExpr>(E);
14177     const Expr *From = CE->getSubExpr();
14178     switch (CE->getCastKind()) {
14179     default:
14180       break;
14181     case CK_NoOp:
14182       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14183     case CK_ArrayToPointerDecay:
14184       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14185     case CK_UncheckedDerivedToBase:
14186     case CK_DerivedToBase: {
14187       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14188       if (!P)
14189         break;
14190       return getDerivedToBaseAlignmentAndOffset(
14191           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14192     }
14193     }
14194     break;
14195   }
14196   case Stmt::CXXThisExprClass: {
14197     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14198     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14199     return std::make_pair(Alignment, CharUnits::Zero());
14200   }
14201   case Stmt::UnaryOperatorClass: {
14202     auto *UO = cast<UnaryOperator>(E);
14203     if (UO->getOpcode() == UO_AddrOf)
14204       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14205     break;
14206   }
14207   case Stmt::BinaryOperatorClass: {
14208     auto *BO = cast<BinaryOperator>(E);
14209     auto Opcode = BO->getOpcode();
14210     switch (Opcode) {
14211     default:
14212       break;
14213     case BO_Add:
14214     case BO_Sub: {
14215       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14216       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14217         std::swap(LHS, RHS);
14218       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14219                                                   Ctx);
14220     }
14221     case BO_Comma:
14222       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14223     }
14224     break;
14225   }
14226   }
14227   return llvm::None;
14228 }
14229 
14230 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14231   // See if we can compute the alignment of a VarDecl and an offset from it.
14232   Optional<std::pair<CharUnits, CharUnits>> P =
14233       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14234 
14235   if (P)
14236     return P->first.alignmentAtOffset(P->second);
14237 
14238   // If that failed, return the type's alignment.
14239   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14240 }
14241 
14242 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14243 /// pointer cast increases the alignment requirements.
14244 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14245   // This is actually a lot of work to potentially be doing on every
14246   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14247   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14248     return;
14249 
14250   // Ignore dependent types.
14251   if (T->isDependentType() || Op->getType()->isDependentType())
14252     return;
14253 
14254   // Require that the destination be a pointer type.
14255   const PointerType *DestPtr = T->getAs<PointerType>();
14256   if (!DestPtr) return;
14257 
14258   // If the destination has alignment 1, we're done.
14259   QualType DestPointee = DestPtr->getPointeeType();
14260   if (DestPointee->isIncompleteType()) return;
14261   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14262   if (DestAlign.isOne()) return;
14263 
14264   // Require that the source be a pointer type.
14265   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14266   if (!SrcPtr) return;
14267   QualType SrcPointee = SrcPtr->getPointeeType();
14268 
14269   // Explicitly allow casts from cv void*.  We already implicitly
14270   // allowed casts to cv void*, since they have alignment 1.
14271   // Also allow casts involving incomplete types, which implicitly
14272   // includes 'void'.
14273   if (SrcPointee->isIncompleteType()) return;
14274 
14275   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14276 
14277   if (SrcAlign >= DestAlign) return;
14278 
14279   Diag(TRange.getBegin(), diag::warn_cast_align)
14280     << Op->getType() << T
14281     << static_cast<unsigned>(SrcAlign.getQuantity())
14282     << static_cast<unsigned>(DestAlign.getQuantity())
14283     << TRange << Op->getSourceRange();
14284 }
14285 
14286 /// Check whether this array fits the idiom of a size-one tail padded
14287 /// array member of a struct.
14288 ///
14289 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14290 /// commonly used to emulate flexible arrays in C89 code.
14291 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14292                                     const NamedDecl *ND) {
14293   if (Size != 1 || !ND) return false;
14294 
14295   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14296   if (!FD) return false;
14297 
14298   // Don't consider sizes resulting from macro expansions or template argument
14299   // substitution to form C89 tail-padded arrays.
14300 
14301   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14302   while (TInfo) {
14303     TypeLoc TL = TInfo->getTypeLoc();
14304     // Look through typedefs.
14305     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14306       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14307       TInfo = TDL->getTypeSourceInfo();
14308       continue;
14309     }
14310     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14311       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14312       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14313         return false;
14314     }
14315     break;
14316   }
14317 
14318   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14319   if (!RD) return false;
14320   if (RD->isUnion()) return false;
14321   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14322     if (!CRD->isStandardLayout()) return false;
14323   }
14324 
14325   // See if this is the last field decl in the record.
14326   const Decl *D = FD;
14327   while ((D = D->getNextDeclInContext()))
14328     if (isa<FieldDecl>(D))
14329       return false;
14330   return true;
14331 }
14332 
14333 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14334                             const ArraySubscriptExpr *ASE,
14335                             bool AllowOnePastEnd, bool IndexNegated) {
14336   // Already diagnosed by the constant evaluator.
14337   if (isConstantEvaluated())
14338     return;
14339 
14340   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14341   if (IndexExpr->isValueDependent())
14342     return;
14343 
14344   const Type *EffectiveType =
14345       BaseExpr->getType()->getPointeeOrArrayElementType();
14346   BaseExpr = BaseExpr->IgnoreParenCasts();
14347   const ConstantArrayType *ArrayTy =
14348       Context.getAsConstantArrayType(BaseExpr->getType());
14349 
14350   if (!ArrayTy)
14351     return;
14352 
14353   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14354   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14355     return;
14356 
14357   Expr::EvalResult Result;
14358   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14359     return;
14360 
14361   llvm::APSInt index = Result.Val.getInt();
14362   if (IndexNegated)
14363     index = -index;
14364 
14365   const NamedDecl *ND = nullptr;
14366   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14367     ND = DRE->getDecl();
14368   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14369     ND = ME->getMemberDecl();
14370 
14371   if (index.isUnsigned() || !index.isNegative()) {
14372     // It is possible that the type of the base expression after
14373     // IgnoreParenCasts is incomplete, even though the type of the base
14374     // expression before IgnoreParenCasts is complete (see PR39746 for an
14375     // example). In this case we have no information about whether the array
14376     // access exceeds the array bounds. However we can still diagnose an array
14377     // access which precedes the array bounds.
14378     if (BaseType->isIncompleteType())
14379       return;
14380 
14381     llvm::APInt size = ArrayTy->getSize();
14382     if (!size.isStrictlyPositive())
14383       return;
14384 
14385     if (BaseType != EffectiveType) {
14386       // Make sure we're comparing apples to apples when comparing index to size
14387       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14388       uint64_t array_typesize = Context.getTypeSize(BaseType);
14389       // Handle ptrarith_typesize being zero, such as when casting to void*
14390       if (!ptrarith_typesize) ptrarith_typesize = 1;
14391       if (ptrarith_typesize != array_typesize) {
14392         // There's a cast to a different size type involved
14393         uint64_t ratio = array_typesize / ptrarith_typesize;
14394         // TODO: Be smarter about handling cases where array_typesize is not a
14395         // multiple of ptrarith_typesize
14396         if (ptrarith_typesize * ratio == array_typesize)
14397           size *= llvm::APInt(size.getBitWidth(), ratio);
14398       }
14399     }
14400 
14401     if (size.getBitWidth() > index.getBitWidth())
14402       index = index.zext(size.getBitWidth());
14403     else if (size.getBitWidth() < index.getBitWidth())
14404       size = size.zext(index.getBitWidth());
14405 
14406     // For array subscripting the index must be less than size, but for pointer
14407     // arithmetic also allow the index (offset) to be equal to size since
14408     // computing the next address after the end of the array is legal and
14409     // commonly done e.g. in C++ iterators and range-based for loops.
14410     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14411       return;
14412 
14413     // Also don't warn for arrays of size 1 which are members of some
14414     // structure. These are often used to approximate flexible arrays in C89
14415     // code.
14416     if (IsTailPaddedMemberArray(*this, size, ND))
14417       return;
14418 
14419     // Suppress the warning if the subscript expression (as identified by the
14420     // ']' location) and the index expression are both from macro expansions
14421     // within a system header.
14422     if (ASE) {
14423       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14424           ASE->getRBracketLoc());
14425       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14426         SourceLocation IndexLoc =
14427             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14428         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14429           return;
14430       }
14431     }
14432 
14433     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14434     if (ASE)
14435       DiagID = diag::warn_array_index_exceeds_bounds;
14436 
14437     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14438                         PDiag(DiagID) << index.toString(10, true)
14439                                       << size.toString(10, true)
14440                                       << (unsigned)size.getLimitedValue(~0U)
14441                                       << IndexExpr->getSourceRange());
14442   } else {
14443     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14444     if (!ASE) {
14445       DiagID = diag::warn_ptr_arith_precedes_bounds;
14446       if (index.isNegative()) index = -index;
14447     }
14448 
14449     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14450                         PDiag(DiagID) << index.toString(10, true)
14451                                       << IndexExpr->getSourceRange());
14452   }
14453 
14454   if (!ND) {
14455     // Try harder to find a NamedDecl to point at in the note.
14456     while (const ArraySubscriptExpr *ASE =
14457            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14458       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14459     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14460       ND = DRE->getDecl();
14461     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14462       ND = ME->getMemberDecl();
14463   }
14464 
14465   if (ND)
14466     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14467                         PDiag(diag::note_array_declared_here) << ND);
14468 }
14469 
14470 void Sema::CheckArrayAccess(const Expr *expr) {
14471   int AllowOnePastEnd = 0;
14472   while (expr) {
14473     expr = expr->IgnoreParenImpCasts();
14474     switch (expr->getStmtClass()) {
14475       case Stmt::ArraySubscriptExprClass: {
14476         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14477         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14478                          AllowOnePastEnd > 0);
14479         expr = ASE->getBase();
14480         break;
14481       }
14482       case Stmt::MemberExprClass: {
14483         expr = cast<MemberExpr>(expr)->getBase();
14484         break;
14485       }
14486       case Stmt::OMPArraySectionExprClass: {
14487         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14488         if (ASE->getLowerBound())
14489           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14490                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14491         return;
14492       }
14493       case Stmt::UnaryOperatorClass: {
14494         // Only unwrap the * and & unary operators
14495         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14496         expr = UO->getSubExpr();
14497         switch (UO->getOpcode()) {
14498           case UO_AddrOf:
14499             AllowOnePastEnd++;
14500             break;
14501           case UO_Deref:
14502             AllowOnePastEnd--;
14503             break;
14504           default:
14505             return;
14506         }
14507         break;
14508       }
14509       case Stmt::ConditionalOperatorClass: {
14510         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14511         if (const Expr *lhs = cond->getLHS())
14512           CheckArrayAccess(lhs);
14513         if (const Expr *rhs = cond->getRHS())
14514           CheckArrayAccess(rhs);
14515         return;
14516       }
14517       case Stmt::CXXOperatorCallExprClass: {
14518         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14519         for (const auto *Arg : OCE->arguments())
14520           CheckArrayAccess(Arg);
14521         return;
14522       }
14523       default:
14524         return;
14525     }
14526   }
14527 }
14528 
14529 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14530 
14531 namespace {
14532 
14533 struct RetainCycleOwner {
14534   VarDecl *Variable = nullptr;
14535   SourceRange Range;
14536   SourceLocation Loc;
14537   bool Indirect = false;
14538 
14539   RetainCycleOwner() = default;
14540 
14541   void setLocsFrom(Expr *e) {
14542     Loc = e->getExprLoc();
14543     Range = e->getSourceRange();
14544   }
14545 };
14546 
14547 } // namespace
14548 
14549 /// Consider whether capturing the given variable can possibly lead to
14550 /// a retain cycle.
14551 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14552   // In ARC, it's captured strongly iff the variable has __strong
14553   // lifetime.  In MRR, it's captured strongly if the variable is
14554   // __block and has an appropriate type.
14555   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14556     return false;
14557 
14558   owner.Variable = var;
14559   if (ref)
14560     owner.setLocsFrom(ref);
14561   return true;
14562 }
14563 
14564 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14565   while (true) {
14566     e = e->IgnoreParens();
14567     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14568       switch (cast->getCastKind()) {
14569       case CK_BitCast:
14570       case CK_LValueBitCast:
14571       case CK_LValueToRValue:
14572       case CK_ARCReclaimReturnedObject:
14573         e = cast->getSubExpr();
14574         continue;
14575 
14576       default:
14577         return false;
14578       }
14579     }
14580 
14581     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14582       ObjCIvarDecl *ivar = ref->getDecl();
14583       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14584         return false;
14585 
14586       // Try to find a retain cycle in the base.
14587       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14588         return false;
14589 
14590       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14591       owner.Indirect = true;
14592       return true;
14593     }
14594 
14595     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14596       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14597       if (!var) return false;
14598       return considerVariable(var, ref, owner);
14599     }
14600 
14601     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14602       if (member->isArrow()) return false;
14603 
14604       // Don't count this as an indirect ownership.
14605       e = member->getBase();
14606       continue;
14607     }
14608 
14609     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14610       // Only pay attention to pseudo-objects on property references.
14611       ObjCPropertyRefExpr *pre
14612         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14613                                               ->IgnoreParens());
14614       if (!pre) return false;
14615       if (pre->isImplicitProperty()) return false;
14616       ObjCPropertyDecl *property = pre->getExplicitProperty();
14617       if (!property->isRetaining() &&
14618           !(property->getPropertyIvarDecl() &&
14619             property->getPropertyIvarDecl()->getType()
14620               .getObjCLifetime() == Qualifiers::OCL_Strong))
14621           return false;
14622 
14623       owner.Indirect = true;
14624       if (pre->isSuperReceiver()) {
14625         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14626         if (!owner.Variable)
14627           return false;
14628         owner.Loc = pre->getLocation();
14629         owner.Range = pre->getSourceRange();
14630         return true;
14631       }
14632       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14633                               ->getSourceExpr());
14634       continue;
14635     }
14636 
14637     // Array ivars?
14638 
14639     return false;
14640   }
14641 }
14642 
14643 namespace {
14644 
14645   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14646     ASTContext &Context;
14647     VarDecl *Variable;
14648     Expr *Capturer = nullptr;
14649     bool VarWillBeReased = false;
14650 
14651     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14652         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14653           Context(Context), Variable(variable) {}
14654 
14655     void VisitDeclRefExpr(DeclRefExpr *ref) {
14656       if (ref->getDecl() == Variable && !Capturer)
14657         Capturer = ref;
14658     }
14659 
14660     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14661       if (Capturer) return;
14662       Visit(ref->getBase());
14663       if (Capturer && ref->isFreeIvar())
14664         Capturer = ref;
14665     }
14666 
14667     void VisitBlockExpr(BlockExpr *block) {
14668       // Look inside nested blocks
14669       if (block->getBlockDecl()->capturesVariable(Variable))
14670         Visit(block->getBlockDecl()->getBody());
14671     }
14672 
14673     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14674       if (Capturer) return;
14675       if (OVE->getSourceExpr())
14676         Visit(OVE->getSourceExpr());
14677     }
14678 
14679     void VisitBinaryOperator(BinaryOperator *BinOp) {
14680       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14681         return;
14682       Expr *LHS = BinOp->getLHS();
14683       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14684         if (DRE->getDecl() != Variable)
14685           return;
14686         if (Expr *RHS = BinOp->getRHS()) {
14687           RHS = RHS->IgnoreParenCasts();
14688           Optional<llvm::APSInt> Value;
14689           VarWillBeReased =
14690               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14691                *Value == 0);
14692         }
14693       }
14694     }
14695   };
14696 
14697 } // namespace
14698 
14699 /// Check whether the given argument is a block which captures a
14700 /// variable.
14701 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14702   assert(owner.Variable && owner.Loc.isValid());
14703 
14704   e = e->IgnoreParenCasts();
14705 
14706   // Look through [^{...} copy] and Block_copy(^{...}).
14707   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14708     Selector Cmd = ME->getSelector();
14709     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14710       e = ME->getInstanceReceiver();
14711       if (!e)
14712         return nullptr;
14713       e = e->IgnoreParenCasts();
14714     }
14715   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14716     if (CE->getNumArgs() == 1) {
14717       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14718       if (Fn) {
14719         const IdentifierInfo *FnI = Fn->getIdentifier();
14720         if (FnI && FnI->isStr("_Block_copy")) {
14721           e = CE->getArg(0)->IgnoreParenCasts();
14722         }
14723       }
14724     }
14725   }
14726 
14727   BlockExpr *block = dyn_cast<BlockExpr>(e);
14728   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14729     return nullptr;
14730 
14731   FindCaptureVisitor visitor(S.Context, owner.Variable);
14732   visitor.Visit(block->getBlockDecl()->getBody());
14733   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14734 }
14735 
14736 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14737                                 RetainCycleOwner &owner) {
14738   assert(capturer);
14739   assert(owner.Variable && owner.Loc.isValid());
14740 
14741   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14742     << owner.Variable << capturer->getSourceRange();
14743   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14744     << owner.Indirect << owner.Range;
14745 }
14746 
14747 /// Check for a keyword selector that starts with the word 'add' or
14748 /// 'set'.
14749 static bool isSetterLikeSelector(Selector sel) {
14750   if (sel.isUnarySelector()) return false;
14751 
14752   StringRef str = sel.getNameForSlot(0);
14753   while (!str.empty() && str.front() == '_') str = str.substr(1);
14754   if (str.startswith("set"))
14755     str = str.substr(3);
14756   else if (str.startswith("add")) {
14757     // Specially allow 'addOperationWithBlock:'.
14758     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14759       return false;
14760     str = str.substr(3);
14761   }
14762   else
14763     return false;
14764 
14765   if (str.empty()) return true;
14766   return !isLowercase(str.front());
14767 }
14768 
14769 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14770                                                     ObjCMessageExpr *Message) {
14771   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14772                                                 Message->getReceiverInterface(),
14773                                                 NSAPI::ClassId_NSMutableArray);
14774   if (!IsMutableArray) {
14775     return None;
14776   }
14777 
14778   Selector Sel = Message->getSelector();
14779 
14780   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14781     S.NSAPIObj->getNSArrayMethodKind(Sel);
14782   if (!MKOpt) {
14783     return None;
14784   }
14785 
14786   NSAPI::NSArrayMethodKind MK = *MKOpt;
14787 
14788   switch (MK) {
14789     case NSAPI::NSMutableArr_addObject:
14790     case NSAPI::NSMutableArr_insertObjectAtIndex:
14791     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14792       return 0;
14793     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14794       return 1;
14795 
14796     default:
14797       return None;
14798   }
14799 
14800   return None;
14801 }
14802 
14803 static
14804 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14805                                                   ObjCMessageExpr *Message) {
14806   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14807                                             Message->getReceiverInterface(),
14808                                             NSAPI::ClassId_NSMutableDictionary);
14809   if (!IsMutableDictionary) {
14810     return None;
14811   }
14812 
14813   Selector Sel = Message->getSelector();
14814 
14815   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14816     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14817   if (!MKOpt) {
14818     return None;
14819   }
14820 
14821   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14822 
14823   switch (MK) {
14824     case NSAPI::NSMutableDict_setObjectForKey:
14825     case NSAPI::NSMutableDict_setValueForKey:
14826     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14827       return 0;
14828 
14829     default:
14830       return None;
14831   }
14832 
14833   return None;
14834 }
14835 
14836 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14837   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14838                                                 Message->getReceiverInterface(),
14839                                                 NSAPI::ClassId_NSMutableSet);
14840 
14841   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14842                                             Message->getReceiverInterface(),
14843                                             NSAPI::ClassId_NSMutableOrderedSet);
14844   if (!IsMutableSet && !IsMutableOrderedSet) {
14845     return None;
14846   }
14847 
14848   Selector Sel = Message->getSelector();
14849 
14850   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14851   if (!MKOpt) {
14852     return None;
14853   }
14854 
14855   NSAPI::NSSetMethodKind MK = *MKOpt;
14856 
14857   switch (MK) {
14858     case NSAPI::NSMutableSet_addObject:
14859     case NSAPI::NSOrderedSet_setObjectAtIndex:
14860     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14861     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14862       return 0;
14863     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14864       return 1;
14865   }
14866 
14867   return None;
14868 }
14869 
14870 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14871   if (!Message->isInstanceMessage()) {
14872     return;
14873   }
14874 
14875   Optional<int> ArgOpt;
14876 
14877   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14878       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14879       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14880     return;
14881   }
14882 
14883   int ArgIndex = *ArgOpt;
14884 
14885   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14886   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14887     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14888   }
14889 
14890   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14891     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14892       if (ArgRE->isObjCSelfExpr()) {
14893         Diag(Message->getSourceRange().getBegin(),
14894              diag::warn_objc_circular_container)
14895           << ArgRE->getDecl() << StringRef("'super'");
14896       }
14897     }
14898   } else {
14899     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14900 
14901     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14902       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14903     }
14904 
14905     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14906       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14907         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14908           ValueDecl *Decl = ReceiverRE->getDecl();
14909           Diag(Message->getSourceRange().getBegin(),
14910                diag::warn_objc_circular_container)
14911             << Decl << Decl;
14912           if (!ArgRE->isObjCSelfExpr()) {
14913             Diag(Decl->getLocation(),
14914                  diag::note_objc_circular_container_declared_here)
14915               << Decl;
14916           }
14917         }
14918       }
14919     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14920       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14921         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14922           ObjCIvarDecl *Decl = IvarRE->getDecl();
14923           Diag(Message->getSourceRange().getBegin(),
14924                diag::warn_objc_circular_container)
14925             << Decl << Decl;
14926           Diag(Decl->getLocation(),
14927                diag::note_objc_circular_container_declared_here)
14928             << Decl;
14929         }
14930       }
14931     }
14932   }
14933 }
14934 
14935 /// Check a message send to see if it's likely to cause a retain cycle.
14936 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14937   // Only check instance methods whose selector looks like a setter.
14938   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14939     return;
14940 
14941   // Try to find a variable that the receiver is strongly owned by.
14942   RetainCycleOwner owner;
14943   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14944     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14945       return;
14946   } else {
14947     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14948     owner.Variable = getCurMethodDecl()->getSelfDecl();
14949     owner.Loc = msg->getSuperLoc();
14950     owner.Range = msg->getSuperLoc();
14951   }
14952 
14953   // Check whether the receiver is captured by any of the arguments.
14954   const ObjCMethodDecl *MD = msg->getMethodDecl();
14955   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14956     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14957       // noescape blocks should not be retained by the method.
14958       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14959         continue;
14960       return diagnoseRetainCycle(*this, capturer, owner);
14961     }
14962   }
14963 }
14964 
14965 /// Check a property assign to see if it's likely to cause a retain cycle.
14966 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14967   RetainCycleOwner owner;
14968   if (!findRetainCycleOwner(*this, receiver, owner))
14969     return;
14970 
14971   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14972     diagnoseRetainCycle(*this, capturer, owner);
14973 }
14974 
14975 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14976   RetainCycleOwner Owner;
14977   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14978     return;
14979 
14980   // Because we don't have an expression for the variable, we have to set the
14981   // location explicitly here.
14982   Owner.Loc = Var->getLocation();
14983   Owner.Range = Var->getSourceRange();
14984 
14985   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14986     diagnoseRetainCycle(*this, Capturer, Owner);
14987 }
14988 
14989 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14990                                      Expr *RHS, bool isProperty) {
14991   // Check if RHS is an Objective-C object literal, which also can get
14992   // immediately zapped in a weak reference.  Note that we explicitly
14993   // allow ObjCStringLiterals, since those are designed to never really die.
14994   RHS = RHS->IgnoreParenImpCasts();
14995 
14996   // This enum needs to match with the 'select' in
14997   // warn_objc_arc_literal_assign (off-by-1).
14998   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14999   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15000     return false;
15001 
15002   S.Diag(Loc, diag::warn_arc_literal_assign)
15003     << (unsigned) Kind
15004     << (isProperty ? 0 : 1)
15005     << RHS->getSourceRange();
15006 
15007   return true;
15008 }
15009 
15010 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15011                                     Qualifiers::ObjCLifetime LT,
15012                                     Expr *RHS, bool isProperty) {
15013   // Strip off any implicit cast added to get to the one ARC-specific.
15014   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15015     if (cast->getCastKind() == CK_ARCConsumeObject) {
15016       S.Diag(Loc, diag::warn_arc_retained_assign)
15017         << (LT == Qualifiers::OCL_ExplicitNone)
15018         << (isProperty ? 0 : 1)
15019         << RHS->getSourceRange();
15020       return true;
15021     }
15022     RHS = cast->getSubExpr();
15023   }
15024 
15025   if (LT == Qualifiers::OCL_Weak &&
15026       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15027     return true;
15028 
15029   return false;
15030 }
15031 
15032 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15033                               QualType LHS, Expr *RHS) {
15034   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15035 
15036   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15037     return false;
15038 
15039   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15040     return true;
15041 
15042   return false;
15043 }
15044 
15045 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15046                               Expr *LHS, Expr *RHS) {
15047   QualType LHSType;
15048   // PropertyRef on LHS type need be directly obtained from
15049   // its declaration as it has a PseudoType.
15050   ObjCPropertyRefExpr *PRE
15051     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15052   if (PRE && !PRE->isImplicitProperty()) {
15053     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15054     if (PD)
15055       LHSType = PD->getType();
15056   }
15057 
15058   if (LHSType.isNull())
15059     LHSType = LHS->getType();
15060 
15061   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15062 
15063   if (LT == Qualifiers::OCL_Weak) {
15064     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15065       getCurFunction()->markSafeWeakUse(LHS);
15066   }
15067 
15068   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15069     return;
15070 
15071   // FIXME. Check for other life times.
15072   if (LT != Qualifiers::OCL_None)
15073     return;
15074 
15075   if (PRE) {
15076     if (PRE->isImplicitProperty())
15077       return;
15078     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15079     if (!PD)
15080       return;
15081 
15082     unsigned Attributes = PD->getPropertyAttributes();
15083     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15084       // when 'assign' attribute was not explicitly specified
15085       // by user, ignore it and rely on property type itself
15086       // for lifetime info.
15087       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15088       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15089           LHSType->isObjCRetainableType())
15090         return;
15091 
15092       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15093         if (cast->getCastKind() == CK_ARCConsumeObject) {
15094           Diag(Loc, diag::warn_arc_retained_property_assign)
15095           << RHS->getSourceRange();
15096           return;
15097         }
15098         RHS = cast->getSubExpr();
15099       }
15100     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15101       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15102         return;
15103     }
15104   }
15105 }
15106 
15107 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15108 
15109 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15110                                         SourceLocation StmtLoc,
15111                                         const NullStmt *Body) {
15112   // Do not warn if the body is a macro that expands to nothing, e.g:
15113   //
15114   // #define CALL(x)
15115   // if (condition)
15116   //   CALL(0);
15117   if (Body->hasLeadingEmptyMacro())
15118     return false;
15119 
15120   // Get line numbers of statement and body.
15121   bool StmtLineInvalid;
15122   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15123                                                       &StmtLineInvalid);
15124   if (StmtLineInvalid)
15125     return false;
15126 
15127   bool BodyLineInvalid;
15128   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15129                                                       &BodyLineInvalid);
15130   if (BodyLineInvalid)
15131     return false;
15132 
15133   // Warn if null statement and body are on the same line.
15134   if (StmtLine != BodyLine)
15135     return false;
15136 
15137   return true;
15138 }
15139 
15140 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15141                                  const Stmt *Body,
15142                                  unsigned DiagID) {
15143   // Since this is a syntactic check, don't emit diagnostic for template
15144   // instantiations, this just adds noise.
15145   if (CurrentInstantiationScope)
15146     return;
15147 
15148   // The body should be a null statement.
15149   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15150   if (!NBody)
15151     return;
15152 
15153   // Do the usual checks.
15154   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15155     return;
15156 
15157   Diag(NBody->getSemiLoc(), DiagID);
15158   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15159 }
15160 
15161 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15162                                  const Stmt *PossibleBody) {
15163   assert(!CurrentInstantiationScope); // Ensured by caller
15164 
15165   SourceLocation StmtLoc;
15166   const Stmt *Body;
15167   unsigned DiagID;
15168   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15169     StmtLoc = FS->getRParenLoc();
15170     Body = FS->getBody();
15171     DiagID = diag::warn_empty_for_body;
15172   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15173     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15174     Body = WS->getBody();
15175     DiagID = diag::warn_empty_while_body;
15176   } else
15177     return; // Neither `for' nor `while'.
15178 
15179   // The body should be a null statement.
15180   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15181   if (!NBody)
15182     return;
15183 
15184   // Skip expensive checks if diagnostic is disabled.
15185   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15186     return;
15187 
15188   // Do the usual checks.
15189   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15190     return;
15191 
15192   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15193   // noise level low, emit diagnostics only if for/while is followed by a
15194   // CompoundStmt, e.g.:
15195   //    for (int i = 0; i < n; i++);
15196   //    {
15197   //      a(i);
15198   //    }
15199   // or if for/while is followed by a statement with more indentation
15200   // than for/while itself:
15201   //    for (int i = 0; i < n; i++);
15202   //      a(i);
15203   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15204   if (!ProbableTypo) {
15205     bool BodyColInvalid;
15206     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15207         PossibleBody->getBeginLoc(), &BodyColInvalid);
15208     if (BodyColInvalid)
15209       return;
15210 
15211     bool StmtColInvalid;
15212     unsigned StmtCol =
15213         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15214     if (StmtColInvalid)
15215       return;
15216 
15217     if (BodyCol > StmtCol)
15218       ProbableTypo = true;
15219   }
15220 
15221   if (ProbableTypo) {
15222     Diag(NBody->getSemiLoc(), DiagID);
15223     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15224   }
15225 }
15226 
15227 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15228 
15229 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15230 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15231                              SourceLocation OpLoc) {
15232   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15233     return;
15234 
15235   if (inTemplateInstantiation())
15236     return;
15237 
15238   // Strip parens and casts away.
15239   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15240   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15241 
15242   // Check for a call expression
15243   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15244   if (!CE || CE->getNumArgs() != 1)
15245     return;
15246 
15247   // Check for a call to std::move
15248   if (!CE->isCallToStdMove())
15249     return;
15250 
15251   // Get argument from std::move
15252   RHSExpr = CE->getArg(0);
15253 
15254   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15255   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15256 
15257   // Two DeclRefExpr's, check that the decls are the same.
15258   if (LHSDeclRef && RHSDeclRef) {
15259     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15260       return;
15261     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15262         RHSDeclRef->getDecl()->getCanonicalDecl())
15263       return;
15264 
15265     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15266                                         << LHSExpr->getSourceRange()
15267                                         << RHSExpr->getSourceRange();
15268     return;
15269   }
15270 
15271   // Member variables require a different approach to check for self moves.
15272   // MemberExpr's are the same if every nested MemberExpr refers to the same
15273   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15274   // the base Expr's are CXXThisExpr's.
15275   const Expr *LHSBase = LHSExpr;
15276   const Expr *RHSBase = RHSExpr;
15277   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15278   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15279   if (!LHSME || !RHSME)
15280     return;
15281 
15282   while (LHSME && RHSME) {
15283     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15284         RHSME->getMemberDecl()->getCanonicalDecl())
15285       return;
15286 
15287     LHSBase = LHSME->getBase();
15288     RHSBase = RHSME->getBase();
15289     LHSME = dyn_cast<MemberExpr>(LHSBase);
15290     RHSME = dyn_cast<MemberExpr>(RHSBase);
15291   }
15292 
15293   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15294   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15295   if (LHSDeclRef && RHSDeclRef) {
15296     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15297       return;
15298     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15299         RHSDeclRef->getDecl()->getCanonicalDecl())
15300       return;
15301 
15302     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15303                                         << LHSExpr->getSourceRange()
15304                                         << RHSExpr->getSourceRange();
15305     return;
15306   }
15307 
15308   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15309     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15310                                         << LHSExpr->getSourceRange()
15311                                         << RHSExpr->getSourceRange();
15312 }
15313 
15314 //===--- Layout compatibility ----------------------------------------------//
15315 
15316 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15317 
15318 /// Check if two enumeration types are layout-compatible.
15319 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15320   // C++11 [dcl.enum] p8:
15321   // Two enumeration types are layout-compatible if they have the same
15322   // underlying type.
15323   return ED1->isComplete() && ED2->isComplete() &&
15324          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15325 }
15326 
15327 /// Check if two fields are layout-compatible.
15328 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15329                                FieldDecl *Field2) {
15330   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15331     return false;
15332 
15333   if (Field1->isBitField() != Field2->isBitField())
15334     return false;
15335 
15336   if (Field1->isBitField()) {
15337     // Make sure that the bit-fields are the same length.
15338     unsigned Bits1 = Field1->getBitWidthValue(C);
15339     unsigned Bits2 = Field2->getBitWidthValue(C);
15340 
15341     if (Bits1 != Bits2)
15342       return false;
15343   }
15344 
15345   return true;
15346 }
15347 
15348 /// Check if two standard-layout structs are layout-compatible.
15349 /// (C++11 [class.mem] p17)
15350 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15351                                      RecordDecl *RD2) {
15352   // If both records are C++ classes, check that base classes match.
15353   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15354     // If one of records is a CXXRecordDecl we are in C++ mode,
15355     // thus the other one is a CXXRecordDecl, too.
15356     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15357     // Check number of base classes.
15358     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15359       return false;
15360 
15361     // Check the base classes.
15362     for (CXXRecordDecl::base_class_const_iterator
15363                Base1 = D1CXX->bases_begin(),
15364            BaseEnd1 = D1CXX->bases_end(),
15365               Base2 = D2CXX->bases_begin();
15366          Base1 != BaseEnd1;
15367          ++Base1, ++Base2) {
15368       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15369         return false;
15370     }
15371   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15372     // If only RD2 is a C++ class, it should have zero base classes.
15373     if (D2CXX->getNumBases() > 0)
15374       return false;
15375   }
15376 
15377   // Check the fields.
15378   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15379                              Field2End = RD2->field_end(),
15380                              Field1 = RD1->field_begin(),
15381                              Field1End = RD1->field_end();
15382   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15383     if (!isLayoutCompatible(C, *Field1, *Field2))
15384       return false;
15385   }
15386   if (Field1 != Field1End || Field2 != Field2End)
15387     return false;
15388 
15389   return true;
15390 }
15391 
15392 /// Check if two standard-layout unions are layout-compatible.
15393 /// (C++11 [class.mem] p18)
15394 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15395                                     RecordDecl *RD2) {
15396   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15397   for (auto *Field2 : RD2->fields())
15398     UnmatchedFields.insert(Field2);
15399 
15400   for (auto *Field1 : RD1->fields()) {
15401     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15402         I = UnmatchedFields.begin(),
15403         E = UnmatchedFields.end();
15404 
15405     for ( ; I != E; ++I) {
15406       if (isLayoutCompatible(C, Field1, *I)) {
15407         bool Result = UnmatchedFields.erase(*I);
15408         (void) Result;
15409         assert(Result);
15410         break;
15411       }
15412     }
15413     if (I == E)
15414       return false;
15415   }
15416 
15417   return UnmatchedFields.empty();
15418 }
15419 
15420 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15421                                RecordDecl *RD2) {
15422   if (RD1->isUnion() != RD2->isUnion())
15423     return false;
15424 
15425   if (RD1->isUnion())
15426     return isLayoutCompatibleUnion(C, RD1, RD2);
15427   else
15428     return isLayoutCompatibleStruct(C, RD1, RD2);
15429 }
15430 
15431 /// Check if two types are layout-compatible in C++11 sense.
15432 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15433   if (T1.isNull() || T2.isNull())
15434     return false;
15435 
15436   // C++11 [basic.types] p11:
15437   // If two types T1 and T2 are the same type, then T1 and T2 are
15438   // layout-compatible types.
15439   if (C.hasSameType(T1, T2))
15440     return true;
15441 
15442   T1 = T1.getCanonicalType().getUnqualifiedType();
15443   T2 = T2.getCanonicalType().getUnqualifiedType();
15444 
15445   const Type::TypeClass TC1 = T1->getTypeClass();
15446   const Type::TypeClass TC2 = T2->getTypeClass();
15447 
15448   if (TC1 != TC2)
15449     return false;
15450 
15451   if (TC1 == Type::Enum) {
15452     return isLayoutCompatible(C,
15453                               cast<EnumType>(T1)->getDecl(),
15454                               cast<EnumType>(T2)->getDecl());
15455   } else if (TC1 == Type::Record) {
15456     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15457       return false;
15458 
15459     return isLayoutCompatible(C,
15460                               cast<RecordType>(T1)->getDecl(),
15461                               cast<RecordType>(T2)->getDecl());
15462   }
15463 
15464   return false;
15465 }
15466 
15467 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15468 
15469 /// Given a type tag expression find the type tag itself.
15470 ///
15471 /// \param TypeExpr Type tag expression, as it appears in user's code.
15472 ///
15473 /// \param VD Declaration of an identifier that appears in a type tag.
15474 ///
15475 /// \param MagicValue Type tag magic value.
15476 ///
15477 /// \param isConstantEvaluated wether the evalaution should be performed in
15478 
15479 /// constant context.
15480 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15481                             const ValueDecl **VD, uint64_t *MagicValue,
15482                             bool isConstantEvaluated) {
15483   while(true) {
15484     if (!TypeExpr)
15485       return false;
15486 
15487     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15488 
15489     switch (TypeExpr->getStmtClass()) {
15490     case Stmt::UnaryOperatorClass: {
15491       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15492       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15493         TypeExpr = UO->getSubExpr();
15494         continue;
15495       }
15496       return false;
15497     }
15498 
15499     case Stmt::DeclRefExprClass: {
15500       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15501       *VD = DRE->getDecl();
15502       return true;
15503     }
15504 
15505     case Stmt::IntegerLiteralClass: {
15506       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15507       llvm::APInt MagicValueAPInt = IL->getValue();
15508       if (MagicValueAPInt.getActiveBits() <= 64) {
15509         *MagicValue = MagicValueAPInt.getZExtValue();
15510         return true;
15511       } else
15512         return false;
15513     }
15514 
15515     case Stmt::BinaryConditionalOperatorClass:
15516     case Stmt::ConditionalOperatorClass: {
15517       const AbstractConditionalOperator *ACO =
15518           cast<AbstractConditionalOperator>(TypeExpr);
15519       bool Result;
15520       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15521                                                      isConstantEvaluated)) {
15522         if (Result)
15523           TypeExpr = ACO->getTrueExpr();
15524         else
15525           TypeExpr = ACO->getFalseExpr();
15526         continue;
15527       }
15528       return false;
15529     }
15530 
15531     case Stmt::BinaryOperatorClass: {
15532       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15533       if (BO->getOpcode() == BO_Comma) {
15534         TypeExpr = BO->getRHS();
15535         continue;
15536       }
15537       return false;
15538     }
15539 
15540     default:
15541       return false;
15542     }
15543   }
15544 }
15545 
15546 /// Retrieve the C type corresponding to type tag TypeExpr.
15547 ///
15548 /// \param TypeExpr Expression that specifies a type tag.
15549 ///
15550 /// \param MagicValues Registered magic values.
15551 ///
15552 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15553 ///        kind.
15554 ///
15555 /// \param TypeInfo Information about the corresponding C type.
15556 ///
15557 /// \param isConstantEvaluated wether the evalaution should be performed in
15558 /// constant context.
15559 ///
15560 /// \returns true if the corresponding C type was found.
15561 static bool GetMatchingCType(
15562     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15563     const ASTContext &Ctx,
15564     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15565         *MagicValues,
15566     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15567     bool isConstantEvaluated) {
15568   FoundWrongKind = false;
15569 
15570   // Variable declaration that has type_tag_for_datatype attribute.
15571   const ValueDecl *VD = nullptr;
15572 
15573   uint64_t MagicValue;
15574 
15575   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15576     return false;
15577 
15578   if (VD) {
15579     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15580       if (I->getArgumentKind() != ArgumentKind) {
15581         FoundWrongKind = true;
15582         return false;
15583       }
15584       TypeInfo.Type = I->getMatchingCType();
15585       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15586       TypeInfo.MustBeNull = I->getMustBeNull();
15587       return true;
15588     }
15589     return false;
15590   }
15591 
15592   if (!MagicValues)
15593     return false;
15594 
15595   llvm::DenseMap<Sema::TypeTagMagicValue,
15596                  Sema::TypeTagData>::const_iterator I =
15597       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15598   if (I == MagicValues->end())
15599     return false;
15600 
15601   TypeInfo = I->second;
15602   return true;
15603 }
15604 
15605 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15606                                       uint64_t MagicValue, QualType Type,
15607                                       bool LayoutCompatible,
15608                                       bool MustBeNull) {
15609   if (!TypeTagForDatatypeMagicValues)
15610     TypeTagForDatatypeMagicValues.reset(
15611         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15612 
15613   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15614   (*TypeTagForDatatypeMagicValues)[Magic] =
15615       TypeTagData(Type, LayoutCompatible, MustBeNull);
15616 }
15617 
15618 static bool IsSameCharType(QualType T1, QualType T2) {
15619   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15620   if (!BT1)
15621     return false;
15622 
15623   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15624   if (!BT2)
15625     return false;
15626 
15627   BuiltinType::Kind T1Kind = BT1->getKind();
15628   BuiltinType::Kind T2Kind = BT2->getKind();
15629 
15630   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15631          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15632          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15633          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15634 }
15635 
15636 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15637                                     const ArrayRef<const Expr *> ExprArgs,
15638                                     SourceLocation CallSiteLoc) {
15639   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15640   bool IsPointerAttr = Attr->getIsPointer();
15641 
15642   // Retrieve the argument representing the 'type_tag'.
15643   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15644   if (TypeTagIdxAST >= ExprArgs.size()) {
15645     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15646         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15647     return;
15648   }
15649   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15650   bool FoundWrongKind;
15651   TypeTagData TypeInfo;
15652   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15653                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15654                         TypeInfo, isConstantEvaluated())) {
15655     if (FoundWrongKind)
15656       Diag(TypeTagExpr->getExprLoc(),
15657            diag::warn_type_tag_for_datatype_wrong_kind)
15658         << TypeTagExpr->getSourceRange();
15659     return;
15660   }
15661 
15662   // Retrieve the argument representing the 'arg_idx'.
15663   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15664   if (ArgumentIdxAST >= ExprArgs.size()) {
15665     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15666         << 1 << Attr->getArgumentIdx().getSourceIndex();
15667     return;
15668   }
15669   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15670   if (IsPointerAttr) {
15671     // Skip implicit cast of pointer to `void *' (as a function argument).
15672     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15673       if (ICE->getType()->isVoidPointerType() &&
15674           ICE->getCastKind() == CK_BitCast)
15675         ArgumentExpr = ICE->getSubExpr();
15676   }
15677   QualType ArgumentType = ArgumentExpr->getType();
15678 
15679   // Passing a `void*' pointer shouldn't trigger a warning.
15680   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15681     return;
15682 
15683   if (TypeInfo.MustBeNull) {
15684     // Type tag with matching void type requires a null pointer.
15685     if (!ArgumentExpr->isNullPointerConstant(Context,
15686                                              Expr::NPC_ValueDependentIsNotNull)) {
15687       Diag(ArgumentExpr->getExprLoc(),
15688            diag::warn_type_safety_null_pointer_required)
15689           << ArgumentKind->getName()
15690           << ArgumentExpr->getSourceRange()
15691           << TypeTagExpr->getSourceRange();
15692     }
15693     return;
15694   }
15695 
15696   QualType RequiredType = TypeInfo.Type;
15697   if (IsPointerAttr)
15698     RequiredType = Context.getPointerType(RequiredType);
15699 
15700   bool mismatch = false;
15701   if (!TypeInfo.LayoutCompatible) {
15702     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15703 
15704     // C++11 [basic.fundamental] p1:
15705     // Plain char, signed char, and unsigned char are three distinct types.
15706     //
15707     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15708     // char' depending on the current char signedness mode.
15709     if (mismatch)
15710       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15711                                            RequiredType->getPointeeType())) ||
15712           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15713         mismatch = false;
15714   } else
15715     if (IsPointerAttr)
15716       mismatch = !isLayoutCompatible(Context,
15717                                      ArgumentType->getPointeeType(),
15718                                      RequiredType->getPointeeType());
15719     else
15720       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15721 
15722   if (mismatch)
15723     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15724         << ArgumentType << ArgumentKind
15725         << TypeInfo.LayoutCompatible << RequiredType
15726         << ArgumentExpr->getSourceRange()
15727         << TypeTagExpr->getSourceRange();
15728 }
15729 
15730 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15731                                          CharUnits Alignment) {
15732   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15733 }
15734 
15735 void Sema::DiagnoseMisalignedMembers() {
15736   for (MisalignedMember &m : MisalignedMembers) {
15737     const NamedDecl *ND = m.RD;
15738     if (ND->getName().empty()) {
15739       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15740         ND = TD;
15741     }
15742     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15743         << m.MD << ND << m.E->getSourceRange();
15744   }
15745   MisalignedMembers.clear();
15746 }
15747 
15748 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15749   E = E->IgnoreParens();
15750   if (!T->isPointerType() && !T->isIntegerType())
15751     return;
15752   if (isa<UnaryOperator>(E) &&
15753       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15754     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15755     if (isa<MemberExpr>(Op)) {
15756       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15757       if (MA != MisalignedMembers.end() &&
15758           (T->isIntegerType() ||
15759            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15760                                    Context.getTypeAlignInChars(
15761                                        T->getPointeeType()) <= MA->Alignment))))
15762         MisalignedMembers.erase(MA);
15763     }
15764   }
15765 }
15766 
15767 void Sema::RefersToMemberWithReducedAlignment(
15768     Expr *E,
15769     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15770         Action) {
15771   const auto *ME = dyn_cast<MemberExpr>(E);
15772   if (!ME)
15773     return;
15774 
15775   // No need to check expressions with an __unaligned-qualified type.
15776   if (E->getType().getQualifiers().hasUnaligned())
15777     return;
15778 
15779   // For a chain of MemberExpr like "a.b.c.d" this list
15780   // will keep FieldDecl's like [d, c, b].
15781   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15782   const MemberExpr *TopME = nullptr;
15783   bool AnyIsPacked = false;
15784   do {
15785     QualType BaseType = ME->getBase()->getType();
15786     if (BaseType->isDependentType())
15787       return;
15788     if (ME->isArrow())
15789       BaseType = BaseType->getPointeeType();
15790     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15791     if (RD->isInvalidDecl())
15792       return;
15793 
15794     ValueDecl *MD = ME->getMemberDecl();
15795     auto *FD = dyn_cast<FieldDecl>(MD);
15796     // We do not care about non-data members.
15797     if (!FD || FD->isInvalidDecl())
15798       return;
15799 
15800     AnyIsPacked =
15801         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15802     ReverseMemberChain.push_back(FD);
15803 
15804     TopME = ME;
15805     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15806   } while (ME);
15807   assert(TopME && "We did not compute a topmost MemberExpr!");
15808 
15809   // Not the scope of this diagnostic.
15810   if (!AnyIsPacked)
15811     return;
15812 
15813   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15814   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15815   // TODO: The innermost base of the member expression may be too complicated.
15816   // For now, just disregard these cases. This is left for future
15817   // improvement.
15818   if (!DRE && !isa<CXXThisExpr>(TopBase))
15819       return;
15820 
15821   // Alignment expected by the whole expression.
15822   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15823 
15824   // No need to do anything else with this case.
15825   if (ExpectedAlignment.isOne())
15826     return;
15827 
15828   // Synthesize offset of the whole access.
15829   CharUnits Offset;
15830   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15831        I++) {
15832     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15833   }
15834 
15835   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15836   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15837       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15838 
15839   // The base expression of the innermost MemberExpr may give
15840   // stronger guarantees than the class containing the member.
15841   if (DRE && !TopME->isArrow()) {
15842     const ValueDecl *VD = DRE->getDecl();
15843     if (!VD->getType()->isReferenceType())
15844       CompleteObjectAlignment =
15845           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15846   }
15847 
15848   // Check if the synthesized offset fulfills the alignment.
15849   if (Offset % ExpectedAlignment != 0 ||
15850       // It may fulfill the offset it but the effective alignment may still be
15851       // lower than the expected expression alignment.
15852       CompleteObjectAlignment < ExpectedAlignment) {
15853     // If this happens, we want to determine a sensible culprit of this.
15854     // Intuitively, watching the chain of member expressions from right to
15855     // left, we start with the required alignment (as required by the field
15856     // type) but some packed attribute in that chain has reduced the alignment.
15857     // It may happen that another packed structure increases it again. But if
15858     // we are here such increase has not been enough. So pointing the first
15859     // FieldDecl that either is packed or else its RecordDecl is,
15860     // seems reasonable.
15861     FieldDecl *FD = nullptr;
15862     CharUnits Alignment;
15863     for (FieldDecl *FDI : ReverseMemberChain) {
15864       if (FDI->hasAttr<PackedAttr>() ||
15865           FDI->getParent()->hasAttr<PackedAttr>()) {
15866         FD = FDI;
15867         Alignment = std::min(
15868             Context.getTypeAlignInChars(FD->getType()),
15869             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15870         break;
15871       }
15872     }
15873     assert(FD && "We did not find a packed FieldDecl!");
15874     Action(E, FD->getParent(), FD, Alignment);
15875   }
15876 }
15877 
15878 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15879   using namespace std::placeholders;
15880 
15881   RefersToMemberWithReducedAlignment(
15882       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15883                      _2, _3, _4));
15884 }
15885 
15886 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15887                                             ExprResult CallResult) {
15888   if (checkArgCount(*this, TheCall, 1))
15889     return ExprError();
15890 
15891   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15892   if (MatrixArg.isInvalid())
15893     return MatrixArg;
15894   Expr *Matrix = MatrixArg.get();
15895 
15896   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15897   if (!MType) {
15898     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15899     return ExprError();
15900   }
15901 
15902   // Create returned matrix type by swapping rows and columns of the argument
15903   // matrix type.
15904   QualType ResultType = Context.getConstantMatrixType(
15905       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15906 
15907   // Change the return type to the type of the returned matrix.
15908   TheCall->setType(ResultType);
15909 
15910   // Update call argument to use the possibly converted matrix argument.
15911   TheCall->setArg(0, Matrix);
15912   return CallResult;
15913 }
15914 
15915 // Get and verify the matrix dimensions.
15916 static llvm::Optional<unsigned>
15917 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15918   SourceLocation ErrorPos;
15919   Optional<llvm::APSInt> Value =
15920       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15921   if (!Value) {
15922     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15923         << Name;
15924     return {};
15925   }
15926   uint64_t Dim = Value->getZExtValue();
15927   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15928     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15929         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15930     return {};
15931   }
15932   return Dim;
15933 }
15934 
15935 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15936                                                   ExprResult CallResult) {
15937   if (!getLangOpts().MatrixTypes) {
15938     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15939     return ExprError();
15940   }
15941 
15942   if (checkArgCount(*this, TheCall, 4))
15943     return ExprError();
15944 
15945   unsigned PtrArgIdx = 0;
15946   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15947   Expr *RowsExpr = TheCall->getArg(1);
15948   Expr *ColumnsExpr = TheCall->getArg(2);
15949   Expr *StrideExpr = TheCall->getArg(3);
15950 
15951   bool ArgError = false;
15952 
15953   // Check pointer argument.
15954   {
15955     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15956     if (PtrConv.isInvalid())
15957       return PtrConv;
15958     PtrExpr = PtrConv.get();
15959     TheCall->setArg(0, PtrExpr);
15960     if (PtrExpr->isTypeDependent()) {
15961       TheCall->setType(Context.DependentTy);
15962       return TheCall;
15963     }
15964   }
15965 
15966   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15967   QualType ElementTy;
15968   if (!PtrTy) {
15969     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15970         << PtrArgIdx + 1;
15971     ArgError = true;
15972   } else {
15973     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15974 
15975     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15976       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15977           << PtrArgIdx + 1;
15978       ArgError = true;
15979     }
15980   }
15981 
15982   // Apply default Lvalue conversions and convert the expression to size_t.
15983   auto ApplyArgumentConversions = [this](Expr *E) {
15984     ExprResult Conv = DefaultLvalueConversion(E);
15985     if (Conv.isInvalid())
15986       return Conv;
15987 
15988     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15989   };
15990 
15991   // Apply conversion to row and column expressions.
15992   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15993   if (!RowsConv.isInvalid()) {
15994     RowsExpr = RowsConv.get();
15995     TheCall->setArg(1, RowsExpr);
15996   } else
15997     RowsExpr = nullptr;
15998 
15999   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16000   if (!ColumnsConv.isInvalid()) {
16001     ColumnsExpr = ColumnsConv.get();
16002     TheCall->setArg(2, ColumnsExpr);
16003   } else
16004     ColumnsExpr = nullptr;
16005 
16006   // If any any part of the result matrix type is still pending, just use
16007   // Context.DependentTy, until all parts are resolved.
16008   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16009       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16010     TheCall->setType(Context.DependentTy);
16011     return CallResult;
16012   }
16013 
16014   // Check row and column dimenions.
16015   llvm::Optional<unsigned> MaybeRows;
16016   if (RowsExpr)
16017     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16018 
16019   llvm::Optional<unsigned> MaybeColumns;
16020   if (ColumnsExpr)
16021     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16022 
16023   // Check stride argument.
16024   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16025   if (StrideConv.isInvalid())
16026     return ExprError();
16027   StrideExpr = StrideConv.get();
16028   TheCall->setArg(3, StrideExpr);
16029 
16030   if (MaybeRows) {
16031     if (Optional<llvm::APSInt> Value =
16032             StrideExpr->getIntegerConstantExpr(Context)) {
16033       uint64_t Stride = Value->getZExtValue();
16034       if (Stride < *MaybeRows) {
16035         Diag(StrideExpr->getBeginLoc(),
16036              diag::err_builtin_matrix_stride_too_small);
16037         ArgError = true;
16038       }
16039     }
16040   }
16041 
16042   if (ArgError || !MaybeRows || !MaybeColumns)
16043     return ExprError();
16044 
16045   TheCall->setType(
16046       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16047   return CallResult;
16048 }
16049 
16050 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16051                                                    ExprResult CallResult) {
16052   if (checkArgCount(*this, TheCall, 3))
16053     return ExprError();
16054 
16055   unsigned PtrArgIdx = 1;
16056   Expr *MatrixExpr = TheCall->getArg(0);
16057   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16058   Expr *StrideExpr = TheCall->getArg(2);
16059 
16060   bool ArgError = false;
16061 
16062   {
16063     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16064     if (MatrixConv.isInvalid())
16065       return MatrixConv;
16066     MatrixExpr = MatrixConv.get();
16067     TheCall->setArg(0, MatrixExpr);
16068   }
16069   if (MatrixExpr->isTypeDependent()) {
16070     TheCall->setType(Context.DependentTy);
16071     return TheCall;
16072   }
16073 
16074   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16075   if (!MatrixTy) {
16076     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16077     ArgError = true;
16078   }
16079 
16080   {
16081     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16082     if (PtrConv.isInvalid())
16083       return PtrConv;
16084     PtrExpr = PtrConv.get();
16085     TheCall->setArg(1, PtrExpr);
16086     if (PtrExpr->isTypeDependent()) {
16087       TheCall->setType(Context.DependentTy);
16088       return TheCall;
16089     }
16090   }
16091 
16092   // Check pointer argument.
16093   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16094   if (!PtrTy) {
16095     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16096         << PtrArgIdx + 1;
16097     ArgError = true;
16098   } else {
16099     QualType ElementTy = PtrTy->getPointeeType();
16100     if (ElementTy.isConstQualified()) {
16101       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16102       ArgError = true;
16103     }
16104     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16105     if (MatrixTy &&
16106         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16107       Diag(PtrExpr->getBeginLoc(),
16108            diag::err_builtin_matrix_pointer_arg_mismatch)
16109           << ElementTy << MatrixTy->getElementType();
16110       ArgError = true;
16111     }
16112   }
16113 
16114   // Apply default Lvalue conversions and convert the stride expression to
16115   // size_t.
16116   {
16117     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16118     if (StrideConv.isInvalid())
16119       return StrideConv;
16120 
16121     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16122     if (StrideConv.isInvalid())
16123       return StrideConv;
16124     StrideExpr = StrideConv.get();
16125     TheCall->setArg(2, StrideExpr);
16126   }
16127 
16128   // Check stride argument.
16129   if (MatrixTy) {
16130     if (Optional<llvm::APSInt> Value =
16131             StrideExpr->getIntegerConstantExpr(Context)) {
16132       uint64_t Stride = Value->getZExtValue();
16133       if (Stride < MatrixTy->getNumRows()) {
16134         Diag(StrideExpr->getBeginLoc(),
16135              diag::err_builtin_matrix_stride_too_small);
16136         ArgError = true;
16137       }
16138     }
16139   }
16140 
16141   if (ArgError)
16142     return ExprError();
16143 
16144   return CallResult;
16145 }
16146 
16147 /// \brief Enforce the bounds of a TCB
16148 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16149 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16150 /// and enforce_tcb_leaf attributes.
16151 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16152                                const FunctionDecl *Callee) {
16153   const FunctionDecl *Caller = getCurFunctionDecl();
16154 
16155   // Calls to builtins are not enforced.
16156   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16157       Callee->getBuiltinID() != 0)
16158     return;
16159 
16160   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16161   // all TCBs the callee is a part of.
16162   llvm::StringSet<> CalleeTCBs;
16163   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16164            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16165   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16166            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16167 
16168   // Go through the TCBs the caller is a part of and emit warnings if Caller
16169   // is in a TCB that the Callee is not.
16170   for_each(
16171       Caller->specific_attrs<EnforceTCBAttr>(),
16172       [&](const auto *A) {
16173         StringRef CallerTCB = A->getTCBName();
16174         if (CalleeTCBs.count(CallerTCB) == 0) {
16175           this->Diag(TheCall->getExprLoc(),
16176                      diag::warn_tcb_enforcement_violation) << Callee
16177                                                            << CallerTCB;
16178         }
16179       });
16180 }
16181