xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp (revision 85868e8a1daeaae7a0e48effb2ea2310ae3b02c6)
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/Stmt.h"
34 #include "clang/AST/TemplateBase.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLoc.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/SaveAndRestore.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstddef>
92 #include <cstdint>
93 #include <functional>
94 #include <limits>
95 #include <string>
96 #include <tuple>
97 #include <utility>
98 
99 using namespace clang;
100 using namespace sema;
101 
102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103                                                     unsigned ByteNo) const {
104   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105                                Context.getTargetInfo());
106 }
107 
108 /// Checks that a call expression's argument count is the desired number.
109 /// This is useful when doing custom type-checking.  Returns true on error.
110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111   unsigned argCount = call->getNumArgs();
112   if (argCount == desiredArgCount) return false;
113 
114   if (argCount < desiredArgCount)
115     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116            << 0 /*function call*/ << desiredArgCount << argCount
117            << call->getSourceRange();
118 
119   // Highlight all the excess arguments.
120   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
121                     call->getArg(argCount - 1)->getEndLoc());
122 
123   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124     << 0 /*function call*/ << desiredArgCount << argCount
125     << call->getArg(1)->getSourceRange();
126 }
127 
128 /// Check that the first argument to __builtin_annotation is an integer
129 /// and the second argument is a non-wide string literal.
130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131   if (checkArgCount(S, TheCall, 2))
132     return true;
133 
134   // First argument should be an integer.
135   Expr *ValArg = TheCall->getArg(0);
136   QualType Ty = ValArg->getType();
137   if (!Ty->isIntegerType()) {
138     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139         << ValArg->getSourceRange();
140     return true;
141   }
142 
143   // Second argument should be a constant string.
144   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146   if (!Literal || !Literal->isAscii()) {
147     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148         << StrArg->getSourceRange();
149     return true;
150   }
151 
152   TheCall->setType(Ty);
153   return false;
154 }
155 
156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157   // We need at least one argument.
158   if (TheCall->getNumArgs() < 1) {
159     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
160         << 0 << 1 << TheCall->getNumArgs()
161         << TheCall->getCallee()->getSourceRange();
162     return true;
163   }
164 
165   // All arguments should be wide string literals.
166   for (Expr *Arg : TheCall->arguments()) {
167     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168     if (!Literal || !Literal->isWide()) {
169       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
170           << Arg->getSourceRange();
171       return true;
172     }
173   }
174 
175   return false;
176 }
177 
178 /// Check that the argument to __builtin_addressof is a glvalue, and set the
179 /// result type to the corresponding pointer type.
180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181   if (checkArgCount(S, TheCall, 1))
182     return true;
183 
184   ExprResult Arg(TheCall->getArg(0));
185   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
186   if (ResultType.isNull())
187     return true;
188 
189   TheCall->setArg(0, Arg.get());
190   TheCall->setType(ResultType);
191   return false;
192 }
193 
194 /// Check the number of arguments and set the result type to
195 /// the argument type.
196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
197   if (checkArgCount(S, TheCall, 1))
198     return true;
199 
200   TheCall->setType(TheCall->getArg(0)->getType());
201   return false;
202 }
203 
204 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
205   if (checkArgCount(S, TheCall, 3))
206     return true;
207 
208   // First two arguments should be integers.
209   for (unsigned I = 0; I < 2; ++I) {
210     ExprResult Arg = TheCall->getArg(I);
211     QualType Ty = Arg.get()->getType();
212     if (!Ty->isIntegerType()) {
213       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
214           << Ty << Arg.get()->getSourceRange();
215       return true;
216     }
217     InitializedEntity Entity = InitializedEntity::InitializeParameter(
218         S.getASTContext(), Ty, /*consume*/ false);
219     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
220     if (Arg.isInvalid())
221       return true;
222     TheCall->setArg(I, Arg.get());
223   }
224 
225   // Third argument should be a pointer to a non-const integer.
226   // IRGen correctly handles volatile, restrict, and address spaces, and
227   // the other qualifiers aren't possible.
228   {
229     ExprResult Arg = TheCall->getArg(2);
230     QualType Ty = Arg.get()->getType();
231     const auto *PtrTy = Ty->getAs<PointerType>();
232     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
233           !PtrTy->getPointeeType().isConstQualified())) {
234       S.Diag(Arg.get()->getBeginLoc(),
235              diag::err_overflow_builtin_must_be_ptr_int)
236           << Ty << Arg.get()->getSourceRange();
237       return true;
238     }
239     InitializedEntity Entity = InitializedEntity::InitializeParameter(
240         S.getASTContext(), Ty, /*consume*/ false);
241     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
242     if (Arg.isInvalid())
243       return true;
244     TheCall->setArg(2, Arg.get());
245   }
246   return false;
247 }
248 
249 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
250   if (checkArgCount(S, BuiltinCall, 2))
251     return true;
252 
253   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
254   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
255   Expr *Call = BuiltinCall->getArg(0);
256   Expr *Chain = BuiltinCall->getArg(1);
257 
258   if (Call->getStmtClass() != Stmt::CallExprClass) {
259     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
260         << Call->getSourceRange();
261     return true;
262   }
263 
264   auto CE = cast<CallExpr>(Call);
265   if (CE->getCallee()->getType()->isBlockPointerType()) {
266     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
267         << Call->getSourceRange();
268     return true;
269   }
270 
271   const Decl *TargetDecl = CE->getCalleeDecl();
272   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
273     if (FD->getBuiltinID()) {
274       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
275           << Call->getSourceRange();
276       return true;
277     }
278 
279   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
280     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
281         << Call->getSourceRange();
282     return true;
283   }
284 
285   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
286   if (ChainResult.isInvalid())
287     return true;
288   if (!ChainResult.get()->getType()->isPointerType()) {
289     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
290         << Chain->getSourceRange();
291     return true;
292   }
293 
294   QualType ReturnTy = CE->getCallReturnType(S.Context);
295   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
296   QualType BuiltinTy = S.Context.getFunctionType(
297       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
298   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
299 
300   Builtin =
301       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
302 
303   BuiltinCall->setType(CE->getType());
304   BuiltinCall->setValueKind(CE->getValueKind());
305   BuiltinCall->setObjectKind(CE->getObjectKind());
306   BuiltinCall->setCallee(Builtin);
307   BuiltinCall->setArg(1, ChainResult.get());
308 
309   return false;
310 }
311 
312 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
313 /// __builtin_*_chk function, then use the object size argument specified in the
314 /// source. Otherwise, infer the object size using __builtin_object_size.
315 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
316                                                CallExpr *TheCall) {
317   // FIXME: There are some more useful checks we could be doing here:
318   //  - Analyze the format string of sprintf to see how much of buffer is used.
319   //  - Evaluate strlen of strcpy arguments, use as object size.
320 
321   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
322       isConstantEvaluated())
323     return;
324 
325   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
326   if (!BuiltinID)
327     return;
328 
329   unsigned DiagID = 0;
330   bool IsChkVariant = false;
331   unsigned SizeIndex, ObjectIndex;
332   switch (BuiltinID) {
333   default:
334     return;
335   case Builtin::BI__builtin___memcpy_chk:
336   case Builtin::BI__builtin___memmove_chk:
337   case Builtin::BI__builtin___memset_chk:
338   case Builtin::BI__builtin___strlcat_chk:
339   case Builtin::BI__builtin___strlcpy_chk:
340   case Builtin::BI__builtin___strncat_chk:
341   case Builtin::BI__builtin___strncpy_chk:
342   case Builtin::BI__builtin___stpncpy_chk:
343   case Builtin::BI__builtin___memccpy_chk: {
344     DiagID = diag::warn_builtin_chk_overflow;
345     IsChkVariant = true;
346     SizeIndex = TheCall->getNumArgs() - 2;
347     ObjectIndex = TheCall->getNumArgs() - 1;
348     break;
349   }
350 
351   case Builtin::BI__builtin___snprintf_chk:
352   case Builtin::BI__builtin___vsnprintf_chk: {
353     DiagID = diag::warn_builtin_chk_overflow;
354     IsChkVariant = true;
355     SizeIndex = 1;
356     ObjectIndex = 3;
357     break;
358   }
359 
360   case Builtin::BIstrncat:
361   case Builtin::BI__builtin_strncat:
362   case Builtin::BIstrncpy:
363   case Builtin::BI__builtin_strncpy:
364   case Builtin::BIstpncpy:
365   case Builtin::BI__builtin_stpncpy: {
366     // Whether these functions overflow depends on the runtime strlen of the
367     // string, not just the buffer size, so emitting the "always overflow"
368     // diagnostic isn't quite right. We should still diagnose passing a buffer
369     // size larger than the destination buffer though; this is a runtime abort
370     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
371     DiagID = diag::warn_fortify_source_size_mismatch;
372     SizeIndex = TheCall->getNumArgs() - 1;
373     ObjectIndex = 0;
374     break;
375   }
376 
377   case Builtin::BImemcpy:
378   case Builtin::BI__builtin_memcpy:
379   case Builtin::BImemmove:
380   case Builtin::BI__builtin_memmove:
381   case Builtin::BImemset:
382   case Builtin::BI__builtin_memset: {
383     DiagID = diag::warn_fortify_source_overflow;
384     SizeIndex = TheCall->getNumArgs() - 1;
385     ObjectIndex = 0;
386     break;
387   }
388   case Builtin::BIsnprintf:
389   case Builtin::BI__builtin_snprintf:
390   case Builtin::BIvsnprintf:
391   case Builtin::BI__builtin_vsnprintf: {
392     DiagID = diag::warn_fortify_source_size_mismatch;
393     SizeIndex = 1;
394     ObjectIndex = 0;
395     break;
396   }
397   }
398 
399   llvm::APSInt ObjectSize;
400   // For __builtin___*_chk, the object size is explicitly provided by the caller
401   // (usually using __builtin_object_size). Use that value to check this call.
402   if (IsChkVariant) {
403     Expr::EvalResult Result;
404     Expr *SizeArg = TheCall->getArg(ObjectIndex);
405     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
406       return;
407     ObjectSize = Result.Val.getInt();
408 
409   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
410   } else {
411     // If the parameter has a pass_object_size attribute, then we should use its
412     // (potentially) more strict checking mode. Otherwise, conservatively assume
413     // type 0.
414     int BOSType = 0;
415     if (const auto *POS =
416             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
417       BOSType = POS->getType();
418 
419     Expr *ObjArg = TheCall->getArg(ObjectIndex);
420     uint64_t Result;
421     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
422       return;
423     // Get the object size in the target's size_t width.
424     const TargetInfo &TI = getASTContext().getTargetInfo();
425     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
426     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
427   }
428 
429   // Evaluate the number of bytes of the object that this call will use.
430   Expr::EvalResult Result;
431   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
432   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
433     return;
434   llvm::APSInt UsedSize = Result.Val.getInt();
435 
436   if (UsedSize.ule(ObjectSize))
437     return;
438 
439   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
440   // Skim off the details of whichever builtin was called to produce a better
441   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
442   if (IsChkVariant) {
443     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
444     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
445   } else if (FunctionName.startswith("__builtin_")) {
446     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
447   }
448 
449   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
450                       PDiag(DiagID)
451                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
452                           << UsedSize.toString(/*Radix=*/10));
453 }
454 
455 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
456                                      Scope::ScopeFlags NeededScopeFlags,
457                                      unsigned DiagID) {
458   // Scopes aren't available during instantiation. Fortunately, builtin
459   // functions cannot be template args so they cannot be formed through template
460   // instantiation. Therefore checking once during the parse is sufficient.
461   if (SemaRef.inTemplateInstantiation())
462     return false;
463 
464   Scope *S = SemaRef.getCurScope();
465   while (S && !S->isSEHExceptScope())
466     S = S->getParent();
467   if (!S || !(S->getFlags() & NeededScopeFlags)) {
468     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
469     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
470         << DRE->getDecl()->getIdentifier();
471     return true;
472   }
473 
474   return false;
475 }
476 
477 static inline bool isBlockPointer(Expr *Arg) {
478   return Arg->getType()->isBlockPointerType();
479 }
480 
481 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
482 /// void*, which is a requirement of device side enqueue.
483 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
484   const BlockPointerType *BPT =
485       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
486   ArrayRef<QualType> Params =
487       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
488   unsigned ArgCounter = 0;
489   bool IllegalParams = false;
490   // Iterate through the block parameters until either one is found that is not
491   // a local void*, or the block is valid.
492   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
493        I != E; ++I, ++ArgCounter) {
494     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
495         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
496             LangAS::opencl_local) {
497       // Get the location of the error. If a block literal has been passed
498       // (BlockExpr) then we can point straight to the offending argument,
499       // else we just point to the variable reference.
500       SourceLocation ErrorLoc;
501       if (isa<BlockExpr>(BlockArg)) {
502         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
503         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
504       } else if (isa<DeclRefExpr>(BlockArg)) {
505         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
506       }
507       S.Diag(ErrorLoc,
508              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
509       IllegalParams = true;
510     }
511   }
512 
513   return IllegalParams;
514 }
515 
516 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
517   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
518     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
519         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
520     return true;
521   }
522   return false;
523 }
524 
525 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
526   if (checkArgCount(S, TheCall, 2))
527     return true;
528 
529   if (checkOpenCLSubgroupExt(S, TheCall))
530     return true;
531 
532   // First argument is an ndrange_t type.
533   Expr *NDRangeArg = TheCall->getArg(0);
534   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
535     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
536         << TheCall->getDirectCallee() << "'ndrange_t'";
537     return true;
538   }
539 
540   Expr *BlockArg = TheCall->getArg(1);
541   if (!isBlockPointer(BlockArg)) {
542     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
543         << TheCall->getDirectCallee() << "block";
544     return true;
545   }
546   return checkOpenCLBlockArgs(S, BlockArg);
547 }
548 
549 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
550 /// get_kernel_work_group_size
551 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
552 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
553   if (checkArgCount(S, TheCall, 1))
554     return true;
555 
556   Expr *BlockArg = TheCall->getArg(0);
557   if (!isBlockPointer(BlockArg)) {
558     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
559         << TheCall->getDirectCallee() << "block";
560     return true;
561   }
562   return checkOpenCLBlockArgs(S, BlockArg);
563 }
564 
565 /// Diagnose integer type and any valid implicit conversion to it.
566 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
567                                       const QualType &IntType);
568 
569 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
570                                             unsigned Start, unsigned End) {
571   bool IllegalParams = false;
572   for (unsigned I = Start; I <= End; ++I)
573     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
574                                               S.Context.getSizeType());
575   return IllegalParams;
576 }
577 
578 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
579 /// 'local void*' parameter of passed block.
580 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
581                                            Expr *BlockArg,
582                                            unsigned NumNonVarArgs) {
583   const BlockPointerType *BPT =
584       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
585   unsigned NumBlockParams =
586       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
587   unsigned TotalNumArgs = TheCall->getNumArgs();
588 
589   // For each argument passed to the block, a corresponding uint needs to
590   // be passed to describe the size of the local memory.
591   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
592     S.Diag(TheCall->getBeginLoc(),
593            diag::err_opencl_enqueue_kernel_local_size_args);
594     return true;
595   }
596 
597   // Check that the sizes of the local memory are specified by integers.
598   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
599                                          TotalNumArgs - 1);
600 }
601 
602 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
603 /// overload formats specified in Table 6.13.17.1.
604 /// int enqueue_kernel(queue_t queue,
605 ///                    kernel_enqueue_flags_t flags,
606 ///                    const ndrange_t ndrange,
607 ///                    void (^block)(void))
608 /// int enqueue_kernel(queue_t queue,
609 ///                    kernel_enqueue_flags_t flags,
610 ///                    const ndrange_t ndrange,
611 ///                    uint num_events_in_wait_list,
612 ///                    clk_event_t *event_wait_list,
613 ///                    clk_event_t *event_ret,
614 ///                    void (^block)(void))
615 /// int enqueue_kernel(queue_t queue,
616 ///                    kernel_enqueue_flags_t flags,
617 ///                    const ndrange_t ndrange,
618 ///                    void (^block)(local void*, ...),
619 ///                    uint size0, ...)
620 /// int enqueue_kernel(queue_t queue,
621 ///                    kernel_enqueue_flags_t flags,
622 ///                    const ndrange_t ndrange,
623 ///                    uint num_events_in_wait_list,
624 ///                    clk_event_t *event_wait_list,
625 ///                    clk_event_t *event_ret,
626 ///                    void (^block)(local void*, ...),
627 ///                    uint size0, ...)
628 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
629   unsigned NumArgs = TheCall->getNumArgs();
630 
631   if (NumArgs < 4) {
632     S.Diag(TheCall->getBeginLoc(),
633            diag::err_typecheck_call_too_few_args_at_least)
634         << 0 << 4 << NumArgs;
635     return true;
636   }
637 
638   Expr *Arg0 = TheCall->getArg(0);
639   Expr *Arg1 = TheCall->getArg(1);
640   Expr *Arg2 = TheCall->getArg(2);
641   Expr *Arg3 = TheCall->getArg(3);
642 
643   // First argument always needs to be a queue_t type.
644   if (!Arg0->getType()->isQueueT()) {
645     S.Diag(TheCall->getArg(0)->getBeginLoc(),
646            diag::err_opencl_builtin_expected_type)
647         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
648     return true;
649   }
650 
651   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
652   if (!Arg1->getType()->isIntegerType()) {
653     S.Diag(TheCall->getArg(1)->getBeginLoc(),
654            diag::err_opencl_builtin_expected_type)
655         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
656     return true;
657   }
658 
659   // Third argument is always an ndrange_t type.
660   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
661     S.Diag(TheCall->getArg(2)->getBeginLoc(),
662            diag::err_opencl_builtin_expected_type)
663         << TheCall->getDirectCallee() << "'ndrange_t'";
664     return true;
665   }
666 
667   // With four arguments, there is only one form that the function could be
668   // called in: no events and no variable arguments.
669   if (NumArgs == 4) {
670     // check that the last argument is the right block type.
671     if (!isBlockPointer(Arg3)) {
672       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
673           << TheCall->getDirectCallee() << "block";
674       return true;
675     }
676     // we have a block type, check the prototype
677     const BlockPointerType *BPT =
678         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
679     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
680       S.Diag(Arg3->getBeginLoc(),
681              diag::err_opencl_enqueue_kernel_blocks_no_args);
682       return true;
683     }
684     return false;
685   }
686   // we can have block + varargs.
687   if (isBlockPointer(Arg3))
688     return (checkOpenCLBlockArgs(S, Arg3) ||
689             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
690   // last two cases with either exactly 7 args or 7 args and varargs.
691   if (NumArgs >= 7) {
692     // check common block argument.
693     Expr *Arg6 = TheCall->getArg(6);
694     if (!isBlockPointer(Arg6)) {
695       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
696           << TheCall->getDirectCallee() << "block";
697       return true;
698     }
699     if (checkOpenCLBlockArgs(S, Arg6))
700       return true;
701 
702     // Forth argument has to be any integer type.
703     if (!Arg3->getType()->isIntegerType()) {
704       S.Diag(TheCall->getArg(3)->getBeginLoc(),
705              diag::err_opencl_builtin_expected_type)
706           << TheCall->getDirectCallee() << "integer";
707       return true;
708     }
709     // check remaining common arguments.
710     Expr *Arg4 = TheCall->getArg(4);
711     Expr *Arg5 = TheCall->getArg(5);
712 
713     // Fifth argument is always passed as a pointer to clk_event_t.
714     if (!Arg4->isNullPointerConstant(S.Context,
715                                      Expr::NPC_ValueDependentIsNotNull) &&
716         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
717       S.Diag(TheCall->getArg(4)->getBeginLoc(),
718              diag::err_opencl_builtin_expected_type)
719           << TheCall->getDirectCallee()
720           << S.Context.getPointerType(S.Context.OCLClkEventTy);
721       return true;
722     }
723 
724     // Sixth argument is always passed as a pointer to clk_event_t.
725     if (!Arg5->isNullPointerConstant(S.Context,
726                                      Expr::NPC_ValueDependentIsNotNull) &&
727         !(Arg5->getType()->isPointerType() &&
728           Arg5->getType()->getPointeeType()->isClkEventT())) {
729       S.Diag(TheCall->getArg(5)->getBeginLoc(),
730              diag::err_opencl_builtin_expected_type)
731           << TheCall->getDirectCallee()
732           << S.Context.getPointerType(S.Context.OCLClkEventTy);
733       return true;
734     }
735 
736     if (NumArgs == 7)
737       return false;
738 
739     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
740   }
741 
742   // None of the specific case has been detected, give generic error
743   S.Diag(TheCall->getBeginLoc(),
744          diag::err_opencl_enqueue_kernel_incorrect_args);
745   return true;
746 }
747 
748 /// Returns OpenCL access qual.
749 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
750     return D->getAttr<OpenCLAccessAttr>();
751 }
752 
753 /// Returns true if pipe element type is different from the pointer.
754 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
755   const Expr *Arg0 = Call->getArg(0);
756   // First argument type should always be pipe.
757   if (!Arg0->getType()->isPipeType()) {
758     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
759         << Call->getDirectCallee() << Arg0->getSourceRange();
760     return true;
761   }
762   OpenCLAccessAttr *AccessQual =
763       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
764   // Validates the access qualifier is compatible with the call.
765   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
766   // read_only and write_only, and assumed to be read_only if no qualifier is
767   // specified.
768   switch (Call->getDirectCallee()->getBuiltinID()) {
769   case Builtin::BIread_pipe:
770   case Builtin::BIreserve_read_pipe:
771   case Builtin::BIcommit_read_pipe:
772   case Builtin::BIwork_group_reserve_read_pipe:
773   case Builtin::BIsub_group_reserve_read_pipe:
774   case Builtin::BIwork_group_commit_read_pipe:
775   case Builtin::BIsub_group_commit_read_pipe:
776     if (!(!AccessQual || AccessQual->isReadOnly())) {
777       S.Diag(Arg0->getBeginLoc(),
778              diag::err_opencl_builtin_pipe_invalid_access_modifier)
779           << "read_only" << Arg0->getSourceRange();
780       return true;
781     }
782     break;
783   case Builtin::BIwrite_pipe:
784   case Builtin::BIreserve_write_pipe:
785   case Builtin::BIcommit_write_pipe:
786   case Builtin::BIwork_group_reserve_write_pipe:
787   case Builtin::BIsub_group_reserve_write_pipe:
788   case Builtin::BIwork_group_commit_write_pipe:
789   case Builtin::BIsub_group_commit_write_pipe:
790     if (!(AccessQual && AccessQual->isWriteOnly())) {
791       S.Diag(Arg0->getBeginLoc(),
792              diag::err_opencl_builtin_pipe_invalid_access_modifier)
793           << "write_only" << Arg0->getSourceRange();
794       return true;
795     }
796     break;
797   default:
798     break;
799   }
800   return false;
801 }
802 
803 /// Returns true if pipe element type is different from the pointer.
804 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
805   const Expr *Arg0 = Call->getArg(0);
806   const Expr *ArgIdx = Call->getArg(Idx);
807   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
808   const QualType EltTy = PipeTy->getElementType();
809   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
810   // The Idx argument should be a pointer and the type of the pointer and
811   // the type of pipe element should also be the same.
812   if (!ArgTy ||
813       !S.Context.hasSameType(
814           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
815     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
816         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
817         << ArgIdx->getType() << ArgIdx->getSourceRange();
818     return true;
819   }
820   return false;
821 }
822 
823 // Performs semantic analysis for the read/write_pipe call.
824 // \param S Reference to the semantic analyzer.
825 // \param Call A pointer to the builtin call.
826 // \return True if a semantic error has been found, false otherwise.
827 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
828   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
829   // functions have two forms.
830   switch (Call->getNumArgs()) {
831   case 2:
832     if (checkOpenCLPipeArg(S, Call))
833       return true;
834     // The call with 2 arguments should be
835     // read/write_pipe(pipe T, T*).
836     // Check packet type T.
837     if (checkOpenCLPipePacketType(S, Call, 1))
838       return true;
839     break;
840 
841   case 4: {
842     if (checkOpenCLPipeArg(S, Call))
843       return true;
844     // The call with 4 arguments should be
845     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
846     // Check reserve_id_t.
847     if (!Call->getArg(1)->getType()->isReserveIDT()) {
848       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
849           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
850           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
851       return true;
852     }
853 
854     // Check the index.
855     const Expr *Arg2 = Call->getArg(2);
856     if (!Arg2->getType()->isIntegerType() &&
857         !Arg2->getType()->isUnsignedIntegerType()) {
858       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
859           << Call->getDirectCallee() << S.Context.UnsignedIntTy
860           << Arg2->getType() << Arg2->getSourceRange();
861       return true;
862     }
863 
864     // Check packet type T.
865     if (checkOpenCLPipePacketType(S, Call, 3))
866       return true;
867   } break;
868   default:
869     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
870         << Call->getDirectCallee() << Call->getSourceRange();
871     return true;
872   }
873 
874   return false;
875 }
876 
877 // Performs a semantic analysis on the {work_group_/sub_group_
878 //        /_}reserve_{read/write}_pipe
879 // \param S Reference to the semantic analyzer.
880 // \param Call The call to the builtin function to be analyzed.
881 // \return True if a semantic error was found, false otherwise.
882 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
883   if (checkArgCount(S, Call, 2))
884     return true;
885 
886   if (checkOpenCLPipeArg(S, Call))
887     return true;
888 
889   // Check the reserve size.
890   if (!Call->getArg(1)->getType()->isIntegerType() &&
891       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
892     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
893         << Call->getDirectCallee() << S.Context.UnsignedIntTy
894         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
895     return true;
896   }
897 
898   // Since return type of reserve_read/write_pipe built-in function is
899   // reserve_id_t, which is not defined in the builtin def file , we used int
900   // as return type and need to override the return type of these functions.
901   Call->setType(S.Context.OCLReserveIDTy);
902 
903   return false;
904 }
905 
906 // Performs a semantic analysis on {work_group_/sub_group_
907 //        /_}commit_{read/write}_pipe
908 // \param S Reference to the semantic analyzer.
909 // \param Call The call to the builtin function to be analyzed.
910 // \return True if a semantic error was found, false otherwise.
911 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
912   if (checkArgCount(S, Call, 2))
913     return true;
914 
915   if (checkOpenCLPipeArg(S, Call))
916     return true;
917 
918   // Check reserve_id_t.
919   if (!Call->getArg(1)->getType()->isReserveIDT()) {
920     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
921         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
922         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
923     return true;
924   }
925 
926   return false;
927 }
928 
929 // Performs a semantic analysis on the call to built-in Pipe
930 //        Query Functions.
931 // \param S Reference to the semantic analyzer.
932 // \param Call The call to the builtin function to be analyzed.
933 // \return True if a semantic error was found, false otherwise.
934 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
935   if (checkArgCount(S, Call, 1))
936     return true;
937 
938   if (!Call->getArg(0)->getType()->isPipeType()) {
939     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
940         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
941     return true;
942   }
943 
944   return false;
945 }
946 
947 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
948 // Performs semantic analysis for the to_global/local/private call.
949 // \param S Reference to the semantic analyzer.
950 // \param BuiltinID ID of the builtin function.
951 // \param Call A pointer to the builtin call.
952 // \return True if a semantic error has been found, false otherwise.
953 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
954                                     CallExpr *Call) {
955   if (Call->getNumArgs() != 1) {
956     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
957         << Call->getDirectCallee() << Call->getSourceRange();
958     return true;
959   }
960 
961   auto RT = Call->getArg(0)->getType();
962   if (!RT->isPointerType() || RT->getPointeeType()
963       .getAddressSpace() == LangAS::opencl_constant) {
964     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
965         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
966     return true;
967   }
968 
969   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
970     S.Diag(Call->getArg(0)->getBeginLoc(),
971            diag::warn_opencl_generic_address_space_arg)
972         << Call->getDirectCallee()->getNameInfo().getAsString()
973         << Call->getArg(0)->getSourceRange();
974   }
975 
976   RT = RT->getPointeeType();
977   auto Qual = RT.getQualifiers();
978   switch (BuiltinID) {
979   case Builtin::BIto_global:
980     Qual.setAddressSpace(LangAS::opencl_global);
981     break;
982   case Builtin::BIto_local:
983     Qual.setAddressSpace(LangAS::opencl_local);
984     break;
985   case Builtin::BIto_private:
986     Qual.setAddressSpace(LangAS::opencl_private);
987     break;
988   default:
989     llvm_unreachable("Invalid builtin function");
990   }
991   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
992       RT.getUnqualifiedType(), Qual)));
993 
994   return false;
995 }
996 
997 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
998   if (checkArgCount(S, TheCall, 1))
999     return ExprError();
1000 
1001   // Compute __builtin_launder's parameter type from the argument.
1002   // The parameter type is:
1003   //  * The type of the argument if it's not an array or function type,
1004   //  Otherwise,
1005   //  * The decayed argument type.
1006   QualType ParamTy = [&]() {
1007     QualType ArgTy = TheCall->getArg(0)->getType();
1008     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1009       return S.Context.getPointerType(Ty->getElementType());
1010     if (ArgTy->isFunctionType()) {
1011       return S.Context.getPointerType(ArgTy);
1012     }
1013     return ArgTy;
1014   }();
1015 
1016   TheCall->setType(ParamTy);
1017 
1018   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1019     if (!ParamTy->isPointerType())
1020       return 0;
1021     if (ParamTy->isFunctionPointerType())
1022       return 1;
1023     if (ParamTy->isVoidPointerType())
1024       return 2;
1025     return llvm::Optional<unsigned>{};
1026   }();
1027   if (DiagSelect.hasValue()) {
1028     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1029         << DiagSelect.getValue() << TheCall->getSourceRange();
1030     return ExprError();
1031   }
1032 
1033   // We either have an incomplete class type, or we have a class template
1034   // whose instantiation has not been forced. Example:
1035   //
1036   //   template <class T> struct Foo { T value; };
1037   //   Foo<int> *p = nullptr;
1038   //   auto *d = __builtin_launder(p);
1039   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1040                             diag::err_incomplete_type))
1041     return ExprError();
1042 
1043   assert(ParamTy->getPointeeType()->isObjectType() &&
1044          "Unhandled non-object pointer case");
1045 
1046   InitializedEntity Entity =
1047       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1048   ExprResult Arg =
1049       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1050   if (Arg.isInvalid())
1051     return ExprError();
1052   TheCall->setArg(0, Arg.get());
1053 
1054   return TheCall;
1055 }
1056 
1057 // Emit an error and return true if the current architecture is not in the list
1058 // of supported architectures.
1059 static bool
1060 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1061                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1062   llvm::Triple::ArchType CurArch =
1063       S.getASTContext().getTargetInfo().getTriple().getArch();
1064   if (llvm::is_contained(SupportedArchs, CurArch))
1065     return false;
1066   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1067       << TheCall->getSourceRange();
1068   return true;
1069 }
1070 
1071 ExprResult
1072 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1073                                CallExpr *TheCall) {
1074   ExprResult TheCallResult(TheCall);
1075 
1076   // Find out if any arguments are required to be integer constant expressions.
1077   unsigned ICEArguments = 0;
1078   ASTContext::GetBuiltinTypeError Error;
1079   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1080   if (Error != ASTContext::GE_None)
1081     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1082 
1083   // If any arguments are required to be ICE's, check and diagnose.
1084   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1085     // Skip arguments not required to be ICE's.
1086     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1087 
1088     llvm::APSInt Result;
1089     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1090       return true;
1091     ICEArguments &= ~(1 << ArgNo);
1092   }
1093 
1094   switch (BuiltinID) {
1095   case Builtin::BI__builtin___CFStringMakeConstantString:
1096     assert(TheCall->getNumArgs() == 1 &&
1097            "Wrong # arguments to builtin CFStringMakeConstantString");
1098     if (CheckObjCString(TheCall->getArg(0)))
1099       return ExprError();
1100     break;
1101   case Builtin::BI__builtin_ms_va_start:
1102   case Builtin::BI__builtin_stdarg_start:
1103   case Builtin::BI__builtin_va_start:
1104     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1105       return ExprError();
1106     break;
1107   case Builtin::BI__va_start: {
1108     switch (Context.getTargetInfo().getTriple().getArch()) {
1109     case llvm::Triple::aarch64:
1110     case llvm::Triple::arm:
1111     case llvm::Triple::thumb:
1112       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1113         return ExprError();
1114       break;
1115     default:
1116       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1117         return ExprError();
1118       break;
1119     }
1120     break;
1121   }
1122 
1123   // The acquire, release, and no fence variants are ARM and AArch64 only.
1124   case Builtin::BI_interlockedbittestandset_acq:
1125   case Builtin::BI_interlockedbittestandset_rel:
1126   case Builtin::BI_interlockedbittestandset_nf:
1127   case Builtin::BI_interlockedbittestandreset_acq:
1128   case Builtin::BI_interlockedbittestandreset_rel:
1129   case Builtin::BI_interlockedbittestandreset_nf:
1130     if (CheckBuiltinTargetSupport(
1131             *this, BuiltinID, TheCall,
1132             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1133       return ExprError();
1134     break;
1135 
1136   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1137   case Builtin::BI_bittest64:
1138   case Builtin::BI_bittestandcomplement64:
1139   case Builtin::BI_bittestandreset64:
1140   case Builtin::BI_bittestandset64:
1141   case Builtin::BI_interlockedbittestandreset64:
1142   case Builtin::BI_interlockedbittestandset64:
1143     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1144                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1145                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1146       return ExprError();
1147     break;
1148 
1149   case Builtin::BI__builtin_isgreater:
1150   case Builtin::BI__builtin_isgreaterequal:
1151   case Builtin::BI__builtin_isless:
1152   case Builtin::BI__builtin_islessequal:
1153   case Builtin::BI__builtin_islessgreater:
1154   case Builtin::BI__builtin_isunordered:
1155     if (SemaBuiltinUnorderedCompare(TheCall))
1156       return ExprError();
1157     break;
1158   case Builtin::BI__builtin_fpclassify:
1159     if (SemaBuiltinFPClassification(TheCall, 6))
1160       return ExprError();
1161     break;
1162   case Builtin::BI__builtin_isfinite:
1163   case Builtin::BI__builtin_isinf:
1164   case Builtin::BI__builtin_isinf_sign:
1165   case Builtin::BI__builtin_isnan:
1166   case Builtin::BI__builtin_isnormal:
1167   case Builtin::BI__builtin_signbit:
1168   case Builtin::BI__builtin_signbitf:
1169   case Builtin::BI__builtin_signbitl:
1170     if (SemaBuiltinFPClassification(TheCall, 1))
1171       return ExprError();
1172     break;
1173   case Builtin::BI__builtin_shufflevector:
1174     return SemaBuiltinShuffleVector(TheCall);
1175     // TheCall will be freed by the smart pointer here, but that's fine, since
1176     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1177   case Builtin::BI__builtin_prefetch:
1178     if (SemaBuiltinPrefetch(TheCall))
1179       return ExprError();
1180     break;
1181   case Builtin::BI__builtin_alloca_with_align:
1182     if (SemaBuiltinAllocaWithAlign(TheCall))
1183       return ExprError();
1184     LLVM_FALLTHROUGH;
1185   case Builtin::BI__builtin_alloca:
1186     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1187         << TheCall->getDirectCallee();
1188     break;
1189   case Builtin::BI__assume:
1190   case Builtin::BI__builtin_assume:
1191     if (SemaBuiltinAssume(TheCall))
1192       return ExprError();
1193     break;
1194   case Builtin::BI__builtin_assume_aligned:
1195     if (SemaBuiltinAssumeAligned(TheCall))
1196       return ExprError();
1197     break;
1198   case Builtin::BI__builtin_dynamic_object_size:
1199   case Builtin::BI__builtin_object_size:
1200     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1201       return ExprError();
1202     break;
1203   case Builtin::BI__builtin_longjmp:
1204     if (SemaBuiltinLongjmp(TheCall))
1205       return ExprError();
1206     break;
1207   case Builtin::BI__builtin_setjmp:
1208     if (SemaBuiltinSetjmp(TheCall))
1209       return ExprError();
1210     break;
1211   case Builtin::BI_setjmp:
1212   case Builtin::BI_setjmpex:
1213     if (checkArgCount(*this, TheCall, 1))
1214       return true;
1215     break;
1216   case Builtin::BI__builtin_classify_type:
1217     if (checkArgCount(*this, TheCall, 1)) return true;
1218     TheCall->setType(Context.IntTy);
1219     break;
1220   case Builtin::BI__builtin_constant_p: {
1221     if (checkArgCount(*this, TheCall, 1)) return true;
1222     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1223     if (Arg.isInvalid()) return true;
1224     TheCall->setArg(0, Arg.get());
1225     TheCall->setType(Context.IntTy);
1226     break;
1227   }
1228   case Builtin::BI__builtin_launder:
1229     return SemaBuiltinLaunder(*this, TheCall);
1230   case Builtin::BI__sync_fetch_and_add:
1231   case Builtin::BI__sync_fetch_and_add_1:
1232   case Builtin::BI__sync_fetch_and_add_2:
1233   case Builtin::BI__sync_fetch_and_add_4:
1234   case Builtin::BI__sync_fetch_and_add_8:
1235   case Builtin::BI__sync_fetch_and_add_16:
1236   case Builtin::BI__sync_fetch_and_sub:
1237   case Builtin::BI__sync_fetch_and_sub_1:
1238   case Builtin::BI__sync_fetch_and_sub_2:
1239   case Builtin::BI__sync_fetch_and_sub_4:
1240   case Builtin::BI__sync_fetch_and_sub_8:
1241   case Builtin::BI__sync_fetch_and_sub_16:
1242   case Builtin::BI__sync_fetch_and_or:
1243   case Builtin::BI__sync_fetch_and_or_1:
1244   case Builtin::BI__sync_fetch_and_or_2:
1245   case Builtin::BI__sync_fetch_and_or_4:
1246   case Builtin::BI__sync_fetch_and_or_8:
1247   case Builtin::BI__sync_fetch_and_or_16:
1248   case Builtin::BI__sync_fetch_and_and:
1249   case Builtin::BI__sync_fetch_and_and_1:
1250   case Builtin::BI__sync_fetch_and_and_2:
1251   case Builtin::BI__sync_fetch_and_and_4:
1252   case Builtin::BI__sync_fetch_and_and_8:
1253   case Builtin::BI__sync_fetch_and_and_16:
1254   case Builtin::BI__sync_fetch_and_xor:
1255   case Builtin::BI__sync_fetch_and_xor_1:
1256   case Builtin::BI__sync_fetch_and_xor_2:
1257   case Builtin::BI__sync_fetch_and_xor_4:
1258   case Builtin::BI__sync_fetch_and_xor_8:
1259   case Builtin::BI__sync_fetch_and_xor_16:
1260   case Builtin::BI__sync_fetch_and_nand:
1261   case Builtin::BI__sync_fetch_and_nand_1:
1262   case Builtin::BI__sync_fetch_and_nand_2:
1263   case Builtin::BI__sync_fetch_and_nand_4:
1264   case Builtin::BI__sync_fetch_and_nand_8:
1265   case Builtin::BI__sync_fetch_and_nand_16:
1266   case Builtin::BI__sync_add_and_fetch:
1267   case Builtin::BI__sync_add_and_fetch_1:
1268   case Builtin::BI__sync_add_and_fetch_2:
1269   case Builtin::BI__sync_add_and_fetch_4:
1270   case Builtin::BI__sync_add_and_fetch_8:
1271   case Builtin::BI__sync_add_and_fetch_16:
1272   case Builtin::BI__sync_sub_and_fetch:
1273   case Builtin::BI__sync_sub_and_fetch_1:
1274   case Builtin::BI__sync_sub_and_fetch_2:
1275   case Builtin::BI__sync_sub_and_fetch_4:
1276   case Builtin::BI__sync_sub_and_fetch_8:
1277   case Builtin::BI__sync_sub_and_fetch_16:
1278   case Builtin::BI__sync_and_and_fetch:
1279   case Builtin::BI__sync_and_and_fetch_1:
1280   case Builtin::BI__sync_and_and_fetch_2:
1281   case Builtin::BI__sync_and_and_fetch_4:
1282   case Builtin::BI__sync_and_and_fetch_8:
1283   case Builtin::BI__sync_and_and_fetch_16:
1284   case Builtin::BI__sync_or_and_fetch:
1285   case Builtin::BI__sync_or_and_fetch_1:
1286   case Builtin::BI__sync_or_and_fetch_2:
1287   case Builtin::BI__sync_or_and_fetch_4:
1288   case Builtin::BI__sync_or_and_fetch_8:
1289   case Builtin::BI__sync_or_and_fetch_16:
1290   case Builtin::BI__sync_xor_and_fetch:
1291   case Builtin::BI__sync_xor_and_fetch_1:
1292   case Builtin::BI__sync_xor_and_fetch_2:
1293   case Builtin::BI__sync_xor_and_fetch_4:
1294   case Builtin::BI__sync_xor_and_fetch_8:
1295   case Builtin::BI__sync_xor_and_fetch_16:
1296   case Builtin::BI__sync_nand_and_fetch:
1297   case Builtin::BI__sync_nand_and_fetch_1:
1298   case Builtin::BI__sync_nand_and_fetch_2:
1299   case Builtin::BI__sync_nand_and_fetch_4:
1300   case Builtin::BI__sync_nand_and_fetch_8:
1301   case Builtin::BI__sync_nand_and_fetch_16:
1302   case Builtin::BI__sync_val_compare_and_swap:
1303   case Builtin::BI__sync_val_compare_and_swap_1:
1304   case Builtin::BI__sync_val_compare_and_swap_2:
1305   case Builtin::BI__sync_val_compare_and_swap_4:
1306   case Builtin::BI__sync_val_compare_and_swap_8:
1307   case Builtin::BI__sync_val_compare_and_swap_16:
1308   case Builtin::BI__sync_bool_compare_and_swap:
1309   case Builtin::BI__sync_bool_compare_and_swap_1:
1310   case Builtin::BI__sync_bool_compare_and_swap_2:
1311   case Builtin::BI__sync_bool_compare_and_swap_4:
1312   case Builtin::BI__sync_bool_compare_and_swap_8:
1313   case Builtin::BI__sync_bool_compare_and_swap_16:
1314   case Builtin::BI__sync_lock_test_and_set:
1315   case Builtin::BI__sync_lock_test_and_set_1:
1316   case Builtin::BI__sync_lock_test_and_set_2:
1317   case Builtin::BI__sync_lock_test_and_set_4:
1318   case Builtin::BI__sync_lock_test_and_set_8:
1319   case Builtin::BI__sync_lock_test_and_set_16:
1320   case Builtin::BI__sync_lock_release:
1321   case Builtin::BI__sync_lock_release_1:
1322   case Builtin::BI__sync_lock_release_2:
1323   case Builtin::BI__sync_lock_release_4:
1324   case Builtin::BI__sync_lock_release_8:
1325   case Builtin::BI__sync_lock_release_16:
1326   case Builtin::BI__sync_swap:
1327   case Builtin::BI__sync_swap_1:
1328   case Builtin::BI__sync_swap_2:
1329   case Builtin::BI__sync_swap_4:
1330   case Builtin::BI__sync_swap_8:
1331   case Builtin::BI__sync_swap_16:
1332     return SemaBuiltinAtomicOverloaded(TheCallResult);
1333   case Builtin::BI__sync_synchronize:
1334     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1335         << TheCall->getCallee()->getSourceRange();
1336     break;
1337   case Builtin::BI__builtin_nontemporal_load:
1338   case Builtin::BI__builtin_nontemporal_store:
1339     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1340 #define BUILTIN(ID, TYPE, ATTRS)
1341 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1342   case Builtin::BI##ID: \
1343     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1344 #include "clang/Basic/Builtins.def"
1345   case Builtin::BI__annotation:
1346     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1347       return ExprError();
1348     break;
1349   case Builtin::BI__builtin_annotation:
1350     if (SemaBuiltinAnnotation(*this, TheCall))
1351       return ExprError();
1352     break;
1353   case Builtin::BI__builtin_addressof:
1354     if (SemaBuiltinAddressof(*this, TheCall))
1355       return ExprError();
1356     break;
1357   case Builtin::BI__builtin_add_overflow:
1358   case Builtin::BI__builtin_sub_overflow:
1359   case Builtin::BI__builtin_mul_overflow:
1360     if (SemaBuiltinOverflow(*this, TheCall))
1361       return ExprError();
1362     break;
1363   case Builtin::BI__builtin_operator_new:
1364   case Builtin::BI__builtin_operator_delete: {
1365     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1366     ExprResult Res =
1367         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1368     if (Res.isInvalid())
1369       CorrectDelayedTyposInExpr(TheCallResult.get());
1370     return Res;
1371   }
1372   case Builtin::BI__builtin_dump_struct: {
1373     // We first want to ensure we are called with 2 arguments
1374     if (checkArgCount(*this, TheCall, 2))
1375       return ExprError();
1376     // Ensure that the first argument is of type 'struct XX *'
1377     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1378     const QualType PtrArgType = PtrArg->getType();
1379     if (!PtrArgType->isPointerType() ||
1380         !PtrArgType->getPointeeType()->isRecordType()) {
1381       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1382           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1383           << "structure pointer";
1384       return ExprError();
1385     }
1386 
1387     // Ensure that the second argument is of type 'FunctionType'
1388     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1389     const QualType FnPtrArgType = FnPtrArg->getType();
1390     if (!FnPtrArgType->isPointerType()) {
1391       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1392           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1393           << FnPtrArgType << "'int (*)(const char *, ...)'";
1394       return ExprError();
1395     }
1396 
1397     const auto *FuncType =
1398         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1399 
1400     if (!FuncType) {
1401       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1402           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1403           << FnPtrArgType << "'int (*)(const char *, ...)'";
1404       return ExprError();
1405     }
1406 
1407     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1408       if (!FT->getNumParams()) {
1409         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1410             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1411             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1412         return ExprError();
1413       }
1414       QualType PT = FT->getParamType(0);
1415       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1416           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1417           !PT->getPointeeType().isConstQualified()) {
1418         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1419             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1420             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1421         return ExprError();
1422       }
1423     }
1424 
1425     TheCall->setType(Context.IntTy);
1426     break;
1427   }
1428   case Builtin::BI__builtin_preserve_access_index:
1429     if (SemaBuiltinPreserveAI(*this, TheCall))
1430       return ExprError();
1431     break;
1432   case Builtin::BI__builtin_call_with_static_chain:
1433     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1434       return ExprError();
1435     break;
1436   case Builtin::BI__exception_code:
1437   case Builtin::BI_exception_code:
1438     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1439                                  diag::err_seh___except_block))
1440       return ExprError();
1441     break;
1442   case Builtin::BI__exception_info:
1443   case Builtin::BI_exception_info:
1444     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1445                                  diag::err_seh___except_filter))
1446       return ExprError();
1447     break;
1448   case Builtin::BI__GetExceptionInfo:
1449     if (checkArgCount(*this, TheCall, 1))
1450       return ExprError();
1451 
1452     if (CheckCXXThrowOperand(
1453             TheCall->getBeginLoc(),
1454             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1455             TheCall))
1456       return ExprError();
1457 
1458     TheCall->setType(Context.VoidPtrTy);
1459     break;
1460   // OpenCL v2.0, s6.13.16 - Pipe functions
1461   case Builtin::BIread_pipe:
1462   case Builtin::BIwrite_pipe:
1463     // Since those two functions are declared with var args, we need a semantic
1464     // check for the argument.
1465     if (SemaBuiltinRWPipe(*this, TheCall))
1466       return ExprError();
1467     break;
1468   case Builtin::BIreserve_read_pipe:
1469   case Builtin::BIreserve_write_pipe:
1470   case Builtin::BIwork_group_reserve_read_pipe:
1471   case Builtin::BIwork_group_reserve_write_pipe:
1472     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BIsub_group_reserve_read_pipe:
1476   case Builtin::BIsub_group_reserve_write_pipe:
1477     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1478         SemaBuiltinReserveRWPipe(*this, TheCall))
1479       return ExprError();
1480     break;
1481   case Builtin::BIcommit_read_pipe:
1482   case Builtin::BIcommit_write_pipe:
1483   case Builtin::BIwork_group_commit_read_pipe:
1484   case Builtin::BIwork_group_commit_write_pipe:
1485     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1486       return ExprError();
1487     break;
1488   case Builtin::BIsub_group_commit_read_pipe:
1489   case Builtin::BIsub_group_commit_write_pipe:
1490     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1491         SemaBuiltinCommitRWPipe(*this, TheCall))
1492       return ExprError();
1493     break;
1494   case Builtin::BIget_pipe_num_packets:
1495   case Builtin::BIget_pipe_max_packets:
1496     if (SemaBuiltinPipePackets(*this, TheCall))
1497       return ExprError();
1498     break;
1499   case Builtin::BIto_global:
1500   case Builtin::BIto_local:
1501   case Builtin::BIto_private:
1502     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1503       return ExprError();
1504     break;
1505   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1506   case Builtin::BIenqueue_kernel:
1507     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1508       return ExprError();
1509     break;
1510   case Builtin::BIget_kernel_work_group_size:
1511   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1512     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1513       return ExprError();
1514     break;
1515   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1516   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1517     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1518       return ExprError();
1519     break;
1520   case Builtin::BI__builtin_os_log_format:
1521   case Builtin::BI__builtin_os_log_format_buffer_size:
1522     if (SemaBuiltinOSLogFormat(TheCall))
1523       return ExprError();
1524     break;
1525   }
1526 
1527   // Since the target specific builtins for each arch overlap, only check those
1528   // of the arch we are compiling for.
1529   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1530     switch (Context.getTargetInfo().getTriple().getArch()) {
1531       case llvm::Triple::arm:
1532       case llvm::Triple::armeb:
1533       case llvm::Triple::thumb:
1534       case llvm::Triple::thumbeb:
1535         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1536           return ExprError();
1537         break;
1538       case llvm::Triple::aarch64:
1539       case llvm::Triple::aarch64_be:
1540         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1541           return ExprError();
1542         break;
1543       case llvm::Triple::bpfeb:
1544       case llvm::Triple::bpfel:
1545         if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall))
1546           return ExprError();
1547         break;
1548       case llvm::Triple::hexagon:
1549         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1550           return ExprError();
1551         break;
1552       case llvm::Triple::mips:
1553       case llvm::Triple::mipsel:
1554       case llvm::Triple::mips64:
1555       case llvm::Triple::mips64el:
1556         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1557           return ExprError();
1558         break;
1559       case llvm::Triple::systemz:
1560         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1561           return ExprError();
1562         break;
1563       case llvm::Triple::x86:
1564       case llvm::Triple::x86_64:
1565         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1566           return ExprError();
1567         break;
1568       case llvm::Triple::ppc:
1569       case llvm::Triple::ppc64:
1570       case llvm::Triple::ppc64le:
1571         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1572           return ExprError();
1573         break;
1574       default:
1575         break;
1576     }
1577   }
1578 
1579   return TheCallResult;
1580 }
1581 
1582 // Get the valid immediate range for the specified NEON type code.
1583 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1584   NeonTypeFlags Type(t);
1585   int IsQuad = ForceQuad ? true : Type.isQuad();
1586   switch (Type.getEltType()) {
1587   case NeonTypeFlags::Int8:
1588   case NeonTypeFlags::Poly8:
1589     return shift ? 7 : (8 << IsQuad) - 1;
1590   case NeonTypeFlags::Int16:
1591   case NeonTypeFlags::Poly16:
1592     return shift ? 15 : (4 << IsQuad) - 1;
1593   case NeonTypeFlags::Int32:
1594     return shift ? 31 : (2 << IsQuad) - 1;
1595   case NeonTypeFlags::Int64:
1596   case NeonTypeFlags::Poly64:
1597     return shift ? 63 : (1 << IsQuad) - 1;
1598   case NeonTypeFlags::Poly128:
1599     return shift ? 127 : (1 << IsQuad) - 1;
1600   case NeonTypeFlags::Float16:
1601     assert(!shift && "cannot shift float types!");
1602     return (4 << IsQuad) - 1;
1603   case NeonTypeFlags::Float32:
1604     assert(!shift && "cannot shift float types!");
1605     return (2 << IsQuad) - 1;
1606   case NeonTypeFlags::Float64:
1607     assert(!shift && "cannot shift float types!");
1608     return (1 << IsQuad) - 1;
1609   }
1610   llvm_unreachable("Invalid NeonTypeFlag!");
1611 }
1612 
1613 /// getNeonEltType - Return the QualType corresponding to the elements of
1614 /// the vector type specified by the NeonTypeFlags.  This is used to check
1615 /// the pointer arguments for Neon load/store intrinsics.
1616 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1617                                bool IsPolyUnsigned, bool IsInt64Long) {
1618   switch (Flags.getEltType()) {
1619   case NeonTypeFlags::Int8:
1620     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1621   case NeonTypeFlags::Int16:
1622     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1623   case NeonTypeFlags::Int32:
1624     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1625   case NeonTypeFlags::Int64:
1626     if (IsInt64Long)
1627       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1628     else
1629       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1630                                 : Context.LongLongTy;
1631   case NeonTypeFlags::Poly8:
1632     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1633   case NeonTypeFlags::Poly16:
1634     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1635   case NeonTypeFlags::Poly64:
1636     if (IsInt64Long)
1637       return Context.UnsignedLongTy;
1638     else
1639       return Context.UnsignedLongLongTy;
1640   case NeonTypeFlags::Poly128:
1641     break;
1642   case NeonTypeFlags::Float16:
1643     return Context.HalfTy;
1644   case NeonTypeFlags::Float32:
1645     return Context.FloatTy;
1646   case NeonTypeFlags::Float64:
1647     return Context.DoubleTy;
1648   }
1649   llvm_unreachable("Invalid NeonTypeFlag!");
1650 }
1651 
1652 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1653   llvm::APSInt Result;
1654   uint64_t mask = 0;
1655   unsigned TV = 0;
1656   int PtrArgNum = -1;
1657   bool HasConstPtr = false;
1658   switch (BuiltinID) {
1659 #define GET_NEON_OVERLOAD_CHECK
1660 #include "clang/Basic/arm_neon.inc"
1661 #include "clang/Basic/arm_fp16.inc"
1662 #undef GET_NEON_OVERLOAD_CHECK
1663   }
1664 
1665   // For NEON intrinsics which are overloaded on vector element type, validate
1666   // the immediate which specifies which variant to emit.
1667   unsigned ImmArg = TheCall->getNumArgs()-1;
1668   if (mask) {
1669     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1670       return true;
1671 
1672     TV = Result.getLimitedValue(64);
1673     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1674       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1675              << TheCall->getArg(ImmArg)->getSourceRange();
1676   }
1677 
1678   if (PtrArgNum >= 0) {
1679     // Check that pointer arguments have the specified type.
1680     Expr *Arg = TheCall->getArg(PtrArgNum);
1681     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1682       Arg = ICE->getSubExpr();
1683     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1684     QualType RHSTy = RHS.get()->getType();
1685 
1686     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1687     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1688                           Arch == llvm::Triple::aarch64_be;
1689     bool IsInt64Long =
1690         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1691     QualType EltTy =
1692         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1693     if (HasConstPtr)
1694       EltTy = EltTy.withConst();
1695     QualType LHSTy = Context.getPointerType(EltTy);
1696     AssignConvertType ConvTy;
1697     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1698     if (RHS.isInvalid())
1699       return true;
1700     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1701                                  RHS.get(), AA_Assigning))
1702       return true;
1703   }
1704 
1705   // For NEON intrinsics which take an immediate value as part of the
1706   // instruction, range check them here.
1707   unsigned i = 0, l = 0, u = 0;
1708   switch (BuiltinID) {
1709   default:
1710     return false;
1711   #define GET_NEON_IMMEDIATE_CHECK
1712   #include "clang/Basic/arm_neon.inc"
1713   #include "clang/Basic/arm_fp16.inc"
1714   #undef GET_NEON_IMMEDIATE_CHECK
1715   }
1716 
1717   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1718 }
1719 
1720 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1721                                         unsigned MaxWidth) {
1722   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1723           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1724           BuiltinID == ARM::BI__builtin_arm_strex ||
1725           BuiltinID == ARM::BI__builtin_arm_stlex ||
1726           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1727           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1728           BuiltinID == AArch64::BI__builtin_arm_strex ||
1729           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1730          "unexpected ARM builtin");
1731   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1732                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1733                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1734                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1735 
1736   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1737 
1738   // Ensure that we have the proper number of arguments.
1739   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1740     return true;
1741 
1742   // Inspect the pointer argument of the atomic builtin.  This should always be
1743   // a pointer type, whose element is an integral scalar or pointer type.
1744   // Because it is a pointer type, we don't have to worry about any implicit
1745   // casts here.
1746   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1747   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1748   if (PointerArgRes.isInvalid())
1749     return true;
1750   PointerArg = PointerArgRes.get();
1751 
1752   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1753   if (!pointerType) {
1754     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1755         << PointerArg->getType() << PointerArg->getSourceRange();
1756     return true;
1757   }
1758 
1759   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1760   // task is to insert the appropriate casts into the AST. First work out just
1761   // what the appropriate type is.
1762   QualType ValType = pointerType->getPointeeType();
1763   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1764   if (IsLdrex)
1765     AddrType.addConst();
1766 
1767   // Issue a warning if the cast is dodgy.
1768   CastKind CastNeeded = CK_NoOp;
1769   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1770     CastNeeded = CK_BitCast;
1771     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1772         << PointerArg->getType() << Context.getPointerType(AddrType)
1773         << AA_Passing << PointerArg->getSourceRange();
1774   }
1775 
1776   // Finally, do the cast and replace the argument with the corrected version.
1777   AddrType = Context.getPointerType(AddrType);
1778   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1779   if (PointerArgRes.isInvalid())
1780     return true;
1781   PointerArg = PointerArgRes.get();
1782 
1783   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1784 
1785   // In general, we allow ints, floats and pointers to be loaded and stored.
1786   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1787       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1788     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1789         << PointerArg->getType() << PointerArg->getSourceRange();
1790     return true;
1791   }
1792 
1793   // But ARM doesn't have instructions to deal with 128-bit versions.
1794   if (Context.getTypeSize(ValType) > MaxWidth) {
1795     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1796     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1797         << PointerArg->getType() << PointerArg->getSourceRange();
1798     return true;
1799   }
1800 
1801   switch (ValType.getObjCLifetime()) {
1802   case Qualifiers::OCL_None:
1803   case Qualifiers::OCL_ExplicitNone:
1804     // okay
1805     break;
1806 
1807   case Qualifiers::OCL_Weak:
1808   case Qualifiers::OCL_Strong:
1809   case Qualifiers::OCL_Autoreleasing:
1810     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1811         << ValType << PointerArg->getSourceRange();
1812     return true;
1813   }
1814 
1815   if (IsLdrex) {
1816     TheCall->setType(ValType);
1817     return false;
1818   }
1819 
1820   // Initialize the argument to be stored.
1821   ExprResult ValArg = TheCall->getArg(0);
1822   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1823       Context, ValType, /*consume*/ false);
1824   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1825   if (ValArg.isInvalid())
1826     return true;
1827   TheCall->setArg(0, ValArg.get());
1828 
1829   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1830   // but the custom checker bypasses all default analysis.
1831   TheCall->setType(Context.IntTy);
1832   return false;
1833 }
1834 
1835 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1836   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1837       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1838       BuiltinID == ARM::BI__builtin_arm_strex ||
1839       BuiltinID == ARM::BI__builtin_arm_stlex) {
1840     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1841   }
1842 
1843   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1844     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1845       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1846   }
1847 
1848   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1849       BuiltinID == ARM::BI__builtin_arm_wsr64)
1850     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1851 
1852   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1853       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1854       BuiltinID == ARM::BI__builtin_arm_wsr ||
1855       BuiltinID == ARM::BI__builtin_arm_wsrp)
1856     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1857 
1858   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1859     return true;
1860 
1861   // For intrinsics which take an immediate value as part of the instruction,
1862   // range check them here.
1863   // FIXME: VFP Intrinsics should error if VFP not present.
1864   switch (BuiltinID) {
1865   default: return false;
1866   case ARM::BI__builtin_arm_ssat:
1867     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1868   case ARM::BI__builtin_arm_usat:
1869     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1870   case ARM::BI__builtin_arm_ssat16:
1871     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1872   case ARM::BI__builtin_arm_usat16:
1873     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1874   case ARM::BI__builtin_arm_vcvtr_f:
1875   case ARM::BI__builtin_arm_vcvtr_d:
1876     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1877   case ARM::BI__builtin_arm_dmb:
1878   case ARM::BI__builtin_arm_dsb:
1879   case ARM::BI__builtin_arm_isb:
1880   case ARM::BI__builtin_arm_dbg:
1881     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1882   }
1883 }
1884 
1885 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1886                                          CallExpr *TheCall) {
1887   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1888       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1889       BuiltinID == AArch64::BI__builtin_arm_strex ||
1890       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1891     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1892   }
1893 
1894   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1895     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1896       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1897       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1898       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1899   }
1900 
1901   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1902       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1903     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1904 
1905   // Memory Tagging Extensions (MTE) Intrinsics
1906   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
1907       BuiltinID == AArch64::BI__builtin_arm_addg ||
1908       BuiltinID == AArch64::BI__builtin_arm_gmi ||
1909       BuiltinID == AArch64::BI__builtin_arm_ldg ||
1910       BuiltinID == AArch64::BI__builtin_arm_stg ||
1911       BuiltinID == AArch64::BI__builtin_arm_subp) {
1912     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
1913   }
1914 
1915   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1916       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1917       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1918       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1919     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1920 
1921   // Only check the valid encoding range. Any constant in this range would be
1922   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1923   // an exception for incorrect registers. This matches MSVC behavior.
1924   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1925       BuiltinID == AArch64::BI_WriteStatusReg)
1926     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1927 
1928   if (BuiltinID == AArch64::BI__getReg)
1929     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1930 
1931   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1932     return true;
1933 
1934   // For intrinsics which take an immediate value as part of the instruction,
1935   // range check them here.
1936   unsigned i = 0, l = 0, u = 0;
1937   switch (BuiltinID) {
1938   default: return false;
1939   case AArch64::BI__builtin_arm_dmb:
1940   case AArch64::BI__builtin_arm_dsb:
1941   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1942   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
1943   }
1944 
1945   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1946 }
1947 
1948 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
1949                                        CallExpr *TheCall) {
1950   assert(BuiltinID == BPF::BI__builtin_preserve_field_info &&
1951          "unexpected ARM builtin");
1952 
1953   if (checkArgCount(*this, TheCall, 2))
1954     return true;
1955 
1956   // The first argument needs to be a record field access.
1957   // If it is an array element access, we delay decision
1958   // to BPF backend to check whether the access is a
1959   // field access or not.
1960   Expr *Arg = TheCall->getArg(0);
1961   if (Arg->getType()->getAsPlaceholderType() ||
1962       (Arg->IgnoreParens()->getObjectKind() != OK_BitField &&
1963        !dyn_cast<MemberExpr>(Arg->IgnoreParens()) &&
1964        !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) {
1965     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field)
1966         << 1 << Arg->getSourceRange();
1967     return true;
1968   }
1969 
1970   // The second argument needs to be a constant int
1971   llvm::APSInt Value;
1972   if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) {
1973     Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const)
1974         << 2 << Arg->getSourceRange();
1975     return true;
1976   }
1977 
1978   TheCall->setType(Context.UnsignedIntTy);
1979   return false;
1980 }
1981 
1982 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1983   struct BuiltinAndString {
1984     unsigned BuiltinID;
1985     const char *Str;
1986   };
1987 
1988   static BuiltinAndString ValidCPU[] = {
1989     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1992     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1993     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1994     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1997     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1998     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1999     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
2012   };
2013 
2014   static BuiltinAndString ValidHVX[] = {
2015     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2667     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2668     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2669     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2670     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2671     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2672     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2673     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2674     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2675     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2676     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2677     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2678     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2679     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2680     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2681     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2682     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2683     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2684     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2685     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2686     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2687     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2688     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2689     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2690     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2691     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2692     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2693     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2694     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2695     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2696     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2697     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2698     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2699     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2700     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2701     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2702     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2703     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2704     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2705     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2706     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2707     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2708     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2709     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2710     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2711     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2712     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2713     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2714     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2715     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2716     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2717     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2718     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2719     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2720     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2721     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2722     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2723     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2724     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2725     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2726     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2727     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2729     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2734     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2737     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2738     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2739     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2742     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2743     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2744     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2745     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2746     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2747   };
2748 
2749   // Sort the tables on first execution so we can binary search them.
2750   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2751     return LHS.BuiltinID < RHS.BuiltinID;
2752   };
2753   static const bool SortOnce =
2754       (llvm::sort(ValidCPU, SortCmp),
2755        llvm::sort(ValidHVX, SortCmp), true);
2756   (void)SortOnce;
2757   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2758     return BI.BuiltinID < BuiltinID;
2759   };
2760 
2761   const TargetInfo &TI = Context.getTargetInfo();
2762 
2763   const BuiltinAndString *FC =
2764       llvm::lower_bound(ValidCPU, BuiltinID, LowerBoundCmp);
2765   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2766     const TargetOptions &Opts = TI.getTargetOpts();
2767     StringRef CPU = Opts.CPU;
2768     if (!CPU.empty()) {
2769       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2770       CPU.consume_front("hexagon");
2771       SmallVector<StringRef, 3> CPUs;
2772       StringRef(FC->Str).split(CPUs, ',');
2773       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2774         return Diag(TheCall->getBeginLoc(),
2775                     diag::err_hexagon_builtin_unsupported_cpu);
2776     }
2777   }
2778 
2779   const BuiltinAndString *FH =
2780       llvm::lower_bound(ValidHVX, BuiltinID, LowerBoundCmp);
2781   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2782     if (!TI.hasFeature("hvx"))
2783       return Diag(TheCall->getBeginLoc(),
2784                   diag::err_hexagon_builtin_requires_hvx);
2785 
2786     SmallVector<StringRef, 3> HVXs;
2787     StringRef(FH->Str).split(HVXs, ',');
2788     bool IsValid = llvm::any_of(HVXs,
2789                                 [&TI] (StringRef V) {
2790                                   std::string F = "hvx" + V.str();
2791                                   return TI.hasFeature(F);
2792                                 });
2793     if (!IsValid)
2794       return Diag(TheCall->getBeginLoc(),
2795                   diag::err_hexagon_builtin_unsupported_hvx);
2796   }
2797 
2798   return false;
2799 }
2800 
2801 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2802   struct ArgInfo {
2803     uint8_t OpNum;
2804     bool IsSigned;
2805     uint8_t BitWidth;
2806     uint8_t Align;
2807   };
2808   struct BuiltinInfo {
2809     unsigned BuiltinID;
2810     ArgInfo Infos[2];
2811   };
2812 
2813   static BuiltinInfo Infos[] = {
2814     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2815     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2816     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2817     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2818     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2819     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2820     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2821     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2822     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2823     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2824     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2825 
2826     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2829     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2830     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2831     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2837 
2838     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2890                                                       {{ 1, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2898                                                       {{ 1, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2905                                                        { 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2907                                                        { 2, false, 6,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2909                                                        { 3, false, 5,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2911                                                        { 3, false, 6,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2928                                                       {{ 2, false, 4,  0 },
2929                                                        { 3, false, 5,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2931                                                       {{ 2, false, 4,  0 },
2932                                                        { 3, false, 5,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2934                                                       {{ 2, false, 4,  0 },
2935                                                        { 3, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2937                                                       {{ 2, false, 4,  0 },
2938                                                        { 3, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2950                                                        { 2, false, 5,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2952                                                        { 2, false, 6,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2961     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2962                                                       {{ 1, false, 4,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2964     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2965                                                       {{ 1, false, 4,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2967     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2968     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2974     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2977     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2983     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2986                                                       {{ 3, false, 1,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2991                                                       {{ 3, false, 1,  0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2996                                                       {{ 3, false, 1,  0 }} },
2997   };
2998 
2999   // Use a dynamically initialized static to sort the table exactly once on
3000   // first run.
3001   static const bool SortOnce =
3002       (llvm::sort(Infos,
3003                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3004                    return LHS.BuiltinID < RHS.BuiltinID;
3005                  }),
3006        true);
3007   (void)SortOnce;
3008 
3009   const BuiltinInfo *F = llvm::partition_point(
3010       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3011   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3012     return false;
3013 
3014   bool Error = false;
3015 
3016   for (const ArgInfo &A : F->Infos) {
3017     // Ignore empty ArgInfo elements.
3018     if (A.BitWidth == 0)
3019       continue;
3020 
3021     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3022     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3023     if (!A.Align) {
3024       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3025     } else {
3026       unsigned M = 1 << A.Align;
3027       Min *= M;
3028       Max *= M;
3029       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
3030                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3031     }
3032   }
3033   return Error;
3034 }
3035 
3036 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3037                                            CallExpr *TheCall) {
3038   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
3039          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3040 }
3041 
3042 
3043 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
3044 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3045 // ordering for DSP is unspecified. MSA is ordered by the data format used
3046 // by the underlying instruction i.e., df/m, df/n and then by size.
3047 //
3048 // FIXME: The size tests here should instead be tablegen'd along with the
3049 //        definitions from include/clang/Basic/BuiltinsMips.def.
3050 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3051 //        be too.
3052 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3053   unsigned i = 0, l = 0, u = 0, m = 0;
3054   switch (BuiltinID) {
3055   default: return false;
3056   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3057   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3058   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3059   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3060   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3061   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3062   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3063   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3064   // df/m field.
3065   // These intrinsics take an unsigned 3 bit immediate.
3066   case Mips::BI__builtin_msa_bclri_b:
3067   case Mips::BI__builtin_msa_bnegi_b:
3068   case Mips::BI__builtin_msa_bseti_b:
3069   case Mips::BI__builtin_msa_sat_s_b:
3070   case Mips::BI__builtin_msa_sat_u_b:
3071   case Mips::BI__builtin_msa_slli_b:
3072   case Mips::BI__builtin_msa_srai_b:
3073   case Mips::BI__builtin_msa_srari_b:
3074   case Mips::BI__builtin_msa_srli_b:
3075   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3076   case Mips::BI__builtin_msa_binsli_b:
3077   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3078   // These intrinsics take an unsigned 4 bit immediate.
3079   case Mips::BI__builtin_msa_bclri_h:
3080   case Mips::BI__builtin_msa_bnegi_h:
3081   case Mips::BI__builtin_msa_bseti_h:
3082   case Mips::BI__builtin_msa_sat_s_h:
3083   case Mips::BI__builtin_msa_sat_u_h:
3084   case Mips::BI__builtin_msa_slli_h:
3085   case Mips::BI__builtin_msa_srai_h:
3086   case Mips::BI__builtin_msa_srari_h:
3087   case Mips::BI__builtin_msa_srli_h:
3088   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3089   case Mips::BI__builtin_msa_binsli_h:
3090   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3091   // These intrinsics take an unsigned 5 bit immediate.
3092   // The first block of intrinsics actually have an unsigned 5 bit field,
3093   // not a df/n field.
3094   case Mips::BI__builtin_msa_cfcmsa:
3095   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3096   case Mips::BI__builtin_msa_clei_u_b:
3097   case Mips::BI__builtin_msa_clei_u_h:
3098   case Mips::BI__builtin_msa_clei_u_w:
3099   case Mips::BI__builtin_msa_clei_u_d:
3100   case Mips::BI__builtin_msa_clti_u_b:
3101   case Mips::BI__builtin_msa_clti_u_h:
3102   case Mips::BI__builtin_msa_clti_u_w:
3103   case Mips::BI__builtin_msa_clti_u_d:
3104   case Mips::BI__builtin_msa_maxi_u_b:
3105   case Mips::BI__builtin_msa_maxi_u_h:
3106   case Mips::BI__builtin_msa_maxi_u_w:
3107   case Mips::BI__builtin_msa_maxi_u_d:
3108   case Mips::BI__builtin_msa_mini_u_b:
3109   case Mips::BI__builtin_msa_mini_u_h:
3110   case Mips::BI__builtin_msa_mini_u_w:
3111   case Mips::BI__builtin_msa_mini_u_d:
3112   case Mips::BI__builtin_msa_addvi_b:
3113   case Mips::BI__builtin_msa_addvi_h:
3114   case Mips::BI__builtin_msa_addvi_w:
3115   case Mips::BI__builtin_msa_addvi_d:
3116   case Mips::BI__builtin_msa_bclri_w:
3117   case Mips::BI__builtin_msa_bnegi_w:
3118   case Mips::BI__builtin_msa_bseti_w:
3119   case Mips::BI__builtin_msa_sat_s_w:
3120   case Mips::BI__builtin_msa_sat_u_w:
3121   case Mips::BI__builtin_msa_slli_w:
3122   case Mips::BI__builtin_msa_srai_w:
3123   case Mips::BI__builtin_msa_srari_w:
3124   case Mips::BI__builtin_msa_srli_w:
3125   case Mips::BI__builtin_msa_srlri_w:
3126   case Mips::BI__builtin_msa_subvi_b:
3127   case Mips::BI__builtin_msa_subvi_h:
3128   case Mips::BI__builtin_msa_subvi_w:
3129   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3130   case Mips::BI__builtin_msa_binsli_w:
3131   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3132   // These intrinsics take an unsigned 6 bit immediate.
3133   case Mips::BI__builtin_msa_bclri_d:
3134   case Mips::BI__builtin_msa_bnegi_d:
3135   case Mips::BI__builtin_msa_bseti_d:
3136   case Mips::BI__builtin_msa_sat_s_d:
3137   case Mips::BI__builtin_msa_sat_u_d:
3138   case Mips::BI__builtin_msa_slli_d:
3139   case Mips::BI__builtin_msa_srai_d:
3140   case Mips::BI__builtin_msa_srari_d:
3141   case Mips::BI__builtin_msa_srli_d:
3142   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3143   case Mips::BI__builtin_msa_binsli_d:
3144   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3145   // These intrinsics take a signed 5 bit immediate.
3146   case Mips::BI__builtin_msa_ceqi_b:
3147   case Mips::BI__builtin_msa_ceqi_h:
3148   case Mips::BI__builtin_msa_ceqi_w:
3149   case Mips::BI__builtin_msa_ceqi_d:
3150   case Mips::BI__builtin_msa_clti_s_b:
3151   case Mips::BI__builtin_msa_clti_s_h:
3152   case Mips::BI__builtin_msa_clti_s_w:
3153   case Mips::BI__builtin_msa_clti_s_d:
3154   case Mips::BI__builtin_msa_clei_s_b:
3155   case Mips::BI__builtin_msa_clei_s_h:
3156   case Mips::BI__builtin_msa_clei_s_w:
3157   case Mips::BI__builtin_msa_clei_s_d:
3158   case Mips::BI__builtin_msa_maxi_s_b:
3159   case Mips::BI__builtin_msa_maxi_s_h:
3160   case Mips::BI__builtin_msa_maxi_s_w:
3161   case Mips::BI__builtin_msa_maxi_s_d:
3162   case Mips::BI__builtin_msa_mini_s_b:
3163   case Mips::BI__builtin_msa_mini_s_h:
3164   case Mips::BI__builtin_msa_mini_s_w:
3165   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3166   // These intrinsics take an unsigned 8 bit immediate.
3167   case Mips::BI__builtin_msa_andi_b:
3168   case Mips::BI__builtin_msa_nori_b:
3169   case Mips::BI__builtin_msa_ori_b:
3170   case Mips::BI__builtin_msa_shf_b:
3171   case Mips::BI__builtin_msa_shf_h:
3172   case Mips::BI__builtin_msa_shf_w:
3173   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3174   case Mips::BI__builtin_msa_bseli_b:
3175   case Mips::BI__builtin_msa_bmnzi_b:
3176   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3177   // df/n format
3178   // These intrinsics take an unsigned 4 bit immediate.
3179   case Mips::BI__builtin_msa_copy_s_b:
3180   case Mips::BI__builtin_msa_copy_u_b:
3181   case Mips::BI__builtin_msa_insve_b:
3182   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3183   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3184   // These intrinsics take an unsigned 3 bit immediate.
3185   case Mips::BI__builtin_msa_copy_s_h:
3186   case Mips::BI__builtin_msa_copy_u_h:
3187   case Mips::BI__builtin_msa_insve_h:
3188   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3189   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3190   // These intrinsics take an unsigned 2 bit immediate.
3191   case Mips::BI__builtin_msa_copy_s_w:
3192   case Mips::BI__builtin_msa_copy_u_w:
3193   case Mips::BI__builtin_msa_insve_w:
3194   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3195   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3196   // These intrinsics take an unsigned 1 bit immediate.
3197   case Mips::BI__builtin_msa_copy_s_d:
3198   case Mips::BI__builtin_msa_copy_u_d:
3199   case Mips::BI__builtin_msa_insve_d:
3200   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3201   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3202   // Memory offsets and immediate loads.
3203   // These intrinsics take a signed 10 bit immediate.
3204   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3205   case Mips::BI__builtin_msa_ldi_h:
3206   case Mips::BI__builtin_msa_ldi_w:
3207   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3208   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3209   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3210   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3211   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3212   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3213   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3214   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3215   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3216   }
3217 
3218   if (!m)
3219     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3220 
3221   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3222          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3223 }
3224 
3225 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3226   unsigned i = 0, l = 0, u = 0;
3227   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3228                       BuiltinID == PPC::BI__builtin_divdeu ||
3229                       BuiltinID == PPC::BI__builtin_bpermd;
3230   bool IsTarget64Bit = Context.getTargetInfo()
3231                               .getTypeWidth(Context
3232                                             .getTargetInfo()
3233                                             .getIntPtrType()) == 64;
3234   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3235                        BuiltinID == PPC::BI__builtin_divweu ||
3236                        BuiltinID == PPC::BI__builtin_divde ||
3237                        BuiltinID == PPC::BI__builtin_divdeu;
3238 
3239   if (Is64BitBltin && !IsTarget64Bit)
3240     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3241            << TheCall->getSourceRange();
3242 
3243   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3244       (BuiltinID == PPC::BI__builtin_bpermd &&
3245        !Context.getTargetInfo().hasFeature("bpermd")))
3246     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3247            << TheCall->getSourceRange();
3248 
3249   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3250     if (!Context.getTargetInfo().hasFeature("vsx"))
3251       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3252              << TheCall->getSourceRange();
3253     return false;
3254   };
3255 
3256   switch (BuiltinID) {
3257   default: return false;
3258   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3259   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3260     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3261            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3262   case PPC::BI__builtin_altivec_dss:
3263     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3264   case PPC::BI__builtin_tbegin:
3265   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3266   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3267   case PPC::BI__builtin_tabortwc:
3268   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3269   case PPC::BI__builtin_tabortwci:
3270   case PPC::BI__builtin_tabortdci:
3271     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3272            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3273   case PPC::BI__builtin_altivec_dst:
3274   case PPC::BI__builtin_altivec_dstt:
3275   case PPC::BI__builtin_altivec_dstst:
3276   case PPC::BI__builtin_altivec_dststt:
3277     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3278   case PPC::BI__builtin_vsx_xxpermdi:
3279   case PPC::BI__builtin_vsx_xxsldwi:
3280     return SemaBuiltinVSX(TheCall);
3281   case PPC::BI__builtin_unpack_vector_int128:
3282     return SemaVSXCheck(TheCall) ||
3283            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3284   case PPC::BI__builtin_pack_vector_int128:
3285     return SemaVSXCheck(TheCall);
3286   }
3287   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3288 }
3289 
3290 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3291                                            CallExpr *TheCall) {
3292   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3293     Expr *Arg = TheCall->getArg(0);
3294     llvm::APSInt AbortCode(32);
3295     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3296         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3297       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3298              << Arg->getSourceRange();
3299   }
3300 
3301   // For intrinsics which take an immediate value as part of the instruction,
3302   // range check them here.
3303   unsigned i = 0, l = 0, u = 0;
3304   switch (BuiltinID) {
3305   default: return false;
3306   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3307   case SystemZ::BI__builtin_s390_verimb:
3308   case SystemZ::BI__builtin_s390_verimh:
3309   case SystemZ::BI__builtin_s390_verimf:
3310   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3311   case SystemZ::BI__builtin_s390_vfaeb:
3312   case SystemZ::BI__builtin_s390_vfaeh:
3313   case SystemZ::BI__builtin_s390_vfaef:
3314   case SystemZ::BI__builtin_s390_vfaebs:
3315   case SystemZ::BI__builtin_s390_vfaehs:
3316   case SystemZ::BI__builtin_s390_vfaefs:
3317   case SystemZ::BI__builtin_s390_vfaezb:
3318   case SystemZ::BI__builtin_s390_vfaezh:
3319   case SystemZ::BI__builtin_s390_vfaezf:
3320   case SystemZ::BI__builtin_s390_vfaezbs:
3321   case SystemZ::BI__builtin_s390_vfaezhs:
3322   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3323   case SystemZ::BI__builtin_s390_vfisb:
3324   case SystemZ::BI__builtin_s390_vfidb:
3325     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3326            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3327   case SystemZ::BI__builtin_s390_vftcisb:
3328   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3329   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3330   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3331   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3332   case SystemZ::BI__builtin_s390_vstrcb:
3333   case SystemZ::BI__builtin_s390_vstrch:
3334   case SystemZ::BI__builtin_s390_vstrcf:
3335   case SystemZ::BI__builtin_s390_vstrczb:
3336   case SystemZ::BI__builtin_s390_vstrczh:
3337   case SystemZ::BI__builtin_s390_vstrczf:
3338   case SystemZ::BI__builtin_s390_vstrcbs:
3339   case SystemZ::BI__builtin_s390_vstrchs:
3340   case SystemZ::BI__builtin_s390_vstrcfs:
3341   case SystemZ::BI__builtin_s390_vstrczbs:
3342   case SystemZ::BI__builtin_s390_vstrczhs:
3343   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3344   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3345   case SystemZ::BI__builtin_s390_vfminsb:
3346   case SystemZ::BI__builtin_s390_vfmaxsb:
3347   case SystemZ::BI__builtin_s390_vfmindb:
3348   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3349   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3350   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3351   }
3352   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3353 }
3354 
3355 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3356 /// This checks that the target supports __builtin_cpu_supports and
3357 /// that the string argument is constant and valid.
3358 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3359   Expr *Arg = TheCall->getArg(0);
3360 
3361   // Check if the argument is a string literal.
3362   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3363     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3364            << Arg->getSourceRange();
3365 
3366   // Check the contents of the string.
3367   StringRef Feature =
3368       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3369   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3370     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3371            << Arg->getSourceRange();
3372   return false;
3373 }
3374 
3375 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3376 /// This checks that the target supports __builtin_cpu_is and
3377 /// that the string argument is constant and valid.
3378 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3379   Expr *Arg = TheCall->getArg(0);
3380 
3381   // Check if the argument is a string literal.
3382   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3383     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3384            << Arg->getSourceRange();
3385 
3386   // Check the contents of the string.
3387   StringRef Feature =
3388       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3389   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3390     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3391            << Arg->getSourceRange();
3392   return false;
3393 }
3394 
3395 // Check if the rounding mode is legal.
3396 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3397   // Indicates if this instruction has rounding control or just SAE.
3398   bool HasRC = false;
3399 
3400   unsigned ArgNum = 0;
3401   switch (BuiltinID) {
3402   default:
3403     return false;
3404   case X86::BI__builtin_ia32_vcvttsd2si32:
3405   case X86::BI__builtin_ia32_vcvttsd2si64:
3406   case X86::BI__builtin_ia32_vcvttsd2usi32:
3407   case X86::BI__builtin_ia32_vcvttsd2usi64:
3408   case X86::BI__builtin_ia32_vcvttss2si32:
3409   case X86::BI__builtin_ia32_vcvttss2si64:
3410   case X86::BI__builtin_ia32_vcvttss2usi32:
3411   case X86::BI__builtin_ia32_vcvttss2usi64:
3412     ArgNum = 1;
3413     break;
3414   case X86::BI__builtin_ia32_maxpd512:
3415   case X86::BI__builtin_ia32_maxps512:
3416   case X86::BI__builtin_ia32_minpd512:
3417   case X86::BI__builtin_ia32_minps512:
3418     ArgNum = 2;
3419     break;
3420   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3421   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3422   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3423   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3424   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3425   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3426   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3427   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3428   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3429   case X86::BI__builtin_ia32_exp2pd_mask:
3430   case X86::BI__builtin_ia32_exp2ps_mask:
3431   case X86::BI__builtin_ia32_getexppd512_mask:
3432   case X86::BI__builtin_ia32_getexpps512_mask:
3433   case X86::BI__builtin_ia32_rcp28pd_mask:
3434   case X86::BI__builtin_ia32_rcp28ps_mask:
3435   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3436   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3437   case X86::BI__builtin_ia32_vcomisd:
3438   case X86::BI__builtin_ia32_vcomiss:
3439   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3440     ArgNum = 3;
3441     break;
3442   case X86::BI__builtin_ia32_cmppd512_mask:
3443   case X86::BI__builtin_ia32_cmpps512_mask:
3444   case X86::BI__builtin_ia32_cmpsd_mask:
3445   case X86::BI__builtin_ia32_cmpss_mask:
3446   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3447   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3448   case X86::BI__builtin_ia32_getexpss128_round_mask:
3449   case X86::BI__builtin_ia32_getmantpd512_mask:
3450   case X86::BI__builtin_ia32_getmantps512_mask:
3451   case X86::BI__builtin_ia32_maxsd_round_mask:
3452   case X86::BI__builtin_ia32_maxss_round_mask:
3453   case X86::BI__builtin_ia32_minsd_round_mask:
3454   case X86::BI__builtin_ia32_minss_round_mask:
3455   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3456   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3457   case X86::BI__builtin_ia32_reducepd512_mask:
3458   case X86::BI__builtin_ia32_reduceps512_mask:
3459   case X86::BI__builtin_ia32_rndscalepd_mask:
3460   case X86::BI__builtin_ia32_rndscaleps_mask:
3461   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3462   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3463     ArgNum = 4;
3464     break;
3465   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3466   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3467   case X86::BI__builtin_ia32_fixupimmps512_mask:
3468   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3469   case X86::BI__builtin_ia32_fixupimmsd_mask:
3470   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3471   case X86::BI__builtin_ia32_fixupimmss_mask:
3472   case X86::BI__builtin_ia32_fixupimmss_maskz:
3473   case X86::BI__builtin_ia32_getmantsd_round_mask:
3474   case X86::BI__builtin_ia32_getmantss_round_mask:
3475   case X86::BI__builtin_ia32_rangepd512_mask:
3476   case X86::BI__builtin_ia32_rangeps512_mask:
3477   case X86::BI__builtin_ia32_rangesd128_round_mask:
3478   case X86::BI__builtin_ia32_rangess128_round_mask:
3479   case X86::BI__builtin_ia32_reducesd_mask:
3480   case X86::BI__builtin_ia32_reducess_mask:
3481   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3482   case X86::BI__builtin_ia32_rndscaless_round_mask:
3483     ArgNum = 5;
3484     break;
3485   case X86::BI__builtin_ia32_vcvtsd2si64:
3486   case X86::BI__builtin_ia32_vcvtsd2si32:
3487   case X86::BI__builtin_ia32_vcvtsd2usi32:
3488   case X86::BI__builtin_ia32_vcvtsd2usi64:
3489   case X86::BI__builtin_ia32_vcvtss2si32:
3490   case X86::BI__builtin_ia32_vcvtss2si64:
3491   case X86::BI__builtin_ia32_vcvtss2usi32:
3492   case X86::BI__builtin_ia32_vcvtss2usi64:
3493   case X86::BI__builtin_ia32_sqrtpd512:
3494   case X86::BI__builtin_ia32_sqrtps512:
3495     ArgNum = 1;
3496     HasRC = true;
3497     break;
3498   case X86::BI__builtin_ia32_addpd512:
3499   case X86::BI__builtin_ia32_addps512:
3500   case X86::BI__builtin_ia32_divpd512:
3501   case X86::BI__builtin_ia32_divps512:
3502   case X86::BI__builtin_ia32_mulpd512:
3503   case X86::BI__builtin_ia32_mulps512:
3504   case X86::BI__builtin_ia32_subpd512:
3505   case X86::BI__builtin_ia32_subps512:
3506   case X86::BI__builtin_ia32_cvtsi2sd64:
3507   case X86::BI__builtin_ia32_cvtsi2ss32:
3508   case X86::BI__builtin_ia32_cvtsi2ss64:
3509   case X86::BI__builtin_ia32_cvtusi2sd64:
3510   case X86::BI__builtin_ia32_cvtusi2ss32:
3511   case X86::BI__builtin_ia32_cvtusi2ss64:
3512     ArgNum = 2;
3513     HasRC = true;
3514     break;
3515   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3516   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3517   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3518   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3519   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3520   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3521   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3522   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3523   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3524   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3525   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3526   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3527   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3528   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3529   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3530     ArgNum = 3;
3531     HasRC = true;
3532     break;
3533   case X86::BI__builtin_ia32_addss_round_mask:
3534   case X86::BI__builtin_ia32_addsd_round_mask:
3535   case X86::BI__builtin_ia32_divss_round_mask:
3536   case X86::BI__builtin_ia32_divsd_round_mask:
3537   case X86::BI__builtin_ia32_mulss_round_mask:
3538   case X86::BI__builtin_ia32_mulsd_round_mask:
3539   case X86::BI__builtin_ia32_subss_round_mask:
3540   case X86::BI__builtin_ia32_subsd_round_mask:
3541   case X86::BI__builtin_ia32_scalefpd512_mask:
3542   case X86::BI__builtin_ia32_scalefps512_mask:
3543   case X86::BI__builtin_ia32_scalefsd_round_mask:
3544   case X86::BI__builtin_ia32_scalefss_round_mask:
3545   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3546   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3547   case X86::BI__builtin_ia32_sqrtss_round_mask:
3548   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3549   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3550   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3551   case X86::BI__builtin_ia32_vfmaddss3_mask:
3552   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3553   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3554   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3555   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3556   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3557   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3558   case X86::BI__builtin_ia32_vfmaddps512_mask:
3559   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3560   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3561   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3562   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3563   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3564   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3565   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3566   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3567   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3568   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3569   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3570     ArgNum = 4;
3571     HasRC = true;
3572     break;
3573   }
3574 
3575   llvm::APSInt Result;
3576 
3577   // We can't check the value of a dependent argument.
3578   Expr *Arg = TheCall->getArg(ArgNum);
3579   if (Arg->isTypeDependent() || Arg->isValueDependent())
3580     return false;
3581 
3582   // Check constant-ness first.
3583   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3584     return true;
3585 
3586   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3587   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3588   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3589   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3590   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3591       Result == 8/*ROUND_NO_EXC*/ ||
3592       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3593       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3594     return false;
3595 
3596   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3597          << Arg->getSourceRange();
3598 }
3599 
3600 // Check if the gather/scatter scale is legal.
3601 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3602                                              CallExpr *TheCall) {
3603   unsigned ArgNum = 0;
3604   switch (BuiltinID) {
3605   default:
3606     return false;
3607   case X86::BI__builtin_ia32_gatherpfdpd:
3608   case X86::BI__builtin_ia32_gatherpfdps:
3609   case X86::BI__builtin_ia32_gatherpfqpd:
3610   case X86::BI__builtin_ia32_gatherpfqps:
3611   case X86::BI__builtin_ia32_scatterpfdpd:
3612   case X86::BI__builtin_ia32_scatterpfdps:
3613   case X86::BI__builtin_ia32_scatterpfqpd:
3614   case X86::BI__builtin_ia32_scatterpfqps:
3615     ArgNum = 3;
3616     break;
3617   case X86::BI__builtin_ia32_gatherd_pd:
3618   case X86::BI__builtin_ia32_gatherd_pd256:
3619   case X86::BI__builtin_ia32_gatherq_pd:
3620   case X86::BI__builtin_ia32_gatherq_pd256:
3621   case X86::BI__builtin_ia32_gatherd_ps:
3622   case X86::BI__builtin_ia32_gatherd_ps256:
3623   case X86::BI__builtin_ia32_gatherq_ps:
3624   case X86::BI__builtin_ia32_gatherq_ps256:
3625   case X86::BI__builtin_ia32_gatherd_q:
3626   case X86::BI__builtin_ia32_gatherd_q256:
3627   case X86::BI__builtin_ia32_gatherq_q:
3628   case X86::BI__builtin_ia32_gatherq_q256:
3629   case X86::BI__builtin_ia32_gatherd_d:
3630   case X86::BI__builtin_ia32_gatherd_d256:
3631   case X86::BI__builtin_ia32_gatherq_d:
3632   case X86::BI__builtin_ia32_gatherq_d256:
3633   case X86::BI__builtin_ia32_gather3div2df:
3634   case X86::BI__builtin_ia32_gather3div2di:
3635   case X86::BI__builtin_ia32_gather3div4df:
3636   case X86::BI__builtin_ia32_gather3div4di:
3637   case X86::BI__builtin_ia32_gather3div4sf:
3638   case X86::BI__builtin_ia32_gather3div4si:
3639   case X86::BI__builtin_ia32_gather3div8sf:
3640   case X86::BI__builtin_ia32_gather3div8si:
3641   case X86::BI__builtin_ia32_gather3siv2df:
3642   case X86::BI__builtin_ia32_gather3siv2di:
3643   case X86::BI__builtin_ia32_gather3siv4df:
3644   case X86::BI__builtin_ia32_gather3siv4di:
3645   case X86::BI__builtin_ia32_gather3siv4sf:
3646   case X86::BI__builtin_ia32_gather3siv4si:
3647   case X86::BI__builtin_ia32_gather3siv8sf:
3648   case X86::BI__builtin_ia32_gather3siv8si:
3649   case X86::BI__builtin_ia32_gathersiv8df:
3650   case X86::BI__builtin_ia32_gathersiv16sf:
3651   case X86::BI__builtin_ia32_gatherdiv8df:
3652   case X86::BI__builtin_ia32_gatherdiv16sf:
3653   case X86::BI__builtin_ia32_gathersiv8di:
3654   case X86::BI__builtin_ia32_gathersiv16si:
3655   case X86::BI__builtin_ia32_gatherdiv8di:
3656   case X86::BI__builtin_ia32_gatherdiv16si:
3657   case X86::BI__builtin_ia32_scatterdiv2df:
3658   case X86::BI__builtin_ia32_scatterdiv2di:
3659   case X86::BI__builtin_ia32_scatterdiv4df:
3660   case X86::BI__builtin_ia32_scatterdiv4di:
3661   case X86::BI__builtin_ia32_scatterdiv4sf:
3662   case X86::BI__builtin_ia32_scatterdiv4si:
3663   case X86::BI__builtin_ia32_scatterdiv8sf:
3664   case X86::BI__builtin_ia32_scatterdiv8si:
3665   case X86::BI__builtin_ia32_scattersiv2df:
3666   case X86::BI__builtin_ia32_scattersiv2di:
3667   case X86::BI__builtin_ia32_scattersiv4df:
3668   case X86::BI__builtin_ia32_scattersiv4di:
3669   case X86::BI__builtin_ia32_scattersiv4sf:
3670   case X86::BI__builtin_ia32_scattersiv4si:
3671   case X86::BI__builtin_ia32_scattersiv8sf:
3672   case X86::BI__builtin_ia32_scattersiv8si:
3673   case X86::BI__builtin_ia32_scattersiv8df:
3674   case X86::BI__builtin_ia32_scattersiv16sf:
3675   case X86::BI__builtin_ia32_scatterdiv8df:
3676   case X86::BI__builtin_ia32_scatterdiv16sf:
3677   case X86::BI__builtin_ia32_scattersiv8di:
3678   case X86::BI__builtin_ia32_scattersiv16si:
3679   case X86::BI__builtin_ia32_scatterdiv8di:
3680   case X86::BI__builtin_ia32_scatterdiv16si:
3681     ArgNum = 4;
3682     break;
3683   }
3684 
3685   llvm::APSInt Result;
3686 
3687   // We can't check the value of a dependent argument.
3688   Expr *Arg = TheCall->getArg(ArgNum);
3689   if (Arg->isTypeDependent() || Arg->isValueDependent())
3690     return false;
3691 
3692   // Check constant-ness first.
3693   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3694     return true;
3695 
3696   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3697     return false;
3698 
3699   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3700          << Arg->getSourceRange();
3701 }
3702 
3703 static bool isX86_32Builtin(unsigned BuiltinID) {
3704   // These builtins only work on x86-32 targets.
3705   switch (BuiltinID) {
3706   case X86::BI__builtin_ia32_readeflags_u32:
3707   case X86::BI__builtin_ia32_writeeflags_u32:
3708     return true;
3709   }
3710 
3711   return false;
3712 }
3713 
3714 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3715   if (BuiltinID == X86::BI__builtin_cpu_supports)
3716     return SemaBuiltinCpuSupports(*this, TheCall);
3717 
3718   if (BuiltinID == X86::BI__builtin_cpu_is)
3719     return SemaBuiltinCpuIs(*this, TheCall);
3720 
3721   // Check for 32-bit only builtins on a 64-bit target.
3722   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3723   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3724     return Diag(TheCall->getCallee()->getBeginLoc(),
3725                 diag::err_32_bit_builtin_64_bit_tgt);
3726 
3727   // If the intrinsic has rounding or SAE make sure its valid.
3728   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3729     return true;
3730 
3731   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3732   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3733     return true;
3734 
3735   // For intrinsics which take an immediate value as part of the instruction,
3736   // range check them here.
3737   int i = 0, l = 0, u = 0;
3738   switch (BuiltinID) {
3739   default:
3740     return false;
3741   case X86::BI__builtin_ia32_vec_ext_v2si:
3742   case X86::BI__builtin_ia32_vec_ext_v2di:
3743   case X86::BI__builtin_ia32_vextractf128_pd256:
3744   case X86::BI__builtin_ia32_vextractf128_ps256:
3745   case X86::BI__builtin_ia32_vextractf128_si256:
3746   case X86::BI__builtin_ia32_extract128i256:
3747   case X86::BI__builtin_ia32_extractf64x4_mask:
3748   case X86::BI__builtin_ia32_extracti64x4_mask:
3749   case X86::BI__builtin_ia32_extractf32x8_mask:
3750   case X86::BI__builtin_ia32_extracti32x8_mask:
3751   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3752   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3753   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3754   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3755     i = 1; l = 0; u = 1;
3756     break;
3757   case X86::BI__builtin_ia32_vec_set_v2di:
3758   case X86::BI__builtin_ia32_vinsertf128_pd256:
3759   case X86::BI__builtin_ia32_vinsertf128_ps256:
3760   case X86::BI__builtin_ia32_vinsertf128_si256:
3761   case X86::BI__builtin_ia32_insert128i256:
3762   case X86::BI__builtin_ia32_insertf32x8:
3763   case X86::BI__builtin_ia32_inserti32x8:
3764   case X86::BI__builtin_ia32_insertf64x4:
3765   case X86::BI__builtin_ia32_inserti64x4:
3766   case X86::BI__builtin_ia32_insertf64x2_256:
3767   case X86::BI__builtin_ia32_inserti64x2_256:
3768   case X86::BI__builtin_ia32_insertf32x4_256:
3769   case X86::BI__builtin_ia32_inserti32x4_256:
3770     i = 2; l = 0; u = 1;
3771     break;
3772   case X86::BI__builtin_ia32_vpermilpd:
3773   case X86::BI__builtin_ia32_vec_ext_v4hi:
3774   case X86::BI__builtin_ia32_vec_ext_v4si:
3775   case X86::BI__builtin_ia32_vec_ext_v4sf:
3776   case X86::BI__builtin_ia32_vec_ext_v4di:
3777   case X86::BI__builtin_ia32_extractf32x4_mask:
3778   case X86::BI__builtin_ia32_extracti32x4_mask:
3779   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3780   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3781     i = 1; l = 0; u = 3;
3782     break;
3783   case X86::BI_mm_prefetch:
3784   case X86::BI__builtin_ia32_vec_ext_v8hi:
3785   case X86::BI__builtin_ia32_vec_ext_v8si:
3786     i = 1; l = 0; u = 7;
3787     break;
3788   case X86::BI__builtin_ia32_sha1rnds4:
3789   case X86::BI__builtin_ia32_blendpd:
3790   case X86::BI__builtin_ia32_shufpd:
3791   case X86::BI__builtin_ia32_vec_set_v4hi:
3792   case X86::BI__builtin_ia32_vec_set_v4si:
3793   case X86::BI__builtin_ia32_vec_set_v4di:
3794   case X86::BI__builtin_ia32_shuf_f32x4_256:
3795   case X86::BI__builtin_ia32_shuf_f64x2_256:
3796   case X86::BI__builtin_ia32_shuf_i32x4_256:
3797   case X86::BI__builtin_ia32_shuf_i64x2_256:
3798   case X86::BI__builtin_ia32_insertf64x2_512:
3799   case X86::BI__builtin_ia32_inserti64x2_512:
3800   case X86::BI__builtin_ia32_insertf32x4:
3801   case X86::BI__builtin_ia32_inserti32x4:
3802     i = 2; l = 0; u = 3;
3803     break;
3804   case X86::BI__builtin_ia32_vpermil2pd:
3805   case X86::BI__builtin_ia32_vpermil2pd256:
3806   case X86::BI__builtin_ia32_vpermil2ps:
3807   case X86::BI__builtin_ia32_vpermil2ps256:
3808     i = 3; l = 0; u = 3;
3809     break;
3810   case X86::BI__builtin_ia32_cmpb128_mask:
3811   case X86::BI__builtin_ia32_cmpw128_mask:
3812   case X86::BI__builtin_ia32_cmpd128_mask:
3813   case X86::BI__builtin_ia32_cmpq128_mask:
3814   case X86::BI__builtin_ia32_cmpb256_mask:
3815   case X86::BI__builtin_ia32_cmpw256_mask:
3816   case X86::BI__builtin_ia32_cmpd256_mask:
3817   case X86::BI__builtin_ia32_cmpq256_mask:
3818   case X86::BI__builtin_ia32_cmpb512_mask:
3819   case X86::BI__builtin_ia32_cmpw512_mask:
3820   case X86::BI__builtin_ia32_cmpd512_mask:
3821   case X86::BI__builtin_ia32_cmpq512_mask:
3822   case X86::BI__builtin_ia32_ucmpb128_mask:
3823   case X86::BI__builtin_ia32_ucmpw128_mask:
3824   case X86::BI__builtin_ia32_ucmpd128_mask:
3825   case X86::BI__builtin_ia32_ucmpq128_mask:
3826   case X86::BI__builtin_ia32_ucmpb256_mask:
3827   case X86::BI__builtin_ia32_ucmpw256_mask:
3828   case X86::BI__builtin_ia32_ucmpd256_mask:
3829   case X86::BI__builtin_ia32_ucmpq256_mask:
3830   case X86::BI__builtin_ia32_ucmpb512_mask:
3831   case X86::BI__builtin_ia32_ucmpw512_mask:
3832   case X86::BI__builtin_ia32_ucmpd512_mask:
3833   case X86::BI__builtin_ia32_ucmpq512_mask:
3834   case X86::BI__builtin_ia32_vpcomub:
3835   case X86::BI__builtin_ia32_vpcomuw:
3836   case X86::BI__builtin_ia32_vpcomud:
3837   case X86::BI__builtin_ia32_vpcomuq:
3838   case X86::BI__builtin_ia32_vpcomb:
3839   case X86::BI__builtin_ia32_vpcomw:
3840   case X86::BI__builtin_ia32_vpcomd:
3841   case X86::BI__builtin_ia32_vpcomq:
3842   case X86::BI__builtin_ia32_vec_set_v8hi:
3843   case X86::BI__builtin_ia32_vec_set_v8si:
3844     i = 2; l = 0; u = 7;
3845     break;
3846   case X86::BI__builtin_ia32_vpermilpd256:
3847   case X86::BI__builtin_ia32_roundps:
3848   case X86::BI__builtin_ia32_roundpd:
3849   case X86::BI__builtin_ia32_roundps256:
3850   case X86::BI__builtin_ia32_roundpd256:
3851   case X86::BI__builtin_ia32_getmantpd128_mask:
3852   case X86::BI__builtin_ia32_getmantpd256_mask:
3853   case X86::BI__builtin_ia32_getmantps128_mask:
3854   case X86::BI__builtin_ia32_getmantps256_mask:
3855   case X86::BI__builtin_ia32_getmantpd512_mask:
3856   case X86::BI__builtin_ia32_getmantps512_mask:
3857   case X86::BI__builtin_ia32_vec_ext_v16qi:
3858   case X86::BI__builtin_ia32_vec_ext_v16hi:
3859     i = 1; l = 0; u = 15;
3860     break;
3861   case X86::BI__builtin_ia32_pblendd128:
3862   case X86::BI__builtin_ia32_blendps:
3863   case X86::BI__builtin_ia32_blendpd256:
3864   case X86::BI__builtin_ia32_shufpd256:
3865   case X86::BI__builtin_ia32_roundss:
3866   case X86::BI__builtin_ia32_roundsd:
3867   case X86::BI__builtin_ia32_rangepd128_mask:
3868   case X86::BI__builtin_ia32_rangepd256_mask:
3869   case X86::BI__builtin_ia32_rangepd512_mask:
3870   case X86::BI__builtin_ia32_rangeps128_mask:
3871   case X86::BI__builtin_ia32_rangeps256_mask:
3872   case X86::BI__builtin_ia32_rangeps512_mask:
3873   case X86::BI__builtin_ia32_getmantsd_round_mask:
3874   case X86::BI__builtin_ia32_getmantss_round_mask:
3875   case X86::BI__builtin_ia32_vec_set_v16qi:
3876   case X86::BI__builtin_ia32_vec_set_v16hi:
3877     i = 2; l = 0; u = 15;
3878     break;
3879   case X86::BI__builtin_ia32_vec_ext_v32qi:
3880     i = 1; l = 0; u = 31;
3881     break;
3882   case X86::BI__builtin_ia32_cmpps:
3883   case X86::BI__builtin_ia32_cmpss:
3884   case X86::BI__builtin_ia32_cmppd:
3885   case X86::BI__builtin_ia32_cmpsd:
3886   case X86::BI__builtin_ia32_cmpps256:
3887   case X86::BI__builtin_ia32_cmppd256:
3888   case X86::BI__builtin_ia32_cmpps128_mask:
3889   case X86::BI__builtin_ia32_cmppd128_mask:
3890   case X86::BI__builtin_ia32_cmpps256_mask:
3891   case X86::BI__builtin_ia32_cmppd256_mask:
3892   case X86::BI__builtin_ia32_cmpps512_mask:
3893   case X86::BI__builtin_ia32_cmppd512_mask:
3894   case X86::BI__builtin_ia32_cmpsd_mask:
3895   case X86::BI__builtin_ia32_cmpss_mask:
3896   case X86::BI__builtin_ia32_vec_set_v32qi:
3897     i = 2; l = 0; u = 31;
3898     break;
3899   case X86::BI__builtin_ia32_permdf256:
3900   case X86::BI__builtin_ia32_permdi256:
3901   case X86::BI__builtin_ia32_permdf512:
3902   case X86::BI__builtin_ia32_permdi512:
3903   case X86::BI__builtin_ia32_vpermilps:
3904   case X86::BI__builtin_ia32_vpermilps256:
3905   case X86::BI__builtin_ia32_vpermilpd512:
3906   case X86::BI__builtin_ia32_vpermilps512:
3907   case X86::BI__builtin_ia32_pshufd:
3908   case X86::BI__builtin_ia32_pshufd256:
3909   case X86::BI__builtin_ia32_pshufd512:
3910   case X86::BI__builtin_ia32_pshufhw:
3911   case X86::BI__builtin_ia32_pshufhw256:
3912   case X86::BI__builtin_ia32_pshufhw512:
3913   case X86::BI__builtin_ia32_pshuflw:
3914   case X86::BI__builtin_ia32_pshuflw256:
3915   case X86::BI__builtin_ia32_pshuflw512:
3916   case X86::BI__builtin_ia32_vcvtps2ph:
3917   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3918   case X86::BI__builtin_ia32_vcvtps2ph256:
3919   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3920   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3921   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3922   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3923   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3924   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3925   case X86::BI__builtin_ia32_rndscaleps_mask:
3926   case X86::BI__builtin_ia32_rndscalepd_mask:
3927   case X86::BI__builtin_ia32_reducepd128_mask:
3928   case X86::BI__builtin_ia32_reducepd256_mask:
3929   case X86::BI__builtin_ia32_reducepd512_mask:
3930   case X86::BI__builtin_ia32_reduceps128_mask:
3931   case X86::BI__builtin_ia32_reduceps256_mask:
3932   case X86::BI__builtin_ia32_reduceps512_mask:
3933   case X86::BI__builtin_ia32_prold512:
3934   case X86::BI__builtin_ia32_prolq512:
3935   case X86::BI__builtin_ia32_prold128:
3936   case X86::BI__builtin_ia32_prold256:
3937   case X86::BI__builtin_ia32_prolq128:
3938   case X86::BI__builtin_ia32_prolq256:
3939   case X86::BI__builtin_ia32_prord512:
3940   case X86::BI__builtin_ia32_prorq512:
3941   case X86::BI__builtin_ia32_prord128:
3942   case X86::BI__builtin_ia32_prord256:
3943   case X86::BI__builtin_ia32_prorq128:
3944   case X86::BI__builtin_ia32_prorq256:
3945   case X86::BI__builtin_ia32_fpclasspd128_mask:
3946   case X86::BI__builtin_ia32_fpclasspd256_mask:
3947   case X86::BI__builtin_ia32_fpclassps128_mask:
3948   case X86::BI__builtin_ia32_fpclassps256_mask:
3949   case X86::BI__builtin_ia32_fpclassps512_mask:
3950   case X86::BI__builtin_ia32_fpclasspd512_mask:
3951   case X86::BI__builtin_ia32_fpclasssd_mask:
3952   case X86::BI__builtin_ia32_fpclassss_mask:
3953   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3954   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3955   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3956   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3957   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3958   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3959   case X86::BI__builtin_ia32_kshiftliqi:
3960   case X86::BI__builtin_ia32_kshiftlihi:
3961   case X86::BI__builtin_ia32_kshiftlisi:
3962   case X86::BI__builtin_ia32_kshiftlidi:
3963   case X86::BI__builtin_ia32_kshiftriqi:
3964   case X86::BI__builtin_ia32_kshiftrihi:
3965   case X86::BI__builtin_ia32_kshiftrisi:
3966   case X86::BI__builtin_ia32_kshiftridi:
3967     i = 1; l = 0; u = 255;
3968     break;
3969   case X86::BI__builtin_ia32_vperm2f128_pd256:
3970   case X86::BI__builtin_ia32_vperm2f128_ps256:
3971   case X86::BI__builtin_ia32_vperm2f128_si256:
3972   case X86::BI__builtin_ia32_permti256:
3973   case X86::BI__builtin_ia32_pblendw128:
3974   case X86::BI__builtin_ia32_pblendw256:
3975   case X86::BI__builtin_ia32_blendps256:
3976   case X86::BI__builtin_ia32_pblendd256:
3977   case X86::BI__builtin_ia32_palignr128:
3978   case X86::BI__builtin_ia32_palignr256:
3979   case X86::BI__builtin_ia32_palignr512:
3980   case X86::BI__builtin_ia32_alignq512:
3981   case X86::BI__builtin_ia32_alignd512:
3982   case X86::BI__builtin_ia32_alignd128:
3983   case X86::BI__builtin_ia32_alignd256:
3984   case X86::BI__builtin_ia32_alignq128:
3985   case X86::BI__builtin_ia32_alignq256:
3986   case X86::BI__builtin_ia32_vcomisd:
3987   case X86::BI__builtin_ia32_vcomiss:
3988   case X86::BI__builtin_ia32_shuf_f32x4:
3989   case X86::BI__builtin_ia32_shuf_f64x2:
3990   case X86::BI__builtin_ia32_shuf_i32x4:
3991   case X86::BI__builtin_ia32_shuf_i64x2:
3992   case X86::BI__builtin_ia32_shufpd512:
3993   case X86::BI__builtin_ia32_shufps:
3994   case X86::BI__builtin_ia32_shufps256:
3995   case X86::BI__builtin_ia32_shufps512:
3996   case X86::BI__builtin_ia32_dbpsadbw128:
3997   case X86::BI__builtin_ia32_dbpsadbw256:
3998   case X86::BI__builtin_ia32_dbpsadbw512:
3999   case X86::BI__builtin_ia32_vpshldd128:
4000   case X86::BI__builtin_ia32_vpshldd256:
4001   case X86::BI__builtin_ia32_vpshldd512:
4002   case X86::BI__builtin_ia32_vpshldq128:
4003   case X86::BI__builtin_ia32_vpshldq256:
4004   case X86::BI__builtin_ia32_vpshldq512:
4005   case X86::BI__builtin_ia32_vpshldw128:
4006   case X86::BI__builtin_ia32_vpshldw256:
4007   case X86::BI__builtin_ia32_vpshldw512:
4008   case X86::BI__builtin_ia32_vpshrdd128:
4009   case X86::BI__builtin_ia32_vpshrdd256:
4010   case X86::BI__builtin_ia32_vpshrdd512:
4011   case X86::BI__builtin_ia32_vpshrdq128:
4012   case X86::BI__builtin_ia32_vpshrdq256:
4013   case X86::BI__builtin_ia32_vpshrdq512:
4014   case X86::BI__builtin_ia32_vpshrdw128:
4015   case X86::BI__builtin_ia32_vpshrdw256:
4016   case X86::BI__builtin_ia32_vpshrdw512:
4017     i = 2; l = 0; u = 255;
4018     break;
4019   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4020   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4021   case X86::BI__builtin_ia32_fixupimmps512_mask:
4022   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4023   case X86::BI__builtin_ia32_fixupimmsd_mask:
4024   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4025   case X86::BI__builtin_ia32_fixupimmss_mask:
4026   case X86::BI__builtin_ia32_fixupimmss_maskz:
4027   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4028   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4029   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4030   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4031   case X86::BI__builtin_ia32_fixupimmps128_mask:
4032   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4033   case X86::BI__builtin_ia32_fixupimmps256_mask:
4034   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4035   case X86::BI__builtin_ia32_pternlogd512_mask:
4036   case X86::BI__builtin_ia32_pternlogd512_maskz:
4037   case X86::BI__builtin_ia32_pternlogq512_mask:
4038   case X86::BI__builtin_ia32_pternlogq512_maskz:
4039   case X86::BI__builtin_ia32_pternlogd128_mask:
4040   case X86::BI__builtin_ia32_pternlogd128_maskz:
4041   case X86::BI__builtin_ia32_pternlogd256_mask:
4042   case X86::BI__builtin_ia32_pternlogd256_maskz:
4043   case X86::BI__builtin_ia32_pternlogq128_mask:
4044   case X86::BI__builtin_ia32_pternlogq128_maskz:
4045   case X86::BI__builtin_ia32_pternlogq256_mask:
4046   case X86::BI__builtin_ia32_pternlogq256_maskz:
4047     i = 3; l = 0; u = 255;
4048     break;
4049   case X86::BI__builtin_ia32_gatherpfdpd:
4050   case X86::BI__builtin_ia32_gatherpfdps:
4051   case X86::BI__builtin_ia32_gatherpfqpd:
4052   case X86::BI__builtin_ia32_gatherpfqps:
4053   case X86::BI__builtin_ia32_scatterpfdpd:
4054   case X86::BI__builtin_ia32_scatterpfdps:
4055   case X86::BI__builtin_ia32_scatterpfqpd:
4056   case X86::BI__builtin_ia32_scatterpfqps:
4057     i = 4; l = 2; u = 3;
4058     break;
4059   case X86::BI__builtin_ia32_reducesd_mask:
4060   case X86::BI__builtin_ia32_reducess_mask:
4061   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4062   case X86::BI__builtin_ia32_rndscaless_round_mask:
4063     i = 4; l = 0; u = 255;
4064     break;
4065   }
4066 
4067   // Note that we don't force a hard error on the range check here, allowing
4068   // template-generated or macro-generated dead code to potentially have out-of-
4069   // range values. These need to code generate, but don't need to necessarily
4070   // make any sense. We use a warning that defaults to an error.
4071   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4072 }
4073 
4074 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4075 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4076 /// Returns true when the format fits the function and the FormatStringInfo has
4077 /// been populated.
4078 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4079                                FormatStringInfo *FSI) {
4080   FSI->HasVAListArg = Format->getFirstArg() == 0;
4081   FSI->FormatIdx = Format->getFormatIdx() - 1;
4082   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4083 
4084   // The way the format attribute works in GCC, the implicit this argument
4085   // of member functions is counted. However, it doesn't appear in our own
4086   // lists, so decrement format_idx in that case.
4087   if (IsCXXMember) {
4088     if(FSI->FormatIdx == 0)
4089       return false;
4090     --FSI->FormatIdx;
4091     if (FSI->FirstDataArg != 0)
4092       --FSI->FirstDataArg;
4093   }
4094   return true;
4095 }
4096 
4097 /// Checks if a the given expression evaluates to null.
4098 ///
4099 /// Returns true if the value evaluates to null.
4100 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4101   // If the expression has non-null type, it doesn't evaluate to null.
4102   if (auto nullability
4103         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4104     if (*nullability == NullabilityKind::NonNull)
4105       return false;
4106   }
4107 
4108   // As a special case, transparent unions initialized with zero are
4109   // considered null for the purposes of the nonnull attribute.
4110   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4111     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4112       if (const CompoundLiteralExpr *CLE =
4113           dyn_cast<CompoundLiteralExpr>(Expr))
4114         if (const InitListExpr *ILE =
4115             dyn_cast<InitListExpr>(CLE->getInitializer()))
4116           Expr = ILE->getInit(0);
4117   }
4118 
4119   bool Result;
4120   return (!Expr->isValueDependent() &&
4121           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4122           !Result);
4123 }
4124 
4125 static void CheckNonNullArgument(Sema &S,
4126                                  const Expr *ArgExpr,
4127                                  SourceLocation CallSiteLoc) {
4128   if (CheckNonNullExpr(S, ArgExpr))
4129     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4130                           S.PDiag(diag::warn_null_arg)
4131                               << ArgExpr->getSourceRange());
4132 }
4133 
4134 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4135   FormatStringInfo FSI;
4136   if ((GetFormatStringType(Format) == FST_NSString) &&
4137       getFormatStringInfo(Format, false, &FSI)) {
4138     Idx = FSI.FormatIdx;
4139     return true;
4140   }
4141   return false;
4142 }
4143 
4144 /// Diagnose use of %s directive in an NSString which is being passed
4145 /// as formatting string to formatting method.
4146 static void
4147 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4148                                         const NamedDecl *FDecl,
4149                                         Expr **Args,
4150                                         unsigned NumArgs) {
4151   unsigned Idx = 0;
4152   bool Format = false;
4153   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4154   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4155     Idx = 2;
4156     Format = true;
4157   }
4158   else
4159     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4160       if (S.GetFormatNSStringIdx(I, Idx)) {
4161         Format = true;
4162         break;
4163       }
4164     }
4165   if (!Format || NumArgs <= Idx)
4166     return;
4167   const Expr *FormatExpr = Args[Idx];
4168   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4169     FormatExpr = CSCE->getSubExpr();
4170   const StringLiteral *FormatString;
4171   if (const ObjCStringLiteral *OSL =
4172       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4173     FormatString = OSL->getString();
4174   else
4175     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4176   if (!FormatString)
4177     return;
4178   if (S.FormatStringHasSArg(FormatString)) {
4179     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4180       << "%s" << 1 << 1;
4181     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4182       << FDecl->getDeclName();
4183   }
4184 }
4185 
4186 /// Determine whether the given type has a non-null nullability annotation.
4187 static bool isNonNullType(ASTContext &ctx, QualType type) {
4188   if (auto nullability = type->getNullability(ctx))
4189     return *nullability == NullabilityKind::NonNull;
4190 
4191   return false;
4192 }
4193 
4194 static void CheckNonNullArguments(Sema &S,
4195                                   const NamedDecl *FDecl,
4196                                   const FunctionProtoType *Proto,
4197                                   ArrayRef<const Expr *> Args,
4198                                   SourceLocation CallSiteLoc) {
4199   assert((FDecl || Proto) && "Need a function declaration or prototype");
4200 
4201   // Already checked by by constant evaluator.
4202   if (S.isConstantEvaluated())
4203     return;
4204   // Check the attributes attached to the method/function itself.
4205   llvm::SmallBitVector NonNullArgs;
4206   if (FDecl) {
4207     // Handle the nonnull attribute on the function/method declaration itself.
4208     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4209       if (!NonNull->args_size()) {
4210         // Easy case: all pointer arguments are nonnull.
4211         for (const auto *Arg : Args)
4212           if (S.isValidPointerAttrType(Arg->getType()))
4213             CheckNonNullArgument(S, Arg, CallSiteLoc);
4214         return;
4215       }
4216 
4217       for (const ParamIdx &Idx : NonNull->args()) {
4218         unsigned IdxAST = Idx.getASTIndex();
4219         if (IdxAST >= Args.size())
4220           continue;
4221         if (NonNullArgs.empty())
4222           NonNullArgs.resize(Args.size());
4223         NonNullArgs.set(IdxAST);
4224       }
4225     }
4226   }
4227 
4228   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4229     // Handle the nonnull attribute on the parameters of the
4230     // function/method.
4231     ArrayRef<ParmVarDecl*> parms;
4232     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4233       parms = FD->parameters();
4234     else
4235       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4236 
4237     unsigned ParamIndex = 0;
4238     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4239          I != E; ++I, ++ParamIndex) {
4240       const ParmVarDecl *PVD = *I;
4241       if (PVD->hasAttr<NonNullAttr>() ||
4242           isNonNullType(S.Context, PVD->getType())) {
4243         if (NonNullArgs.empty())
4244           NonNullArgs.resize(Args.size());
4245 
4246         NonNullArgs.set(ParamIndex);
4247       }
4248     }
4249   } else {
4250     // If we have a non-function, non-method declaration but no
4251     // function prototype, try to dig out the function prototype.
4252     if (!Proto) {
4253       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4254         QualType type = VD->getType().getNonReferenceType();
4255         if (auto pointerType = type->getAs<PointerType>())
4256           type = pointerType->getPointeeType();
4257         else if (auto blockType = type->getAs<BlockPointerType>())
4258           type = blockType->getPointeeType();
4259         // FIXME: data member pointers?
4260 
4261         // Dig out the function prototype, if there is one.
4262         Proto = type->getAs<FunctionProtoType>();
4263       }
4264     }
4265 
4266     // Fill in non-null argument information from the nullability
4267     // information on the parameter types (if we have them).
4268     if (Proto) {
4269       unsigned Index = 0;
4270       for (auto paramType : Proto->getParamTypes()) {
4271         if (isNonNullType(S.Context, paramType)) {
4272           if (NonNullArgs.empty())
4273             NonNullArgs.resize(Args.size());
4274 
4275           NonNullArgs.set(Index);
4276         }
4277 
4278         ++Index;
4279       }
4280     }
4281   }
4282 
4283   // Check for non-null arguments.
4284   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4285        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4286     if (NonNullArgs[ArgIndex])
4287       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4288   }
4289 }
4290 
4291 /// Handles the checks for format strings, non-POD arguments to vararg
4292 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4293 /// attributes.
4294 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4295                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4296                      bool IsMemberFunction, SourceLocation Loc,
4297                      SourceRange Range, VariadicCallType CallType) {
4298   // FIXME: We should check as much as we can in the template definition.
4299   if (CurContext->isDependentContext())
4300     return;
4301 
4302   // Printf and scanf checking.
4303   llvm::SmallBitVector CheckedVarArgs;
4304   if (FDecl) {
4305     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4306       // Only create vector if there are format attributes.
4307       CheckedVarArgs.resize(Args.size());
4308 
4309       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4310                            CheckedVarArgs);
4311     }
4312   }
4313 
4314   // Refuse POD arguments that weren't caught by the format string
4315   // checks above.
4316   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4317   if (CallType != VariadicDoesNotApply &&
4318       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4319     unsigned NumParams = Proto ? Proto->getNumParams()
4320                        : FDecl && isa<FunctionDecl>(FDecl)
4321                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4322                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4323                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4324                        : 0;
4325 
4326     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4327       // Args[ArgIdx] can be null in malformed code.
4328       if (const Expr *Arg = Args[ArgIdx]) {
4329         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4330           checkVariadicArgument(Arg, CallType);
4331       }
4332     }
4333   }
4334 
4335   if (FDecl || Proto) {
4336     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4337 
4338     // Type safety checking.
4339     if (FDecl) {
4340       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4341         CheckArgumentWithTypeTag(I, Args, Loc);
4342     }
4343   }
4344 
4345   if (FD)
4346     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4347 }
4348 
4349 /// CheckConstructorCall - Check a constructor call for correctness and safety
4350 /// properties not enforced by the C type system.
4351 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4352                                 ArrayRef<const Expr *> Args,
4353                                 const FunctionProtoType *Proto,
4354                                 SourceLocation Loc) {
4355   VariadicCallType CallType =
4356     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4357   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4358             Loc, SourceRange(), CallType);
4359 }
4360 
4361 /// CheckFunctionCall - Check a direct function call for various correctness
4362 /// and safety properties not strictly enforced by the C type system.
4363 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4364                              const FunctionProtoType *Proto) {
4365   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4366                               isa<CXXMethodDecl>(FDecl);
4367   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4368                           IsMemberOperatorCall;
4369   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4370                                                   TheCall->getCallee());
4371   Expr** Args = TheCall->getArgs();
4372   unsigned NumArgs = TheCall->getNumArgs();
4373 
4374   Expr *ImplicitThis = nullptr;
4375   if (IsMemberOperatorCall) {
4376     // If this is a call to a member operator, hide the first argument
4377     // from checkCall.
4378     // FIXME: Our choice of AST representation here is less than ideal.
4379     ImplicitThis = Args[0];
4380     ++Args;
4381     --NumArgs;
4382   } else if (IsMemberFunction)
4383     ImplicitThis =
4384         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4385 
4386   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4387             IsMemberFunction, TheCall->getRParenLoc(),
4388             TheCall->getCallee()->getSourceRange(), CallType);
4389 
4390   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4391   // None of the checks below are needed for functions that don't have
4392   // simple names (e.g., C++ conversion functions).
4393   if (!FnInfo)
4394     return false;
4395 
4396   CheckAbsoluteValueFunction(TheCall, FDecl);
4397   CheckMaxUnsignedZero(TheCall, FDecl);
4398 
4399   if (getLangOpts().ObjC)
4400     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4401 
4402   unsigned CMId = FDecl->getMemoryFunctionKind();
4403   if (CMId == 0)
4404     return false;
4405 
4406   // Handle memory setting and copying functions.
4407   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4408     CheckStrlcpycatArguments(TheCall, FnInfo);
4409   else if (CMId == Builtin::BIstrncat)
4410     CheckStrncatArguments(TheCall, FnInfo);
4411   else
4412     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4413 
4414   return false;
4415 }
4416 
4417 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4418                                ArrayRef<const Expr *> Args) {
4419   VariadicCallType CallType =
4420       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4421 
4422   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4423             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4424             CallType);
4425 
4426   return false;
4427 }
4428 
4429 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4430                             const FunctionProtoType *Proto) {
4431   QualType Ty;
4432   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4433     Ty = V->getType().getNonReferenceType();
4434   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4435     Ty = F->getType().getNonReferenceType();
4436   else
4437     return false;
4438 
4439   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4440       !Ty->isFunctionProtoType())
4441     return false;
4442 
4443   VariadicCallType CallType;
4444   if (!Proto || !Proto->isVariadic()) {
4445     CallType = VariadicDoesNotApply;
4446   } else if (Ty->isBlockPointerType()) {
4447     CallType = VariadicBlock;
4448   } else { // Ty->isFunctionPointerType()
4449     CallType = VariadicFunction;
4450   }
4451 
4452   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4453             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4454             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4455             TheCall->getCallee()->getSourceRange(), CallType);
4456 
4457   return false;
4458 }
4459 
4460 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4461 /// such as function pointers returned from functions.
4462 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4463   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4464                                                   TheCall->getCallee());
4465   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4466             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4467             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4468             TheCall->getCallee()->getSourceRange(), CallType);
4469 
4470   return false;
4471 }
4472 
4473 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4474   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4475     return false;
4476 
4477   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4478   switch (Op) {
4479   case AtomicExpr::AO__c11_atomic_init:
4480   case AtomicExpr::AO__opencl_atomic_init:
4481     llvm_unreachable("There is no ordering argument for an init");
4482 
4483   case AtomicExpr::AO__c11_atomic_load:
4484   case AtomicExpr::AO__opencl_atomic_load:
4485   case AtomicExpr::AO__atomic_load_n:
4486   case AtomicExpr::AO__atomic_load:
4487     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4488            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4489 
4490   case AtomicExpr::AO__c11_atomic_store:
4491   case AtomicExpr::AO__opencl_atomic_store:
4492   case AtomicExpr::AO__atomic_store:
4493   case AtomicExpr::AO__atomic_store_n:
4494     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4495            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4496            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4497 
4498   default:
4499     return true;
4500   }
4501 }
4502 
4503 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4504                                          AtomicExpr::AtomicOp Op) {
4505   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4506   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4507   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4508   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4509                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4510                          Op);
4511 }
4512 
4513 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4514                                  SourceLocation RParenLoc, MultiExprArg Args,
4515                                  AtomicExpr::AtomicOp Op,
4516                                  AtomicArgumentOrder ArgOrder) {
4517   // All the non-OpenCL operations take one of the following forms.
4518   // The OpenCL operations take the __c11 forms with one extra argument for
4519   // synchronization scope.
4520   enum {
4521     // C    __c11_atomic_init(A *, C)
4522     Init,
4523 
4524     // C    __c11_atomic_load(A *, int)
4525     Load,
4526 
4527     // void __atomic_load(A *, CP, int)
4528     LoadCopy,
4529 
4530     // void __atomic_store(A *, CP, int)
4531     Copy,
4532 
4533     // C    __c11_atomic_add(A *, M, int)
4534     Arithmetic,
4535 
4536     // C    __atomic_exchange_n(A *, CP, int)
4537     Xchg,
4538 
4539     // void __atomic_exchange(A *, C *, CP, int)
4540     GNUXchg,
4541 
4542     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4543     C11CmpXchg,
4544 
4545     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4546     GNUCmpXchg
4547   } Form = Init;
4548 
4549   const unsigned NumForm = GNUCmpXchg + 1;
4550   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4551   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4552   // where:
4553   //   C is an appropriate type,
4554   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4555   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4556   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4557   //   the int parameters are for orderings.
4558 
4559   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4560       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4561       "need to update code for modified forms");
4562   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4563                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4564                         AtomicExpr::AO__atomic_load,
4565                 "need to update code for modified C11 atomics");
4566   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4567                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4568   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4569                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4570                IsOpenCL;
4571   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4572              Op == AtomicExpr::AO__atomic_store_n ||
4573              Op == AtomicExpr::AO__atomic_exchange_n ||
4574              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4575   bool IsAddSub = false;
4576   bool IsMinMax = false;
4577 
4578   switch (Op) {
4579   case AtomicExpr::AO__c11_atomic_init:
4580   case AtomicExpr::AO__opencl_atomic_init:
4581     Form = Init;
4582     break;
4583 
4584   case AtomicExpr::AO__c11_atomic_load:
4585   case AtomicExpr::AO__opencl_atomic_load:
4586   case AtomicExpr::AO__atomic_load_n:
4587     Form = Load;
4588     break;
4589 
4590   case AtomicExpr::AO__atomic_load:
4591     Form = LoadCopy;
4592     break;
4593 
4594   case AtomicExpr::AO__c11_atomic_store:
4595   case AtomicExpr::AO__opencl_atomic_store:
4596   case AtomicExpr::AO__atomic_store:
4597   case AtomicExpr::AO__atomic_store_n:
4598     Form = Copy;
4599     break;
4600 
4601   case AtomicExpr::AO__c11_atomic_fetch_add:
4602   case AtomicExpr::AO__c11_atomic_fetch_sub:
4603   case AtomicExpr::AO__opencl_atomic_fetch_add:
4604   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4605   case AtomicExpr::AO__opencl_atomic_fetch_min:
4606   case AtomicExpr::AO__opencl_atomic_fetch_max:
4607   case AtomicExpr::AO__atomic_fetch_add:
4608   case AtomicExpr::AO__atomic_fetch_sub:
4609   case AtomicExpr::AO__atomic_add_fetch:
4610   case AtomicExpr::AO__atomic_sub_fetch:
4611     IsAddSub = true;
4612     LLVM_FALLTHROUGH;
4613   case AtomicExpr::AO__c11_atomic_fetch_and:
4614   case AtomicExpr::AO__c11_atomic_fetch_or:
4615   case AtomicExpr::AO__c11_atomic_fetch_xor:
4616   case AtomicExpr::AO__opencl_atomic_fetch_and:
4617   case AtomicExpr::AO__opencl_atomic_fetch_or:
4618   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4619   case AtomicExpr::AO__atomic_fetch_and:
4620   case AtomicExpr::AO__atomic_fetch_or:
4621   case AtomicExpr::AO__atomic_fetch_xor:
4622   case AtomicExpr::AO__atomic_fetch_nand:
4623   case AtomicExpr::AO__atomic_and_fetch:
4624   case AtomicExpr::AO__atomic_or_fetch:
4625   case AtomicExpr::AO__atomic_xor_fetch:
4626   case AtomicExpr::AO__atomic_nand_fetch:
4627     Form = Arithmetic;
4628     break;
4629 
4630   case AtomicExpr::AO__atomic_fetch_min:
4631   case AtomicExpr::AO__atomic_fetch_max:
4632     IsMinMax = true;
4633     Form = Arithmetic;
4634     break;
4635 
4636   case AtomicExpr::AO__c11_atomic_exchange:
4637   case AtomicExpr::AO__opencl_atomic_exchange:
4638   case AtomicExpr::AO__atomic_exchange_n:
4639     Form = Xchg;
4640     break;
4641 
4642   case AtomicExpr::AO__atomic_exchange:
4643     Form = GNUXchg;
4644     break;
4645 
4646   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4647   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4648   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4649   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4650     Form = C11CmpXchg;
4651     break;
4652 
4653   case AtomicExpr::AO__atomic_compare_exchange:
4654   case AtomicExpr::AO__atomic_compare_exchange_n:
4655     Form = GNUCmpXchg;
4656     break;
4657   }
4658 
4659   unsigned AdjustedNumArgs = NumArgs[Form];
4660   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4661     ++AdjustedNumArgs;
4662   // Check we have the right number of arguments.
4663   if (Args.size() < AdjustedNumArgs) {
4664     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4665         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4666         << ExprRange;
4667     return ExprError();
4668   } else if (Args.size() > AdjustedNumArgs) {
4669     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4670          diag::err_typecheck_call_too_many_args)
4671         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4672         << ExprRange;
4673     return ExprError();
4674   }
4675 
4676   // Inspect the first argument of the atomic operation.
4677   Expr *Ptr = Args[0];
4678   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4679   if (ConvertedPtr.isInvalid())
4680     return ExprError();
4681 
4682   Ptr = ConvertedPtr.get();
4683   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4684   if (!pointerType) {
4685     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4686         << Ptr->getType() << Ptr->getSourceRange();
4687     return ExprError();
4688   }
4689 
4690   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4691   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4692   QualType ValType = AtomTy; // 'C'
4693   if (IsC11) {
4694     if (!AtomTy->isAtomicType()) {
4695       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4696           << Ptr->getType() << Ptr->getSourceRange();
4697       return ExprError();
4698     }
4699     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4700         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4701       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4702           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4703           << Ptr->getSourceRange();
4704       return ExprError();
4705     }
4706     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4707   } else if (Form != Load && Form != LoadCopy) {
4708     if (ValType.isConstQualified()) {
4709       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4710           << Ptr->getType() << Ptr->getSourceRange();
4711       return ExprError();
4712     }
4713   }
4714 
4715   // For an arithmetic operation, the implied arithmetic must be well-formed.
4716   if (Form == Arithmetic) {
4717     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4718     if (IsAddSub && !ValType->isIntegerType()
4719         && !ValType->isPointerType()) {
4720       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4721           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4722       return ExprError();
4723     }
4724     if (IsMinMax) {
4725       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4726       if (!BT || (BT->getKind() != BuiltinType::Int &&
4727                   BT->getKind() != BuiltinType::UInt)) {
4728         Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_int32_or_ptr);
4729         return ExprError();
4730       }
4731     }
4732     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4733       Diag(ExprRange.getBegin(), diag::err_atomic_op_bitwise_needs_atomic_int)
4734           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4735       return ExprError();
4736     }
4737     if (IsC11 && ValType->isPointerType() &&
4738         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4739                             diag::err_incomplete_type)) {
4740       return ExprError();
4741     }
4742   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4743     // For __atomic_*_n operations, the value type must be a scalar integral or
4744     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4745     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4746         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4747     return ExprError();
4748   }
4749 
4750   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4751       !AtomTy->isScalarType()) {
4752     // For GNU atomics, require a trivially-copyable type. This is not part of
4753     // the GNU atomics specification, but we enforce it for sanity.
4754     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4755         << Ptr->getType() << Ptr->getSourceRange();
4756     return ExprError();
4757   }
4758 
4759   switch (ValType.getObjCLifetime()) {
4760   case Qualifiers::OCL_None:
4761   case Qualifiers::OCL_ExplicitNone:
4762     // okay
4763     break;
4764 
4765   case Qualifiers::OCL_Weak:
4766   case Qualifiers::OCL_Strong:
4767   case Qualifiers::OCL_Autoreleasing:
4768     // FIXME: Can this happen? By this point, ValType should be known
4769     // to be trivially copyable.
4770     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4771         << ValType << Ptr->getSourceRange();
4772     return ExprError();
4773   }
4774 
4775   // All atomic operations have an overload which takes a pointer to a volatile
4776   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4777   // into the result or the other operands. Similarly atomic_load takes a
4778   // pointer to a const 'A'.
4779   ValType.removeLocalVolatile();
4780   ValType.removeLocalConst();
4781   QualType ResultType = ValType;
4782   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4783       Form == Init)
4784     ResultType = Context.VoidTy;
4785   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4786     ResultType = Context.BoolTy;
4787 
4788   // The type of a parameter passed 'by value'. In the GNU atomics, such
4789   // arguments are actually passed as pointers.
4790   QualType ByValType = ValType; // 'CP'
4791   bool IsPassedByAddress = false;
4792   if (!IsC11 && !IsN) {
4793     ByValType = Ptr->getType();
4794     IsPassedByAddress = true;
4795   }
4796 
4797   SmallVector<Expr *, 5> APIOrderedArgs;
4798   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4799     APIOrderedArgs.push_back(Args[0]);
4800     switch (Form) {
4801     case Init:
4802     case Load:
4803       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4804       break;
4805     case LoadCopy:
4806     case Copy:
4807     case Arithmetic:
4808     case Xchg:
4809       APIOrderedArgs.push_back(Args[2]); // Val1
4810       APIOrderedArgs.push_back(Args[1]); // Order
4811       break;
4812     case GNUXchg:
4813       APIOrderedArgs.push_back(Args[2]); // Val1
4814       APIOrderedArgs.push_back(Args[3]); // Val2
4815       APIOrderedArgs.push_back(Args[1]); // Order
4816       break;
4817     case C11CmpXchg:
4818       APIOrderedArgs.push_back(Args[2]); // Val1
4819       APIOrderedArgs.push_back(Args[4]); // Val2
4820       APIOrderedArgs.push_back(Args[1]); // Order
4821       APIOrderedArgs.push_back(Args[3]); // OrderFail
4822       break;
4823     case GNUCmpXchg:
4824       APIOrderedArgs.push_back(Args[2]); // Val1
4825       APIOrderedArgs.push_back(Args[4]); // Val2
4826       APIOrderedArgs.push_back(Args[5]); // Weak
4827       APIOrderedArgs.push_back(Args[1]); // Order
4828       APIOrderedArgs.push_back(Args[3]); // OrderFail
4829       break;
4830     }
4831   } else
4832     APIOrderedArgs.append(Args.begin(), Args.end());
4833 
4834   // The first argument's non-CV pointer type is used to deduce the type of
4835   // subsequent arguments, except for:
4836   //  - weak flag (always converted to bool)
4837   //  - memory order (always converted to int)
4838   //  - scope  (always converted to int)
4839   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4840     QualType Ty;
4841     if (i < NumVals[Form] + 1) {
4842       switch (i) {
4843       case 0:
4844         // The first argument is always a pointer. It has a fixed type.
4845         // It is always dereferenced, a nullptr is undefined.
4846         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4847         // Nothing else to do: we already know all we want about this pointer.
4848         continue;
4849       case 1:
4850         // The second argument is the non-atomic operand. For arithmetic, this
4851         // is always passed by value, and for a compare_exchange it is always
4852         // passed by address. For the rest, GNU uses by-address and C11 uses
4853         // by-value.
4854         assert(Form != Load);
4855         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4856           Ty = ValType;
4857         else if (Form == Copy || Form == Xchg) {
4858           if (IsPassedByAddress) {
4859             // The value pointer is always dereferenced, a nullptr is undefined.
4860             CheckNonNullArgument(*this, APIOrderedArgs[i],
4861                                  ExprRange.getBegin());
4862           }
4863           Ty = ByValType;
4864         } else if (Form == Arithmetic)
4865           Ty = Context.getPointerDiffType();
4866         else {
4867           Expr *ValArg = APIOrderedArgs[i];
4868           // The value pointer is always dereferenced, a nullptr is undefined.
4869           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4870           LangAS AS = LangAS::Default;
4871           // Keep address space of non-atomic pointer type.
4872           if (const PointerType *PtrTy =
4873                   ValArg->getType()->getAs<PointerType>()) {
4874             AS = PtrTy->getPointeeType().getAddressSpace();
4875           }
4876           Ty = Context.getPointerType(
4877               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4878         }
4879         break;
4880       case 2:
4881         // The third argument to compare_exchange / GNU exchange is the desired
4882         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4883         if (IsPassedByAddress)
4884           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4885         Ty = ByValType;
4886         break;
4887       case 3:
4888         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4889         Ty = Context.BoolTy;
4890         break;
4891       }
4892     } else {
4893       // The order(s) and scope are always converted to int.
4894       Ty = Context.IntTy;
4895     }
4896 
4897     InitializedEntity Entity =
4898         InitializedEntity::InitializeParameter(Context, Ty, false);
4899     ExprResult Arg = APIOrderedArgs[i];
4900     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4901     if (Arg.isInvalid())
4902       return true;
4903     APIOrderedArgs[i] = Arg.get();
4904   }
4905 
4906   // Permute the arguments into a 'consistent' order.
4907   SmallVector<Expr*, 5> SubExprs;
4908   SubExprs.push_back(Ptr);
4909   switch (Form) {
4910   case Init:
4911     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4912     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4913     break;
4914   case Load:
4915     SubExprs.push_back(APIOrderedArgs[1]); // Order
4916     break;
4917   case LoadCopy:
4918   case Copy:
4919   case Arithmetic:
4920   case Xchg:
4921     SubExprs.push_back(APIOrderedArgs[2]); // Order
4922     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4923     break;
4924   case GNUXchg:
4925     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4926     SubExprs.push_back(APIOrderedArgs[3]); // Order
4927     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4928     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4929     break;
4930   case C11CmpXchg:
4931     SubExprs.push_back(APIOrderedArgs[3]); // Order
4932     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4933     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4934     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4935     break;
4936   case GNUCmpXchg:
4937     SubExprs.push_back(APIOrderedArgs[4]); // Order
4938     SubExprs.push_back(APIOrderedArgs[1]); // Val1
4939     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4940     SubExprs.push_back(APIOrderedArgs[2]); // Val2
4941     SubExprs.push_back(APIOrderedArgs[3]); // Weak
4942     break;
4943   }
4944 
4945   if (SubExprs.size() >= 2 && Form != Init) {
4946     llvm::APSInt Result(32);
4947     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4948         !isValidOrderingForOp(Result.getSExtValue(), Op))
4949       Diag(SubExprs[1]->getBeginLoc(),
4950            diag::warn_atomic_op_has_invalid_memory_order)
4951           << SubExprs[1]->getSourceRange();
4952   }
4953 
4954   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4955     auto *Scope = Args[Args.size() - 1];
4956     llvm::APSInt Result(32);
4957     if (Scope->isIntegerConstantExpr(Result, Context) &&
4958         !ScopeModel->isValid(Result.getZExtValue())) {
4959       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4960           << Scope->getSourceRange();
4961     }
4962     SubExprs.push_back(Scope);
4963   }
4964 
4965   AtomicExpr *AE = new (Context)
4966       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4967 
4968   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4969        Op == AtomicExpr::AO__c11_atomic_store ||
4970        Op == AtomicExpr::AO__opencl_atomic_load ||
4971        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4972       Context.AtomicUsesUnsupportedLibcall(AE))
4973     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4974         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4975              Op == AtomicExpr::AO__opencl_atomic_load)
4976                 ? 0
4977                 : 1);
4978 
4979   return AE;
4980 }
4981 
4982 /// checkBuiltinArgument - Given a call to a builtin function, perform
4983 /// normal type-checking on the given argument, updating the call in
4984 /// place.  This is useful when a builtin function requires custom
4985 /// type-checking for some of its arguments but not necessarily all of
4986 /// them.
4987 ///
4988 /// Returns true on error.
4989 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4990   FunctionDecl *Fn = E->getDirectCallee();
4991   assert(Fn && "builtin call without direct callee!");
4992 
4993   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4994   InitializedEntity Entity =
4995     InitializedEntity::InitializeParameter(S.Context, Param);
4996 
4997   ExprResult Arg = E->getArg(0);
4998   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4999   if (Arg.isInvalid())
5000     return true;
5001 
5002   E->setArg(ArgIndex, Arg.get());
5003   return false;
5004 }
5005 
5006 /// We have a call to a function like __sync_fetch_and_add, which is an
5007 /// overloaded function based on the pointer type of its first argument.
5008 /// The main BuildCallExpr routines have already promoted the types of
5009 /// arguments because all of these calls are prototyped as void(...).
5010 ///
5011 /// This function goes through and does final semantic checking for these
5012 /// builtins, as well as generating any warnings.
5013 ExprResult
5014 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5015   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5016   Expr *Callee = TheCall->getCallee();
5017   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5018   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5019 
5020   // Ensure that we have at least one argument to do type inference from.
5021   if (TheCall->getNumArgs() < 1) {
5022     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5023         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5024     return ExprError();
5025   }
5026 
5027   // Inspect the first argument of the atomic builtin.  This should always be
5028   // a pointer type, whose element is an integral scalar or pointer type.
5029   // Because it is a pointer type, we don't have to worry about any implicit
5030   // casts here.
5031   // FIXME: We don't allow floating point scalars as input.
5032   Expr *FirstArg = TheCall->getArg(0);
5033   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5034   if (FirstArgResult.isInvalid())
5035     return ExprError();
5036   FirstArg = FirstArgResult.get();
5037   TheCall->setArg(0, FirstArg);
5038 
5039   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5040   if (!pointerType) {
5041     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5042         << FirstArg->getType() << FirstArg->getSourceRange();
5043     return ExprError();
5044   }
5045 
5046   QualType ValType = pointerType->getPointeeType();
5047   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5048       !ValType->isBlockPointerType()) {
5049     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5050         << FirstArg->getType() << FirstArg->getSourceRange();
5051     return ExprError();
5052   }
5053 
5054   if (ValType.isConstQualified()) {
5055     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5056         << FirstArg->getType() << FirstArg->getSourceRange();
5057     return ExprError();
5058   }
5059 
5060   switch (ValType.getObjCLifetime()) {
5061   case Qualifiers::OCL_None:
5062   case Qualifiers::OCL_ExplicitNone:
5063     // okay
5064     break;
5065 
5066   case Qualifiers::OCL_Weak:
5067   case Qualifiers::OCL_Strong:
5068   case Qualifiers::OCL_Autoreleasing:
5069     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5070         << ValType << FirstArg->getSourceRange();
5071     return ExprError();
5072   }
5073 
5074   // Strip any qualifiers off ValType.
5075   ValType = ValType.getUnqualifiedType();
5076 
5077   // The majority of builtins return a value, but a few have special return
5078   // types, so allow them to override appropriately below.
5079   QualType ResultType = ValType;
5080 
5081   // We need to figure out which concrete builtin this maps onto.  For example,
5082   // __sync_fetch_and_add with a 2 byte object turns into
5083   // __sync_fetch_and_add_2.
5084 #define BUILTIN_ROW(x) \
5085   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5086     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5087 
5088   static const unsigned BuiltinIndices[][5] = {
5089     BUILTIN_ROW(__sync_fetch_and_add),
5090     BUILTIN_ROW(__sync_fetch_and_sub),
5091     BUILTIN_ROW(__sync_fetch_and_or),
5092     BUILTIN_ROW(__sync_fetch_and_and),
5093     BUILTIN_ROW(__sync_fetch_and_xor),
5094     BUILTIN_ROW(__sync_fetch_and_nand),
5095 
5096     BUILTIN_ROW(__sync_add_and_fetch),
5097     BUILTIN_ROW(__sync_sub_and_fetch),
5098     BUILTIN_ROW(__sync_and_and_fetch),
5099     BUILTIN_ROW(__sync_or_and_fetch),
5100     BUILTIN_ROW(__sync_xor_and_fetch),
5101     BUILTIN_ROW(__sync_nand_and_fetch),
5102 
5103     BUILTIN_ROW(__sync_val_compare_and_swap),
5104     BUILTIN_ROW(__sync_bool_compare_and_swap),
5105     BUILTIN_ROW(__sync_lock_test_and_set),
5106     BUILTIN_ROW(__sync_lock_release),
5107     BUILTIN_ROW(__sync_swap)
5108   };
5109 #undef BUILTIN_ROW
5110 
5111   // Determine the index of the size.
5112   unsigned SizeIndex;
5113   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5114   case 1: SizeIndex = 0; break;
5115   case 2: SizeIndex = 1; break;
5116   case 4: SizeIndex = 2; break;
5117   case 8: SizeIndex = 3; break;
5118   case 16: SizeIndex = 4; break;
5119   default:
5120     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5121         << FirstArg->getType() << FirstArg->getSourceRange();
5122     return ExprError();
5123   }
5124 
5125   // Each of these builtins has one pointer argument, followed by some number of
5126   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5127   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5128   // as the number of fixed args.
5129   unsigned BuiltinID = FDecl->getBuiltinID();
5130   unsigned BuiltinIndex, NumFixed = 1;
5131   bool WarnAboutSemanticsChange = false;
5132   switch (BuiltinID) {
5133   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5134   case Builtin::BI__sync_fetch_and_add:
5135   case Builtin::BI__sync_fetch_and_add_1:
5136   case Builtin::BI__sync_fetch_and_add_2:
5137   case Builtin::BI__sync_fetch_and_add_4:
5138   case Builtin::BI__sync_fetch_and_add_8:
5139   case Builtin::BI__sync_fetch_and_add_16:
5140     BuiltinIndex = 0;
5141     break;
5142 
5143   case Builtin::BI__sync_fetch_and_sub:
5144   case Builtin::BI__sync_fetch_and_sub_1:
5145   case Builtin::BI__sync_fetch_and_sub_2:
5146   case Builtin::BI__sync_fetch_and_sub_4:
5147   case Builtin::BI__sync_fetch_and_sub_8:
5148   case Builtin::BI__sync_fetch_and_sub_16:
5149     BuiltinIndex = 1;
5150     break;
5151 
5152   case Builtin::BI__sync_fetch_and_or:
5153   case Builtin::BI__sync_fetch_and_or_1:
5154   case Builtin::BI__sync_fetch_and_or_2:
5155   case Builtin::BI__sync_fetch_and_or_4:
5156   case Builtin::BI__sync_fetch_and_or_8:
5157   case Builtin::BI__sync_fetch_and_or_16:
5158     BuiltinIndex = 2;
5159     break;
5160 
5161   case Builtin::BI__sync_fetch_and_and:
5162   case Builtin::BI__sync_fetch_and_and_1:
5163   case Builtin::BI__sync_fetch_and_and_2:
5164   case Builtin::BI__sync_fetch_and_and_4:
5165   case Builtin::BI__sync_fetch_and_and_8:
5166   case Builtin::BI__sync_fetch_and_and_16:
5167     BuiltinIndex = 3;
5168     break;
5169 
5170   case Builtin::BI__sync_fetch_and_xor:
5171   case Builtin::BI__sync_fetch_and_xor_1:
5172   case Builtin::BI__sync_fetch_and_xor_2:
5173   case Builtin::BI__sync_fetch_and_xor_4:
5174   case Builtin::BI__sync_fetch_and_xor_8:
5175   case Builtin::BI__sync_fetch_and_xor_16:
5176     BuiltinIndex = 4;
5177     break;
5178 
5179   case Builtin::BI__sync_fetch_and_nand:
5180   case Builtin::BI__sync_fetch_and_nand_1:
5181   case Builtin::BI__sync_fetch_and_nand_2:
5182   case Builtin::BI__sync_fetch_and_nand_4:
5183   case Builtin::BI__sync_fetch_and_nand_8:
5184   case Builtin::BI__sync_fetch_and_nand_16:
5185     BuiltinIndex = 5;
5186     WarnAboutSemanticsChange = true;
5187     break;
5188 
5189   case Builtin::BI__sync_add_and_fetch:
5190   case Builtin::BI__sync_add_and_fetch_1:
5191   case Builtin::BI__sync_add_and_fetch_2:
5192   case Builtin::BI__sync_add_and_fetch_4:
5193   case Builtin::BI__sync_add_and_fetch_8:
5194   case Builtin::BI__sync_add_and_fetch_16:
5195     BuiltinIndex = 6;
5196     break;
5197 
5198   case Builtin::BI__sync_sub_and_fetch:
5199   case Builtin::BI__sync_sub_and_fetch_1:
5200   case Builtin::BI__sync_sub_and_fetch_2:
5201   case Builtin::BI__sync_sub_and_fetch_4:
5202   case Builtin::BI__sync_sub_and_fetch_8:
5203   case Builtin::BI__sync_sub_and_fetch_16:
5204     BuiltinIndex = 7;
5205     break;
5206 
5207   case Builtin::BI__sync_and_and_fetch:
5208   case Builtin::BI__sync_and_and_fetch_1:
5209   case Builtin::BI__sync_and_and_fetch_2:
5210   case Builtin::BI__sync_and_and_fetch_4:
5211   case Builtin::BI__sync_and_and_fetch_8:
5212   case Builtin::BI__sync_and_and_fetch_16:
5213     BuiltinIndex = 8;
5214     break;
5215 
5216   case Builtin::BI__sync_or_and_fetch:
5217   case Builtin::BI__sync_or_and_fetch_1:
5218   case Builtin::BI__sync_or_and_fetch_2:
5219   case Builtin::BI__sync_or_and_fetch_4:
5220   case Builtin::BI__sync_or_and_fetch_8:
5221   case Builtin::BI__sync_or_and_fetch_16:
5222     BuiltinIndex = 9;
5223     break;
5224 
5225   case Builtin::BI__sync_xor_and_fetch:
5226   case Builtin::BI__sync_xor_and_fetch_1:
5227   case Builtin::BI__sync_xor_and_fetch_2:
5228   case Builtin::BI__sync_xor_and_fetch_4:
5229   case Builtin::BI__sync_xor_and_fetch_8:
5230   case Builtin::BI__sync_xor_and_fetch_16:
5231     BuiltinIndex = 10;
5232     break;
5233 
5234   case Builtin::BI__sync_nand_and_fetch:
5235   case Builtin::BI__sync_nand_and_fetch_1:
5236   case Builtin::BI__sync_nand_and_fetch_2:
5237   case Builtin::BI__sync_nand_and_fetch_4:
5238   case Builtin::BI__sync_nand_and_fetch_8:
5239   case Builtin::BI__sync_nand_and_fetch_16:
5240     BuiltinIndex = 11;
5241     WarnAboutSemanticsChange = true;
5242     break;
5243 
5244   case Builtin::BI__sync_val_compare_and_swap:
5245   case Builtin::BI__sync_val_compare_and_swap_1:
5246   case Builtin::BI__sync_val_compare_and_swap_2:
5247   case Builtin::BI__sync_val_compare_and_swap_4:
5248   case Builtin::BI__sync_val_compare_and_swap_8:
5249   case Builtin::BI__sync_val_compare_and_swap_16:
5250     BuiltinIndex = 12;
5251     NumFixed = 2;
5252     break;
5253 
5254   case Builtin::BI__sync_bool_compare_and_swap:
5255   case Builtin::BI__sync_bool_compare_and_swap_1:
5256   case Builtin::BI__sync_bool_compare_and_swap_2:
5257   case Builtin::BI__sync_bool_compare_and_swap_4:
5258   case Builtin::BI__sync_bool_compare_and_swap_8:
5259   case Builtin::BI__sync_bool_compare_and_swap_16:
5260     BuiltinIndex = 13;
5261     NumFixed = 2;
5262     ResultType = Context.BoolTy;
5263     break;
5264 
5265   case Builtin::BI__sync_lock_test_and_set:
5266   case Builtin::BI__sync_lock_test_and_set_1:
5267   case Builtin::BI__sync_lock_test_and_set_2:
5268   case Builtin::BI__sync_lock_test_and_set_4:
5269   case Builtin::BI__sync_lock_test_and_set_8:
5270   case Builtin::BI__sync_lock_test_and_set_16:
5271     BuiltinIndex = 14;
5272     break;
5273 
5274   case Builtin::BI__sync_lock_release:
5275   case Builtin::BI__sync_lock_release_1:
5276   case Builtin::BI__sync_lock_release_2:
5277   case Builtin::BI__sync_lock_release_4:
5278   case Builtin::BI__sync_lock_release_8:
5279   case Builtin::BI__sync_lock_release_16:
5280     BuiltinIndex = 15;
5281     NumFixed = 0;
5282     ResultType = Context.VoidTy;
5283     break;
5284 
5285   case Builtin::BI__sync_swap:
5286   case Builtin::BI__sync_swap_1:
5287   case Builtin::BI__sync_swap_2:
5288   case Builtin::BI__sync_swap_4:
5289   case Builtin::BI__sync_swap_8:
5290   case Builtin::BI__sync_swap_16:
5291     BuiltinIndex = 16;
5292     break;
5293   }
5294 
5295   // Now that we know how many fixed arguments we expect, first check that we
5296   // have at least that many.
5297   if (TheCall->getNumArgs() < 1+NumFixed) {
5298     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5299         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5300         << Callee->getSourceRange();
5301     return ExprError();
5302   }
5303 
5304   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5305       << Callee->getSourceRange();
5306 
5307   if (WarnAboutSemanticsChange) {
5308     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5309         << Callee->getSourceRange();
5310   }
5311 
5312   // Get the decl for the concrete builtin from this, we can tell what the
5313   // concrete integer type we should convert to is.
5314   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5315   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5316   FunctionDecl *NewBuiltinDecl;
5317   if (NewBuiltinID == BuiltinID)
5318     NewBuiltinDecl = FDecl;
5319   else {
5320     // Perform builtin lookup to avoid redeclaring it.
5321     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5322     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5323     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5324     assert(Res.getFoundDecl());
5325     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5326     if (!NewBuiltinDecl)
5327       return ExprError();
5328   }
5329 
5330   // The first argument --- the pointer --- has a fixed type; we
5331   // deduce the types of the rest of the arguments accordingly.  Walk
5332   // the remaining arguments, converting them to the deduced value type.
5333   for (unsigned i = 0; i != NumFixed; ++i) {
5334     ExprResult Arg = TheCall->getArg(i+1);
5335 
5336     // GCC does an implicit conversion to the pointer or integer ValType.  This
5337     // can fail in some cases (1i -> int**), check for this error case now.
5338     // Initialize the argument.
5339     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5340                                                    ValType, /*consume*/ false);
5341     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5342     if (Arg.isInvalid())
5343       return ExprError();
5344 
5345     // Okay, we have something that *can* be converted to the right type.  Check
5346     // to see if there is a potentially weird extension going on here.  This can
5347     // happen when you do an atomic operation on something like an char* and
5348     // pass in 42.  The 42 gets converted to char.  This is even more strange
5349     // for things like 45.123 -> char, etc.
5350     // FIXME: Do this check.
5351     TheCall->setArg(i+1, Arg.get());
5352   }
5353 
5354   // Create a new DeclRefExpr to refer to the new decl.
5355   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5356       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5357       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5358       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5359 
5360   // Set the callee in the CallExpr.
5361   // FIXME: This loses syntactic information.
5362   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5363   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5364                                               CK_BuiltinFnToFnPtr);
5365   TheCall->setCallee(PromotedCall.get());
5366 
5367   // Change the result type of the call to match the original value type. This
5368   // is arbitrary, but the codegen for these builtins ins design to handle it
5369   // gracefully.
5370   TheCall->setType(ResultType);
5371 
5372   return TheCallResult;
5373 }
5374 
5375 /// SemaBuiltinNontemporalOverloaded - We have a call to
5376 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5377 /// overloaded function based on the pointer type of its last argument.
5378 ///
5379 /// This function goes through and does final semantic checking for these
5380 /// builtins.
5381 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5382   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5383   DeclRefExpr *DRE =
5384       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5385   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5386   unsigned BuiltinID = FDecl->getBuiltinID();
5387   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5388           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5389          "Unexpected nontemporal load/store builtin!");
5390   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5391   unsigned numArgs = isStore ? 2 : 1;
5392 
5393   // Ensure that we have the proper number of arguments.
5394   if (checkArgCount(*this, TheCall, numArgs))
5395     return ExprError();
5396 
5397   // Inspect the last argument of the nontemporal builtin.  This should always
5398   // be a pointer type, from which we imply the type of the memory access.
5399   // Because it is a pointer type, we don't have to worry about any implicit
5400   // casts here.
5401   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5402   ExprResult PointerArgResult =
5403       DefaultFunctionArrayLvalueConversion(PointerArg);
5404 
5405   if (PointerArgResult.isInvalid())
5406     return ExprError();
5407   PointerArg = PointerArgResult.get();
5408   TheCall->setArg(numArgs - 1, PointerArg);
5409 
5410   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5411   if (!pointerType) {
5412     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5413         << PointerArg->getType() << PointerArg->getSourceRange();
5414     return ExprError();
5415   }
5416 
5417   QualType ValType = pointerType->getPointeeType();
5418 
5419   // Strip any qualifiers off ValType.
5420   ValType = ValType.getUnqualifiedType();
5421   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5422       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5423       !ValType->isVectorType()) {
5424     Diag(DRE->getBeginLoc(),
5425          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5426         << PointerArg->getType() << PointerArg->getSourceRange();
5427     return ExprError();
5428   }
5429 
5430   if (!isStore) {
5431     TheCall->setType(ValType);
5432     return TheCallResult;
5433   }
5434 
5435   ExprResult ValArg = TheCall->getArg(0);
5436   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5437       Context, ValType, /*consume*/ false);
5438   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5439   if (ValArg.isInvalid())
5440     return ExprError();
5441 
5442   TheCall->setArg(0, ValArg.get());
5443   TheCall->setType(Context.VoidTy);
5444   return TheCallResult;
5445 }
5446 
5447 /// CheckObjCString - Checks that the argument to the builtin
5448 /// CFString constructor is correct
5449 /// Note: It might also make sense to do the UTF-16 conversion here (would
5450 /// simplify the backend).
5451 bool Sema::CheckObjCString(Expr *Arg) {
5452   Arg = Arg->IgnoreParenCasts();
5453   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5454 
5455   if (!Literal || !Literal->isAscii()) {
5456     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5457         << Arg->getSourceRange();
5458     return true;
5459   }
5460 
5461   if (Literal->containsNonAsciiOrNull()) {
5462     StringRef String = Literal->getString();
5463     unsigned NumBytes = String.size();
5464     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5465     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5466     llvm::UTF16 *ToPtr = &ToBuf[0];
5467 
5468     llvm::ConversionResult Result =
5469         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5470                                  ToPtr + NumBytes, llvm::strictConversion);
5471     // Check for conversion failure.
5472     if (Result != llvm::conversionOK)
5473       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5474           << Arg->getSourceRange();
5475   }
5476   return false;
5477 }
5478 
5479 /// CheckObjCString - Checks that the format string argument to the os_log()
5480 /// and os_trace() functions is correct, and converts it to const char *.
5481 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5482   Arg = Arg->IgnoreParenCasts();
5483   auto *Literal = dyn_cast<StringLiteral>(Arg);
5484   if (!Literal) {
5485     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5486       Literal = ObjcLiteral->getString();
5487     }
5488   }
5489 
5490   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5491     return ExprError(
5492         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5493         << Arg->getSourceRange());
5494   }
5495 
5496   ExprResult Result(Literal);
5497   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5498   InitializedEntity Entity =
5499       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5500   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5501   return Result;
5502 }
5503 
5504 /// Check that the user is calling the appropriate va_start builtin for the
5505 /// target and calling convention.
5506 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5507   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5508   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5509   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5510   bool IsWindows = TT.isOSWindows();
5511   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5512   if (IsX64 || IsAArch64) {
5513     CallingConv CC = CC_C;
5514     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5515       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5516     if (IsMSVAStart) {
5517       // Don't allow this in System V ABI functions.
5518       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5519         return S.Diag(Fn->getBeginLoc(),
5520                       diag::err_ms_va_start_used_in_sysv_function);
5521     } else {
5522       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5523       // On x64 Windows, don't allow this in System V ABI functions.
5524       // (Yes, that means there's no corresponding way to support variadic
5525       // System V ABI functions on Windows.)
5526       if ((IsWindows && CC == CC_X86_64SysV) ||
5527           (!IsWindows && CC == CC_Win64))
5528         return S.Diag(Fn->getBeginLoc(),
5529                       diag::err_va_start_used_in_wrong_abi_function)
5530                << !IsWindows;
5531     }
5532     return false;
5533   }
5534 
5535   if (IsMSVAStart)
5536     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5537   return false;
5538 }
5539 
5540 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5541                                              ParmVarDecl **LastParam = nullptr) {
5542   // Determine whether the current function, block, or obj-c method is variadic
5543   // and get its parameter list.
5544   bool IsVariadic = false;
5545   ArrayRef<ParmVarDecl *> Params;
5546   DeclContext *Caller = S.CurContext;
5547   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5548     IsVariadic = Block->isVariadic();
5549     Params = Block->parameters();
5550   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5551     IsVariadic = FD->isVariadic();
5552     Params = FD->parameters();
5553   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5554     IsVariadic = MD->isVariadic();
5555     // FIXME: This isn't correct for methods (results in bogus warning).
5556     Params = MD->parameters();
5557   } else if (isa<CapturedDecl>(Caller)) {
5558     // We don't support va_start in a CapturedDecl.
5559     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5560     return true;
5561   } else {
5562     // This must be some other declcontext that parses exprs.
5563     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5564     return true;
5565   }
5566 
5567   if (!IsVariadic) {
5568     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5569     return true;
5570   }
5571 
5572   if (LastParam)
5573     *LastParam = Params.empty() ? nullptr : Params.back();
5574 
5575   return false;
5576 }
5577 
5578 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5579 /// for validity.  Emit an error and return true on failure; return false
5580 /// on success.
5581 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5582   Expr *Fn = TheCall->getCallee();
5583 
5584   if (checkVAStartABI(*this, BuiltinID, Fn))
5585     return true;
5586 
5587   if (TheCall->getNumArgs() > 2) {
5588     Diag(TheCall->getArg(2)->getBeginLoc(),
5589          diag::err_typecheck_call_too_many_args)
5590         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5591         << Fn->getSourceRange()
5592         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5593                        (*(TheCall->arg_end() - 1))->getEndLoc());
5594     return true;
5595   }
5596 
5597   if (TheCall->getNumArgs() < 2) {
5598     return Diag(TheCall->getEndLoc(),
5599                 diag::err_typecheck_call_too_few_args_at_least)
5600            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5601   }
5602 
5603   // Type-check the first argument normally.
5604   if (checkBuiltinArgument(*this, TheCall, 0))
5605     return true;
5606 
5607   // Check that the current function is variadic, and get its last parameter.
5608   ParmVarDecl *LastParam;
5609   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5610     return true;
5611 
5612   // Verify that the second argument to the builtin is the last argument of the
5613   // current function or method.
5614   bool SecondArgIsLastNamedArgument = false;
5615   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5616 
5617   // These are valid if SecondArgIsLastNamedArgument is false after the next
5618   // block.
5619   QualType Type;
5620   SourceLocation ParamLoc;
5621   bool IsCRegister = false;
5622 
5623   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5624     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5625       SecondArgIsLastNamedArgument = PV == LastParam;
5626 
5627       Type = PV->getType();
5628       ParamLoc = PV->getLocation();
5629       IsCRegister =
5630           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5631     }
5632   }
5633 
5634   if (!SecondArgIsLastNamedArgument)
5635     Diag(TheCall->getArg(1)->getBeginLoc(),
5636          diag::warn_second_arg_of_va_start_not_last_named_param);
5637   else if (IsCRegister || Type->isReferenceType() ||
5638            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5639              // Promotable integers are UB, but enumerations need a bit of
5640              // extra checking to see what their promotable type actually is.
5641              if (!Type->isPromotableIntegerType())
5642                return false;
5643              if (!Type->isEnumeralType())
5644                return true;
5645              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5646              return !(ED &&
5647                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5648            }()) {
5649     unsigned Reason = 0;
5650     if (Type->isReferenceType())  Reason = 1;
5651     else if (IsCRegister)         Reason = 2;
5652     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5653     Diag(ParamLoc, diag::note_parameter_type) << Type;
5654   }
5655 
5656   TheCall->setType(Context.VoidTy);
5657   return false;
5658 }
5659 
5660 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5661   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5662   //                 const char *named_addr);
5663 
5664   Expr *Func = Call->getCallee();
5665 
5666   if (Call->getNumArgs() < 3)
5667     return Diag(Call->getEndLoc(),
5668                 diag::err_typecheck_call_too_few_args_at_least)
5669            << 0 /*function call*/ << 3 << Call->getNumArgs();
5670 
5671   // Type-check the first argument normally.
5672   if (checkBuiltinArgument(*this, Call, 0))
5673     return true;
5674 
5675   // Check that the current function is variadic.
5676   if (checkVAStartIsInVariadicFunction(*this, Func))
5677     return true;
5678 
5679   // __va_start on Windows does not validate the parameter qualifiers
5680 
5681   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5682   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5683 
5684   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5685   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5686 
5687   const QualType &ConstCharPtrTy =
5688       Context.getPointerType(Context.CharTy.withConst());
5689   if (!Arg1Ty->isPointerType() ||
5690       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5691     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5692         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5693         << 0                                      /* qualifier difference */
5694         << 3                                      /* parameter mismatch */
5695         << 2 << Arg1->getType() << ConstCharPtrTy;
5696 
5697   const QualType SizeTy = Context.getSizeType();
5698   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5699     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5700         << Arg2->getType() << SizeTy << 1 /* different class */
5701         << 0                              /* qualifier difference */
5702         << 3                              /* parameter mismatch */
5703         << 3 << Arg2->getType() << SizeTy;
5704 
5705   return false;
5706 }
5707 
5708 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5709 /// friends.  This is declared to take (...), so we have to check everything.
5710 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5711   if (TheCall->getNumArgs() < 2)
5712     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5713            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5714   if (TheCall->getNumArgs() > 2)
5715     return Diag(TheCall->getArg(2)->getBeginLoc(),
5716                 diag::err_typecheck_call_too_many_args)
5717            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5718            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5719                           (*(TheCall->arg_end() - 1))->getEndLoc());
5720 
5721   ExprResult OrigArg0 = TheCall->getArg(0);
5722   ExprResult OrigArg1 = TheCall->getArg(1);
5723 
5724   // Do standard promotions between the two arguments, returning their common
5725   // type.
5726   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5727   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5728     return true;
5729 
5730   // Make sure any conversions are pushed back into the call; this is
5731   // type safe since unordered compare builtins are declared as "_Bool
5732   // foo(...)".
5733   TheCall->setArg(0, OrigArg0.get());
5734   TheCall->setArg(1, OrigArg1.get());
5735 
5736   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5737     return false;
5738 
5739   // If the common type isn't a real floating type, then the arguments were
5740   // invalid for this operation.
5741   if (Res.isNull() || !Res->isRealFloatingType())
5742     return Diag(OrigArg0.get()->getBeginLoc(),
5743                 diag::err_typecheck_call_invalid_ordered_compare)
5744            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5745            << SourceRange(OrigArg0.get()->getBeginLoc(),
5746                           OrigArg1.get()->getEndLoc());
5747 
5748   return false;
5749 }
5750 
5751 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5752 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5753 /// to check everything. We expect the last argument to be a floating point
5754 /// value.
5755 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5756   if (TheCall->getNumArgs() < NumArgs)
5757     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5758            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5759   if (TheCall->getNumArgs() > NumArgs)
5760     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5761                 diag::err_typecheck_call_too_many_args)
5762            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5763            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5764                           (*(TheCall->arg_end() - 1))->getEndLoc());
5765 
5766   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5767 
5768   if (OrigArg->isTypeDependent())
5769     return false;
5770 
5771   // This operation requires a non-_Complex floating-point number.
5772   if (!OrigArg->getType()->isRealFloatingType())
5773     return Diag(OrigArg->getBeginLoc(),
5774                 diag::err_typecheck_call_invalid_unary_fp)
5775            << OrigArg->getType() << OrigArg->getSourceRange();
5776 
5777   // If this is an implicit conversion from float -> float, double, or
5778   // long double, remove it.
5779   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5780     // Only remove standard FloatCasts, leaving other casts inplace
5781     if (Cast->getCastKind() == CK_FloatingCast) {
5782       Expr *CastArg = Cast->getSubExpr();
5783       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5784         assert(
5785             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5786              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5787              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5788             "promotion from float to either float, double, or long double is "
5789             "the only expected cast here");
5790         Cast->setSubExpr(nullptr);
5791         TheCall->setArg(NumArgs-1, CastArg);
5792       }
5793     }
5794   }
5795 
5796   return false;
5797 }
5798 
5799 // Customized Sema Checking for VSX builtins that have the following signature:
5800 // vector [...] builtinName(vector [...], vector [...], const int);
5801 // Which takes the same type of vectors (any legal vector type) for the first
5802 // two arguments and takes compile time constant for the third argument.
5803 // Example builtins are :
5804 // vector double vec_xxpermdi(vector double, vector double, int);
5805 // vector short vec_xxsldwi(vector short, vector short, int);
5806 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5807   unsigned ExpectedNumArgs = 3;
5808   if (TheCall->getNumArgs() < ExpectedNumArgs)
5809     return Diag(TheCall->getEndLoc(),
5810                 diag::err_typecheck_call_too_few_args_at_least)
5811            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5812            << TheCall->getSourceRange();
5813 
5814   if (TheCall->getNumArgs() > ExpectedNumArgs)
5815     return Diag(TheCall->getEndLoc(),
5816                 diag::err_typecheck_call_too_many_args_at_most)
5817            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5818            << TheCall->getSourceRange();
5819 
5820   // Check the third argument is a compile time constant
5821   llvm::APSInt Value;
5822   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5823     return Diag(TheCall->getBeginLoc(),
5824                 diag::err_vsx_builtin_nonconstant_argument)
5825            << 3 /* argument index */ << TheCall->getDirectCallee()
5826            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5827                           TheCall->getArg(2)->getEndLoc());
5828 
5829   QualType Arg1Ty = TheCall->getArg(0)->getType();
5830   QualType Arg2Ty = TheCall->getArg(1)->getType();
5831 
5832   // Check the type of argument 1 and argument 2 are vectors.
5833   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5834   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5835       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5836     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5837            << TheCall->getDirectCallee()
5838            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5839                           TheCall->getArg(1)->getEndLoc());
5840   }
5841 
5842   // Check the first two arguments are the same type.
5843   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5844     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5845            << TheCall->getDirectCallee()
5846            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5847                           TheCall->getArg(1)->getEndLoc());
5848   }
5849 
5850   // When default clang type checking is turned off and the customized type
5851   // checking is used, the returning type of the function must be explicitly
5852   // set. Otherwise it is _Bool by default.
5853   TheCall->setType(Arg1Ty);
5854 
5855   return false;
5856 }
5857 
5858 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5859 // This is declared to take (...), so we have to check everything.
5860 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5861   if (TheCall->getNumArgs() < 2)
5862     return ExprError(Diag(TheCall->getEndLoc(),
5863                           diag::err_typecheck_call_too_few_args_at_least)
5864                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5865                      << TheCall->getSourceRange());
5866 
5867   // Determine which of the following types of shufflevector we're checking:
5868   // 1) unary, vector mask: (lhs, mask)
5869   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5870   QualType resType = TheCall->getArg(0)->getType();
5871   unsigned numElements = 0;
5872 
5873   if (!TheCall->getArg(0)->isTypeDependent() &&
5874       !TheCall->getArg(1)->isTypeDependent()) {
5875     QualType LHSType = TheCall->getArg(0)->getType();
5876     QualType RHSType = TheCall->getArg(1)->getType();
5877 
5878     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5879       return ExprError(
5880           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5881           << TheCall->getDirectCallee()
5882           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5883                          TheCall->getArg(1)->getEndLoc()));
5884 
5885     numElements = LHSType->castAs<VectorType>()->getNumElements();
5886     unsigned numResElements = TheCall->getNumArgs() - 2;
5887 
5888     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5889     // with mask.  If so, verify that RHS is an integer vector type with the
5890     // same number of elts as lhs.
5891     if (TheCall->getNumArgs() == 2) {
5892       if (!RHSType->hasIntegerRepresentation() ||
5893           RHSType->castAs<VectorType>()->getNumElements() != numElements)
5894         return ExprError(Diag(TheCall->getBeginLoc(),
5895                               diag::err_vec_builtin_incompatible_vector)
5896                          << TheCall->getDirectCallee()
5897                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5898                                         TheCall->getArg(1)->getEndLoc()));
5899     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5900       return ExprError(Diag(TheCall->getBeginLoc(),
5901                             diag::err_vec_builtin_incompatible_vector)
5902                        << TheCall->getDirectCallee()
5903                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5904                                       TheCall->getArg(1)->getEndLoc()));
5905     } else if (numElements != numResElements) {
5906       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
5907       resType = Context.getVectorType(eltType, numResElements,
5908                                       VectorType::GenericVector);
5909     }
5910   }
5911 
5912   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5913     if (TheCall->getArg(i)->isTypeDependent() ||
5914         TheCall->getArg(i)->isValueDependent())
5915       continue;
5916 
5917     llvm::APSInt Result(32);
5918     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5919       return ExprError(Diag(TheCall->getBeginLoc(),
5920                             diag::err_shufflevector_nonconstant_argument)
5921                        << TheCall->getArg(i)->getSourceRange());
5922 
5923     // Allow -1 which will be translated to undef in the IR.
5924     if (Result.isSigned() && Result.isAllOnesValue())
5925       continue;
5926 
5927     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5928       return ExprError(Diag(TheCall->getBeginLoc(),
5929                             diag::err_shufflevector_argument_too_large)
5930                        << TheCall->getArg(i)->getSourceRange());
5931   }
5932 
5933   SmallVector<Expr*, 32> exprs;
5934 
5935   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5936     exprs.push_back(TheCall->getArg(i));
5937     TheCall->setArg(i, nullptr);
5938   }
5939 
5940   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5941                                          TheCall->getCallee()->getBeginLoc(),
5942                                          TheCall->getRParenLoc());
5943 }
5944 
5945 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5946 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5947                                        SourceLocation BuiltinLoc,
5948                                        SourceLocation RParenLoc) {
5949   ExprValueKind VK = VK_RValue;
5950   ExprObjectKind OK = OK_Ordinary;
5951   QualType DstTy = TInfo->getType();
5952   QualType SrcTy = E->getType();
5953 
5954   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5955     return ExprError(Diag(BuiltinLoc,
5956                           diag::err_convertvector_non_vector)
5957                      << E->getSourceRange());
5958   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5959     return ExprError(Diag(BuiltinLoc,
5960                           diag::err_convertvector_non_vector_type));
5961 
5962   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5963     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5964     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5965     if (SrcElts != DstElts)
5966       return ExprError(Diag(BuiltinLoc,
5967                             diag::err_convertvector_incompatible_vector)
5968                        << E->getSourceRange());
5969   }
5970 
5971   return new (Context)
5972       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5973 }
5974 
5975 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5976 // This is declared to take (const void*, ...) and can take two
5977 // optional constant int args.
5978 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5979   unsigned NumArgs = TheCall->getNumArgs();
5980 
5981   if (NumArgs > 3)
5982     return Diag(TheCall->getEndLoc(),
5983                 diag::err_typecheck_call_too_many_args_at_most)
5984            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5985 
5986   // Argument 0 is checked for us and the remaining arguments must be
5987   // constant integers.
5988   for (unsigned i = 1; i != NumArgs; ++i)
5989     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5990       return true;
5991 
5992   return false;
5993 }
5994 
5995 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5996 // __assume does not evaluate its arguments, and should warn if its argument
5997 // has side effects.
5998 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5999   Expr *Arg = TheCall->getArg(0);
6000   if (Arg->isInstantiationDependent()) return false;
6001 
6002   if (Arg->HasSideEffects(Context))
6003     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6004         << Arg->getSourceRange()
6005         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6006 
6007   return false;
6008 }
6009 
6010 /// Handle __builtin_alloca_with_align. This is declared
6011 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6012 /// than 8.
6013 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6014   // The alignment must be a constant integer.
6015   Expr *Arg = TheCall->getArg(1);
6016 
6017   // We can't check the value of a dependent argument.
6018   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6019     if (const auto *UE =
6020             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6021       if (UE->getKind() == UETT_AlignOf ||
6022           UE->getKind() == UETT_PreferredAlignOf)
6023         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6024             << Arg->getSourceRange();
6025 
6026     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6027 
6028     if (!Result.isPowerOf2())
6029       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6030              << Arg->getSourceRange();
6031 
6032     if (Result < Context.getCharWidth())
6033       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6034              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6035 
6036     if (Result > std::numeric_limits<int32_t>::max())
6037       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6038              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6039   }
6040 
6041   return false;
6042 }
6043 
6044 /// Handle __builtin_assume_aligned. This is declared
6045 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6046 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6047   unsigned NumArgs = TheCall->getNumArgs();
6048 
6049   if (NumArgs > 3)
6050     return Diag(TheCall->getEndLoc(),
6051                 diag::err_typecheck_call_too_many_args_at_most)
6052            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6053 
6054   // The alignment must be a constant integer.
6055   Expr *Arg = TheCall->getArg(1);
6056 
6057   // We can't check the value of a dependent argument.
6058   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6059     llvm::APSInt Result;
6060     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6061       return true;
6062 
6063     if (!Result.isPowerOf2())
6064       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6065              << Arg->getSourceRange();
6066 
6067     // Alignment calculations can wrap around if it's greater than 2**29.
6068     unsigned MaximumAlignment = 536870912;
6069     if (Result > MaximumAlignment)
6070       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6071           << Arg->getSourceRange() << MaximumAlignment;
6072   }
6073 
6074   if (NumArgs > 2) {
6075     ExprResult Arg(TheCall->getArg(2));
6076     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6077       Context.getSizeType(), false);
6078     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6079     if (Arg.isInvalid()) return true;
6080     TheCall->setArg(2, Arg.get());
6081   }
6082 
6083   return false;
6084 }
6085 
6086 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6087   unsigned BuiltinID =
6088       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6089   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6090 
6091   unsigned NumArgs = TheCall->getNumArgs();
6092   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6093   if (NumArgs < NumRequiredArgs) {
6094     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6095            << 0 /* function call */ << NumRequiredArgs << NumArgs
6096            << TheCall->getSourceRange();
6097   }
6098   if (NumArgs >= NumRequiredArgs + 0x100) {
6099     return Diag(TheCall->getEndLoc(),
6100                 diag::err_typecheck_call_too_many_args_at_most)
6101            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6102            << TheCall->getSourceRange();
6103   }
6104   unsigned i = 0;
6105 
6106   // For formatting call, check buffer arg.
6107   if (!IsSizeCall) {
6108     ExprResult Arg(TheCall->getArg(i));
6109     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6110         Context, Context.VoidPtrTy, false);
6111     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6112     if (Arg.isInvalid())
6113       return true;
6114     TheCall->setArg(i, Arg.get());
6115     i++;
6116   }
6117 
6118   // Check string literal arg.
6119   unsigned FormatIdx = i;
6120   {
6121     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6122     if (Arg.isInvalid())
6123       return true;
6124     TheCall->setArg(i, Arg.get());
6125     i++;
6126   }
6127 
6128   // Make sure variadic args are scalar.
6129   unsigned FirstDataArg = i;
6130   while (i < NumArgs) {
6131     ExprResult Arg = DefaultVariadicArgumentPromotion(
6132         TheCall->getArg(i), VariadicFunction, nullptr);
6133     if (Arg.isInvalid())
6134       return true;
6135     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6136     if (ArgSize.getQuantity() >= 0x100) {
6137       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6138              << i << (int)ArgSize.getQuantity() << 0xff
6139              << TheCall->getSourceRange();
6140     }
6141     TheCall->setArg(i, Arg.get());
6142     i++;
6143   }
6144 
6145   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6146   // call to avoid duplicate diagnostics.
6147   if (!IsSizeCall) {
6148     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6149     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6150     bool Success = CheckFormatArguments(
6151         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6152         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6153         CheckedVarArgs);
6154     if (!Success)
6155       return true;
6156   }
6157 
6158   if (IsSizeCall) {
6159     TheCall->setType(Context.getSizeType());
6160   } else {
6161     TheCall->setType(Context.VoidPtrTy);
6162   }
6163   return false;
6164 }
6165 
6166 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6167 /// TheCall is a constant expression.
6168 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6169                                   llvm::APSInt &Result) {
6170   Expr *Arg = TheCall->getArg(ArgNum);
6171   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6172   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6173 
6174   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6175 
6176   if (!Arg->isIntegerConstantExpr(Result, Context))
6177     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6178            << FDecl->getDeclName() << Arg->getSourceRange();
6179 
6180   return false;
6181 }
6182 
6183 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6184 /// TheCall is a constant expression in the range [Low, High].
6185 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6186                                        int Low, int High, bool RangeIsError) {
6187   if (isConstantEvaluated())
6188     return false;
6189   llvm::APSInt Result;
6190 
6191   // We can't check the value of a dependent argument.
6192   Expr *Arg = TheCall->getArg(ArgNum);
6193   if (Arg->isTypeDependent() || Arg->isValueDependent())
6194     return false;
6195 
6196   // Check constant-ness first.
6197   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6198     return true;
6199 
6200   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6201     if (RangeIsError)
6202       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6203              << Result.toString(10) << Low << High << Arg->getSourceRange();
6204     else
6205       // Defer the warning until we know if the code will be emitted so that
6206       // dead code can ignore this.
6207       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6208                           PDiag(diag::warn_argument_invalid_range)
6209                               << Result.toString(10) << Low << High
6210                               << Arg->getSourceRange());
6211   }
6212 
6213   return false;
6214 }
6215 
6216 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6217 /// TheCall is a constant expression is a multiple of Num..
6218 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6219                                           unsigned Num) {
6220   llvm::APSInt Result;
6221 
6222   // We can't check the value of a dependent argument.
6223   Expr *Arg = TheCall->getArg(ArgNum);
6224   if (Arg->isTypeDependent() || Arg->isValueDependent())
6225     return false;
6226 
6227   // Check constant-ness first.
6228   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6229     return true;
6230 
6231   if (Result.getSExtValue() % Num != 0)
6232     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6233            << Num << Arg->getSourceRange();
6234 
6235   return false;
6236 }
6237 
6238 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6239 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6240   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6241     if (checkArgCount(*this, TheCall, 2))
6242       return true;
6243     Expr *Arg0 = TheCall->getArg(0);
6244     Expr *Arg1 = TheCall->getArg(1);
6245 
6246     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6247     if (FirstArg.isInvalid())
6248       return true;
6249     QualType FirstArgType = FirstArg.get()->getType();
6250     if (!FirstArgType->isAnyPointerType())
6251       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6252                << "first" << FirstArgType << Arg0->getSourceRange();
6253     TheCall->setArg(0, FirstArg.get());
6254 
6255     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6256     if (SecArg.isInvalid())
6257       return true;
6258     QualType SecArgType = SecArg.get()->getType();
6259     if (!SecArgType->isIntegerType())
6260       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6261                << "second" << SecArgType << Arg1->getSourceRange();
6262 
6263     // Derive the return type from the pointer argument.
6264     TheCall->setType(FirstArgType);
6265     return false;
6266   }
6267 
6268   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6269     if (checkArgCount(*this, TheCall, 2))
6270       return true;
6271 
6272     Expr *Arg0 = TheCall->getArg(0);
6273     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6274     if (FirstArg.isInvalid())
6275       return true;
6276     QualType FirstArgType = FirstArg.get()->getType();
6277     if (!FirstArgType->isAnyPointerType())
6278       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6279                << "first" << FirstArgType << Arg0->getSourceRange();
6280     TheCall->setArg(0, FirstArg.get());
6281 
6282     // Derive the return type from the pointer argument.
6283     TheCall->setType(FirstArgType);
6284 
6285     // Second arg must be an constant in range [0,15]
6286     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6287   }
6288 
6289   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6290     if (checkArgCount(*this, TheCall, 2))
6291       return true;
6292     Expr *Arg0 = TheCall->getArg(0);
6293     Expr *Arg1 = TheCall->getArg(1);
6294 
6295     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6296     if (FirstArg.isInvalid())
6297       return true;
6298     QualType FirstArgType = FirstArg.get()->getType();
6299     if (!FirstArgType->isAnyPointerType())
6300       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6301                << "first" << FirstArgType << Arg0->getSourceRange();
6302 
6303     QualType SecArgType = Arg1->getType();
6304     if (!SecArgType->isIntegerType())
6305       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6306                << "second" << SecArgType << Arg1->getSourceRange();
6307     TheCall->setType(Context.IntTy);
6308     return false;
6309   }
6310 
6311   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6312       BuiltinID == AArch64::BI__builtin_arm_stg) {
6313     if (checkArgCount(*this, TheCall, 1))
6314       return true;
6315     Expr *Arg0 = TheCall->getArg(0);
6316     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6317     if (FirstArg.isInvalid())
6318       return true;
6319 
6320     QualType FirstArgType = FirstArg.get()->getType();
6321     if (!FirstArgType->isAnyPointerType())
6322       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6323                << "first" << FirstArgType << Arg0->getSourceRange();
6324     TheCall->setArg(0, FirstArg.get());
6325 
6326     // Derive the return type from the pointer argument.
6327     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6328       TheCall->setType(FirstArgType);
6329     return false;
6330   }
6331 
6332   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6333     Expr *ArgA = TheCall->getArg(0);
6334     Expr *ArgB = TheCall->getArg(1);
6335 
6336     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6337     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6338 
6339     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6340       return true;
6341 
6342     QualType ArgTypeA = ArgExprA.get()->getType();
6343     QualType ArgTypeB = ArgExprB.get()->getType();
6344 
6345     auto isNull = [&] (Expr *E) -> bool {
6346       return E->isNullPointerConstant(
6347                         Context, Expr::NPC_ValueDependentIsNotNull); };
6348 
6349     // argument should be either a pointer or null
6350     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6351       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6352         << "first" << ArgTypeA << ArgA->getSourceRange();
6353 
6354     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6355       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6356         << "second" << ArgTypeB << ArgB->getSourceRange();
6357 
6358     // Ensure Pointee types are compatible
6359     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6360         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6361       QualType pointeeA = ArgTypeA->getPointeeType();
6362       QualType pointeeB = ArgTypeB->getPointeeType();
6363       if (!Context.typesAreCompatible(
6364              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6365              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6366         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6367           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6368           << ArgB->getSourceRange();
6369       }
6370     }
6371 
6372     // at least one argument should be pointer type
6373     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6374       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6375         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6376 
6377     if (isNull(ArgA)) // adopt type of the other pointer
6378       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6379 
6380     if (isNull(ArgB))
6381       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6382 
6383     TheCall->setArg(0, ArgExprA.get());
6384     TheCall->setArg(1, ArgExprB.get());
6385     TheCall->setType(Context.LongLongTy);
6386     return false;
6387   }
6388   assert(false && "Unhandled ARM MTE intrinsic");
6389   return true;
6390 }
6391 
6392 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6393 /// TheCall is an ARM/AArch64 special register string literal.
6394 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6395                                     int ArgNum, unsigned ExpectedFieldNum,
6396                                     bool AllowName) {
6397   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6398                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6399                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6400                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6401                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6402                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6403   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6404                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6405                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6406                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6407                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6408                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6409   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6410 
6411   // We can't check the value of a dependent argument.
6412   Expr *Arg = TheCall->getArg(ArgNum);
6413   if (Arg->isTypeDependent() || Arg->isValueDependent())
6414     return false;
6415 
6416   // Check if the argument is a string literal.
6417   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6418     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6419            << Arg->getSourceRange();
6420 
6421   // Check the type of special register given.
6422   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6423   SmallVector<StringRef, 6> Fields;
6424   Reg.split(Fields, ":");
6425 
6426   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6427     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6428            << Arg->getSourceRange();
6429 
6430   // If the string is the name of a register then we cannot check that it is
6431   // valid here but if the string is of one the forms described in ACLE then we
6432   // can check that the supplied fields are integers and within the valid
6433   // ranges.
6434   if (Fields.size() > 1) {
6435     bool FiveFields = Fields.size() == 5;
6436 
6437     bool ValidString = true;
6438     if (IsARMBuiltin) {
6439       ValidString &= Fields[0].startswith_lower("cp") ||
6440                      Fields[0].startswith_lower("p");
6441       if (ValidString)
6442         Fields[0] =
6443           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6444 
6445       ValidString &= Fields[2].startswith_lower("c");
6446       if (ValidString)
6447         Fields[2] = Fields[2].drop_front(1);
6448 
6449       if (FiveFields) {
6450         ValidString &= Fields[3].startswith_lower("c");
6451         if (ValidString)
6452           Fields[3] = Fields[3].drop_front(1);
6453       }
6454     }
6455 
6456     SmallVector<int, 5> Ranges;
6457     if (FiveFields)
6458       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6459     else
6460       Ranges.append({15, 7, 15});
6461 
6462     for (unsigned i=0; i<Fields.size(); ++i) {
6463       int IntField;
6464       ValidString &= !Fields[i].getAsInteger(10, IntField);
6465       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6466     }
6467 
6468     if (!ValidString)
6469       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6470              << Arg->getSourceRange();
6471   } else if (IsAArch64Builtin && Fields.size() == 1) {
6472     // If the register name is one of those that appear in the condition below
6473     // and the special register builtin being used is one of the write builtins,
6474     // then we require that the argument provided for writing to the register
6475     // is an integer constant expression. This is because it will be lowered to
6476     // an MSR (immediate) instruction, so we need to know the immediate at
6477     // compile time.
6478     if (TheCall->getNumArgs() != 2)
6479       return false;
6480 
6481     std::string RegLower = Reg.lower();
6482     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6483         RegLower != "pan" && RegLower != "uao")
6484       return false;
6485 
6486     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6487   }
6488 
6489   return false;
6490 }
6491 
6492 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6493 /// This checks that the target supports __builtin_longjmp and
6494 /// that val is a constant 1.
6495 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6496   if (!Context.getTargetInfo().hasSjLjLowering())
6497     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6498            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6499 
6500   Expr *Arg = TheCall->getArg(1);
6501   llvm::APSInt Result;
6502 
6503   // TODO: This is less than ideal. Overload this to take a value.
6504   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6505     return true;
6506 
6507   if (Result != 1)
6508     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6509            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6510 
6511   return false;
6512 }
6513 
6514 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6515 /// This checks that the target supports __builtin_setjmp.
6516 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6517   if (!Context.getTargetInfo().hasSjLjLowering())
6518     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6519            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6520   return false;
6521 }
6522 
6523 namespace {
6524 
6525 class UncoveredArgHandler {
6526   enum { Unknown = -1, AllCovered = -2 };
6527 
6528   signed FirstUncoveredArg = Unknown;
6529   SmallVector<const Expr *, 4> DiagnosticExprs;
6530 
6531 public:
6532   UncoveredArgHandler() = default;
6533 
6534   bool hasUncoveredArg() const {
6535     return (FirstUncoveredArg >= 0);
6536   }
6537 
6538   unsigned getUncoveredArg() const {
6539     assert(hasUncoveredArg() && "no uncovered argument");
6540     return FirstUncoveredArg;
6541   }
6542 
6543   void setAllCovered() {
6544     // A string has been found with all arguments covered, so clear out
6545     // the diagnostics.
6546     DiagnosticExprs.clear();
6547     FirstUncoveredArg = AllCovered;
6548   }
6549 
6550   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6551     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6552 
6553     // Don't update if a previous string covers all arguments.
6554     if (FirstUncoveredArg == AllCovered)
6555       return;
6556 
6557     // UncoveredArgHandler tracks the highest uncovered argument index
6558     // and with it all the strings that match this index.
6559     if (NewFirstUncoveredArg == FirstUncoveredArg)
6560       DiagnosticExprs.push_back(StrExpr);
6561     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6562       DiagnosticExprs.clear();
6563       DiagnosticExprs.push_back(StrExpr);
6564       FirstUncoveredArg = NewFirstUncoveredArg;
6565     }
6566   }
6567 
6568   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6569 };
6570 
6571 enum StringLiteralCheckType {
6572   SLCT_NotALiteral,
6573   SLCT_UncheckedLiteral,
6574   SLCT_CheckedLiteral
6575 };
6576 
6577 } // namespace
6578 
6579 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6580                                      BinaryOperatorKind BinOpKind,
6581                                      bool AddendIsRight) {
6582   unsigned BitWidth = Offset.getBitWidth();
6583   unsigned AddendBitWidth = Addend.getBitWidth();
6584   // There might be negative interim results.
6585   if (Addend.isUnsigned()) {
6586     Addend = Addend.zext(++AddendBitWidth);
6587     Addend.setIsSigned(true);
6588   }
6589   // Adjust the bit width of the APSInts.
6590   if (AddendBitWidth > BitWidth) {
6591     Offset = Offset.sext(AddendBitWidth);
6592     BitWidth = AddendBitWidth;
6593   } else if (BitWidth > AddendBitWidth) {
6594     Addend = Addend.sext(BitWidth);
6595   }
6596 
6597   bool Ov = false;
6598   llvm::APSInt ResOffset = Offset;
6599   if (BinOpKind == BO_Add)
6600     ResOffset = Offset.sadd_ov(Addend, Ov);
6601   else {
6602     assert(AddendIsRight && BinOpKind == BO_Sub &&
6603            "operator must be add or sub with addend on the right");
6604     ResOffset = Offset.ssub_ov(Addend, Ov);
6605   }
6606 
6607   // We add an offset to a pointer here so we should support an offset as big as
6608   // possible.
6609   if (Ov) {
6610     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6611            "index (intermediate) result too big");
6612     Offset = Offset.sext(2 * BitWidth);
6613     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6614     return;
6615   }
6616 
6617   Offset = ResOffset;
6618 }
6619 
6620 namespace {
6621 
6622 // This is a wrapper class around StringLiteral to support offsetted string
6623 // literals as format strings. It takes the offset into account when returning
6624 // the string and its length or the source locations to display notes correctly.
6625 class FormatStringLiteral {
6626   const StringLiteral *FExpr;
6627   int64_t Offset;
6628 
6629  public:
6630   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6631       : FExpr(fexpr), Offset(Offset) {}
6632 
6633   StringRef getString() const {
6634     return FExpr->getString().drop_front(Offset);
6635   }
6636 
6637   unsigned getByteLength() const {
6638     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6639   }
6640 
6641   unsigned getLength() const { return FExpr->getLength() - Offset; }
6642   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6643 
6644   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6645 
6646   QualType getType() const { return FExpr->getType(); }
6647 
6648   bool isAscii() const { return FExpr->isAscii(); }
6649   bool isWide() const { return FExpr->isWide(); }
6650   bool isUTF8() const { return FExpr->isUTF8(); }
6651   bool isUTF16() const { return FExpr->isUTF16(); }
6652   bool isUTF32() const { return FExpr->isUTF32(); }
6653   bool isPascal() const { return FExpr->isPascal(); }
6654 
6655   SourceLocation getLocationOfByte(
6656       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6657       const TargetInfo &Target, unsigned *StartToken = nullptr,
6658       unsigned *StartTokenByteOffset = nullptr) const {
6659     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6660                                     StartToken, StartTokenByteOffset);
6661   }
6662 
6663   SourceLocation getBeginLoc() const LLVM_READONLY {
6664     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6665   }
6666 
6667   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6668 };
6669 
6670 }  // namespace
6671 
6672 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6673                               const Expr *OrigFormatExpr,
6674                               ArrayRef<const Expr *> Args,
6675                               bool HasVAListArg, unsigned format_idx,
6676                               unsigned firstDataArg,
6677                               Sema::FormatStringType Type,
6678                               bool inFunctionCall,
6679                               Sema::VariadicCallType CallType,
6680                               llvm::SmallBitVector &CheckedVarArgs,
6681                               UncoveredArgHandler &UncoveredArg,
6682                               bool IgnoreStringsWithoutSpecifiers);
6683 
6684 // Determine if an expression is a string literal or constant string.
6685 // If this function returns false on the arguments to a function expecting a
6686 // format string, we will usually need to emit a warning.
6687 // True string literals are then checked by CheckFormatString.
6688 static StringLiteralCheckType
6689 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6690                       bool HasVAListArg, unsigned format_idx,
6691                       unsigned firstDataArg, Sema::FormatStringType Type,
6692                       Sema::VariadicCallType CallType, bool InFunctionCall,
6693                       llvm::SmallBitVector &CheckedVarArgs,
6694                       UncoveredArgHandler &UncoveredArg,
6695                       llvm::APSInt Offset,
6696                       bool IgnoreStringsWithoutSpecifiers = false) {
6697   if (S.isConstantEvaluated())
6698     return SLCT_NotALiteral;
6699  tryAgain:
6700   assert(Offset.isSigned() && "invalid offset");
6701 
6702   if (E->isTypeDependent() || E->isValueDependent())
6703     return SLCT_NotALiteral;
6704 
6705   E = E->IgnoreParenCasts();
6706 
6707   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6708     // Technically -Wformat-nonliteral does not warn about this case.
6709     // The behavior of printf and friends in this case is implementation
6710     // dependent.  Ideally if the format string cannot be null then
6711     // it should have a 'nonnull' attribute in the function prototype.
6712     return SLCT_UncheckedLiteral;
6713 
6714   switch (E->getStmtClass()) {
6715   case Stmt::BinaryConditionalOperatorClass:
6716   case Stmt::ConditionalOperatorClass: {
6717     // The expression is a literal if both sub-expressions were, and it was
6718     // completely checked only if both sub-expressions were checked.
6719     const AbstractConditionalOperator *C =
6720         cast<AbstractConditionalOperator>(E);
6721 
6722     // Determine whether it is necessary to check both sub-expressions, for
6723     // example, because the condition expression is a constant that can be
6724     // evaluated at compile time.
6725     bool CheckLeft = true, CheckRight = true;
6726 
6727     bool Cond;
6728     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
6729                                                  S.isConstantEvaluated())) {
6730       if (Cond)
6731         CheckRight = false;
6732       else
6733         CheckLeft = false;
6734     }
6735 
6736     // We need to maintain the offsets for the right and the left hand side
6737     // separately to check if every possible indexed expression is a valid
6738     // string literal. They might have different offsets for different string
6739     // literals in the end.
6740     StringLiteralCheckType Left;
6741     if (!CheckLeft)
6742       Left = SLCT_UncheckedLiteral;
6743     else {
6744       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6745                                    HasVAListArg, format_idx, firstDataArg,
6746                                    Type, CallType, InFunctionCall,
6747                                    CheckedVarArgs, UncoveredArg, Offset,
6748                                    IgnoreStringsWithoutSpecifiers);
6749       if (Left == SLCT_NotALiteral || !CheckRight) {
6750         return Left;
6751       }
6752     }
6753 
6754     StringLiteralCheckType Right = checkFormatStringExpr(
6755         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
6756         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6757         IgnoreStringsWithoutSpecifiers);
6758 
6759     return (CheckLeft && Left < Right) ? Left : Right;
6760   }
6761 
6762   case Stmt::ImplicitCastExprClass:
6763     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6764     goto tryAgain;
6765 
6766   case Stmt::OpaqueValueExprClass:
6767     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6768       E = src;
6769       goto tryAgain;
6770     }
6771     return SLCT_NotALiteral;
6772 
6773   case Stmt::PredefinedExprClass:
6774     // While __func__, etc., are technically not string literals, they
6775     // cannot contain format specifiers and thus are not a security
6776     // liability.
6777     return SLCT_UncheckedLiteral;
6778 
6779   case Stmt::DeclRefExprClass: {
6780     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6781 
6782     // As an exception, do not flag errors for variables binding to
6783     // const string literals.
6784     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6785       bool isConstant = false;
6786       QualType T = DR->getType();
6787 
6788       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6789         isConstant = AT->getElementType().isConstant(S.Context);
6790       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6791         isConstant = T.isConstant(S.Context) &&
6792                      PT->getPointeeType().isConstant(S.Context);
6793       } else if (T->isObjCObjectPointerType()) {
6794         // In ObjC, there is usually no "const ObjectPointer" type,
6795         // so don't check if the pointee type is constant.
6796         isConstant = T.isConstant(S.Context);
6797       }
6798 
6799       if (isConstant) {
6800         if (const Expr *Init = VD->getAnyInitializer()) {
6801           // Look through initializers like const char c[] = { "foo" }
6802           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6803             if (InitList->isStringLiteralInit())
6804               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6805           }
6806           return checkFormatStringExpr(S, Init, Args,
6807                                        HasVAListArg, format_idx,
6808                                        firstDataArg, Type, CallType,
6809                                        /*InFunctionCall*/ false, CheckedVarArgs,
6810                                        UncoveredArg, Offset);
6811         }
6812       }
6813 
6814       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6815       // special check to see if the format string is a function parameter
6816       // of the function calling the printf function.  If the function
6817       // has an attribute indicating it is a printf-like function, then we
6818       // should suppress warnings concerning non-literals being used in a call
6819       // to a vprintf function.  For example:
6820       //
6821       // void
6822       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6823       //      va_list ap;
6824       //      va_start(ap, fmt);
6825       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6826       //      ...
6827       // }
6828       if (HasVAListArg) {
6829         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6830           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6831             int PVIndex = PV->getFunctionScopeIndex() + 1;
6832             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6833               // adjust for implicit parameter
6834               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6835                 if (MD->isInstance())
6836                   ++PVIndex;
6837               // We also check if the formats are compatible.
6838               // We can't pass a 'scanf' string to a 'printf' function.
6839               if (PVIndex == PVFormat->getFormatIdx() &&
6840                   Type == S.GetFormatStringType(PVFormat))
6841                 return SLCT_UncheckedLiteral;
6842             }
6843           }
6844         }
6845       }
6846     }
6847 
6848     return SLCT_NotALiteral;
6849   }
6850 
6851   case Stmt::CallExprClass:
6852   case Stmt::CXXMemberCallExprClass: {
6853     const CallExpr *CE = cast<CallExpr>(E);
6854     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6855       bool IsFirst = true;
6856       StringLiteralCheckType CommonResult;
6857       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6858         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6859         StringLiteralCheckType Result = checkFormatStringExpr(
6860             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6861             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6862             IgnoreStringsWithoutSpecifiers);
6863         if (IsFirst) {
6864           CommonResult = Result;
6865           IsFirst = false;
6866         }
6867       }
6868       if (!IsFirst)
6869         return CommonResult;
6870 
6871       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6872         unsigned BuiltinID = FD->getBuiltinID();
6873         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6874             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6875           const Expr *Arg = CE->getArg(0);
6876           return checkFormatStringExpr(S, Arg, Args,
6877                                        HasVAListArg, format_idx,
6878                                        firstDataArg, Type, CallType,
6879                                        InFunctionCall, CheckedVarArgs,
6880                                        UncoveredArg, Offset,
6881                                        IgnoreStringsWithoutSpecifiers);
6882         }
6883       }
6884     }
6885 
6886     return SLCT_NotALiteral;
6887   }
6888   case Stmt::ObjCMessageExprClass: {
6889     const auto *ME = cast<ObjCMessageExpr>(E);
6890     if (const auto *MD = ME->getMethodDecl()) {
6891       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6892         // As a special case heuristic, if we're using the method -[NSBundle
6893         // localizedStringForKey:value:table:], ignore any key strings that lack
6894         // format specifiers. The idea is that if the key doesn't have any
6895         // format specifiers then its probably just a key to map to the
6896         // localized strings. If it does have format specifiers though, then its
6897         // likely that the text of the key is the format string in the
6898         // programmer's language, and should be checked.
6899         const ObjCInterfaceDecl *IFace;
6900         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6901             IFace->getIdentifier()->isStr("NSBundle") &&
6902             MD->getSelector().isKeywordSelector(
6903                 {"localizedStringForKey", "value", "table"})) {
6904           IgnoreStringsWithoutSpecifiers = true;
6905         }
6906 
6907         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6908         return checkFormatStringExpr(
6909             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6910             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
6911             IgnoreStringsWithoutSpecifiers);
6912       }
6913     }
6914 
6915     return SLCT_NotALiteral;
6916   }
6917   case Stmt::ObjCStringLiteralClass:
6918   case Stmt::StringLiteralClass: {
6919     const StringLiteral *StrE = nullptr;
6920 
6921     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6922       StrE = ObjCFExpr->getString();
6923     else
6924       StrE = cast<StringLiteral>(E);
6925 
6926     if (StrE) {
6927       if (Offset.isNegative() || Offset > StrE->getLength()) {
6928         // TODO: It would be better to have an explicit warning for out of
6929         // bounds literals.
6930         return SLCT_NotALiteral;
6931       }
6932       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6933       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6934                         firstDataArg, Type, InFunctionCall, CallType,
6935                         CheckedVarArgs, UncoveredArg,
6936                         IgnoreStringsWithoutSpecifiers);
6937       return SLCT_CheckedLiteral;
6938     }
6939 
6940     return SLCT_NotALiteral;
6941   }
6942   case Stmt::BinaryOperatorClass: {
6943     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6944 
6945     // A string literal + an int offset is still a string literal.
6946     if (BinOp->isAdditiveOp()) {
6947       Expr::EvalResult LResult, RResult;
6948 
6949       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6950           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6951       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6952           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
6953 
6954       if (LIsInt != RIsInt) {
6955         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6956 
6957         if (LIsInt) {
6958           if (BinOpKind == BO_Add) {
6959             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6960             E = BinOp->getRHS();
6961             goto tryAgain;
6962           }
6963         } else {
6964           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6965           E = BinOp->getLHS();
6966           goto tryAgain;
6967         }
6968       }
6969     }
6970 
6971     return SLCT_NotALiteral;
6972   }
6973   case Stmt::UnaryOperatorClass: {
6974     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6975     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6976     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6977       Expr::EvalResult IndexResult;
6978       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6979                                        Expr::SE_NoSideEffects,
6980                                        S.isConstantEvaluated())) {
6981         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6982                    /*RHS is int*/ true);
6983         E = ASE->getBase();
6984         goto tryAgain;
6985       }
6986     }
6987 
6988     return SLCT_NotALiteral;
6989   }
6990 
6991   default:
6992     return SLCT_NotALiteral;
6993   }
6994 }
6995 
6996 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6997   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6998       .Case("scanf", FST_Scanf)
6999       .Cases("printf", "printf0", FST_Printf)
7000       .Cases("NSString", "CFString", FST_NSString)
7001       .Case("strftime", FST_Strftime)
7002       .Case("strfmon", FST_Strfmon)
7003       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7004       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7005       .Case("os_trace", FST_OSLog)
7006       .Case("os_log", FST_OSLog)
7007       .Default(FST_Unknown);
7008 }
7009 
7010 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7011 /// functions) for correct use of format strings.
7012 /// Returns true if a format string has been fully checked.
7013 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7014                                 ArrayRef<const Expr *> Args,
7015                                 bool IsCXXMember,
7016                                 VariadicCallType CallType,
7017                                 SourceLocation Loc, SourceRange Range,
7018                                 llvm::SmallBitVector &CheckedVarArgs) {
7019   FormatStringInfo FSI;
7020   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7021     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7022                                 FSI.FirstDataArg, GetFormatStringType(Format),
7023                                 CallType, Loc, Range, CheckedVarArgs);
7024   return false;
7025 }
7026 
7027 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7028                                 bool HasVAListArg, unsigned format_idx,
7029                                 unsigned firstDataArg, FormatStringType Type,
7030                                 VariadicCallType CallType,
7031                                 SourceLocation Loc, SourceRange Range,
7032                                 llvm::SmallBitVector &CheckedVarArgs) {
7033   // CHECK: printf/scanf-like function is called with no format string.
7034   if (format_idx >= Args.size()) {
7035     Diag(Loc, diag::warn_missing_format_string) << Range;
7036     return false;
7037   }
7038 
7039   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7040 
7041   // CHECK: format string is not a string literal.
7042   //
7043   // Dynamically generated format strings are difficult to
7044   // automatically vet at compile time.  Requiring that format strings
7045   // are string literals: (1) permits the checking of format strings by
7046   // the compiler and thereby (2) can practically remove the source of
7047   // many format string exploits.
7048 
7049   // Format string can be either ObjC string (e.g. @"%d") or
7050   // C string (e.g. "%d")
7051   // ObjC string uses the same format specifiers as C string, so we can use
7052   // the same format string checking logic for both ObjC and C strings.
7053   UncoveredArgHandler UncoveredArg;
7054   StringLiteralCheckType CT =
7055       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7056                             format_idx, firstDataArg, Type, CallType,
7057                             /*IsFunctionCall*/ true, CheckedVarArgs,
7058                             UncoveredArg,
7059                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7060 
7061   // Generate a diagnostic where an uncovered argument is detected.
7062   if (UncoveredArg.hasUncoveredArg()) {
7063     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7064     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7065     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7066   }
7067 
7068   if (CT != SLCT_NotALiteral)
7069     // Literal format string found, check done!
7070     return CT == SLCT_CheckedLiteral;
7071 
7072   // Strftime is particular as it always uses a single 'time' argument,
7073   // so it is safe to pass a non-literal string.
7074   if (Type == FST_Strftime)
7075     return false;
7076 
7077   // Do not emit diag when the string param is a macro expansion and the
7078   // format is either NSString or CFString. This is a hack to prevent
7079   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7080   // which are usually used in place of NS and CF string literals.
7081   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7082   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7083     return false;
7084 
7085   // If there are no arguments specified, warn with -Wformat-security, otherwise
7086   // warn only with -Wformat-nonliteral.
7087   if (Args.size() == firstDataArg) {
7088     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7089       << OrigFormatExpr->getSourceRange();
7090     switch (Type) {
7091     default:
7092       break;
7093     case FST_Kprintf:
7094     case FST_FreeBSDKPrintf:
7095     case FST_Printf:
7096       Diag(FormatLoc, diag::note_format_security_fixit)
7097         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7098       break;
7099     case FST_NSString:
7100       Diag(FormatLoc, diag::note_format_security_fixit)
7101         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7102       break;
7103     }
7104   } else {
7105     Diag(FormatLoc, diag::warn_format_nonliteral)
7106       << OrigFormatExpr->getSourceRange();
7107   }
7108   return false;
7109 }
7110 
7111 namespace {
7112 
7113 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7114 protected:
7115   Sema &S;
7116   const FormatStringLiteral *FExpr;
7117   const Expr *OrigFormatExpr;
7118   const Sema::FormatStringType FSType;
7119   const unsigned FirstDataArg;
7120   const unsigned NumDataArgs;
7121   const char *Beg; // Start of format string.
7122   const bool HasVAListArg;
7123   ArrayRef<const Expr *> Args;
7124   unsigned FormatIdx;
7125   llvm::SmallBitVector CoveredArgs;
7126   bool usesPositionalArgs = false;
7127   bool atFirstArg = true;
7128   bool inFunctionCall;
7129   Sema::VariadicCallType CallType;
7130   llvm::SmallBitVector &CheckedVarArgs;
7131   UncoveredArgHandler &UncoveredArg;
7132 
7133 public:
7134   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7135                      const Expr *origFormatExpr,
7136                      const Sema::FormatStringType type, unsigned firstDataArg,
7137                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7138                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7139                      bool inFunctionCall, Sema::VariadicCallType callType,
7140                      llvm::SmallBitVector &CheckedVarArgs,
7141                      UncoveredArgHandler &UncoveredArg)
7142       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7143         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7144         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7145         inFunctionCall(inFunctionCall), CallType(callType),
7146         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7147     CoveredArgs.resize(numDataArgs);
7148     CoveredArgs.reset();
7149   }
7150 
7151   void DoneProcessing();
7152 
7153   void HandleIncompleteSpecifier(const char *startSpecifier,
7154                                  unsigned specifierLen) override;
7155 
7156   void HandleInvalidLengthModifier(
7157                            const analyze_format_string::FormatSpecifier &FS,
7158                            const analyze_format_string::ConversionSpecifier &CS,
7159                            const char *startSpecifier, unsigned specifierLen,
7160                            unsigned DiagID);
7161 
7162   void HandleNonStandardLengthModifier(
7163                     const analyze_format_string::FormatSpecifier &FS,
7164                     const char *startSpecifier, unsigned specifierLen);
7165 
7166   void HandleNonStandardConversionSpecifier(
7167                     const analyze_format_string::ConversionSpecifier &CS,
7168                     const char *startSpecifier, unsigned specifierLen);
7169 
7170   void HandlePosition(const char *startPos, unsigned posLen) override;
7171 
7172   void HandleInvalidPosition(const char *startSpecifier,
7173                              unsigned specifierLen,
7174                              analyze_format_string::PositionContext p) override;
7175 
7176   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7177 
7178   void HandleNullChar(const char *nullCharacter) override;
7179 
7180   template <typename Range>
7181   static void
7182   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7183                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7184                        bool IsStringLocation, Range StringRange,
7185                        ArrayRef<FixItHint> Fixit = None);
7186 
7187 protected:
7188   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7189                                         const char *startSpec,
7190                                         unsigned specifierLen,
7191                                         const char *csStart, unsigned csLen);
7192 
7193   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7194                                          const char *startSpec,
7195                                          unsigned specifierLen);
7196 
7197   SourceRange getFormatStringRange();
7198   CharSourceRange getSpecifierRange(const char *startSpecifier,
7199                                     unsigned specifierLen);
7200   SourceLocation getLocationOfByte(const char *x);
7201 
7202   const Expr *getDataArg(unsigned i) const;
7203 
7204   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7205                     const analyze_format_string::ConversionSpecifier &CS,
7206                     const char *startSpecifier, unsigned specifierLen,
7207                     unsigned argIndex);
7208 
7209   template <typename Range>
7210   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7211                             bool IsStringLocation, Range StringRange,
7212                             ArrayRef<FixItHint> Fixit = None);
7213 };
7214 
7215 } // namespace
7216 
7217 SourceRange CheckFormatHandler::getFormatStringRange() {
7218   return OrigFormatExpr->getSourceRange();
7219 }
7220 
7221 CharSourceRange CheckFormatHandler::
7222 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7223   SourceLocation Start = getLocationOfByte(startSpecifier);
7224   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7225 
7226   // Advance the end SourceLocation by one due to half-open ranges.
7227   End = End.getLocWithOffset(1);
7228 
7229   return CharSourceRange::getCharRange(Start, End);
7230 }
7231 
7232 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7233   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7234                                   S.getLangOpts(), S.Context.getTargetInfo());
7235 }
7236 
7237 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7238                                                    unsigned specifierLen){
7239   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7240                        getLocationOfByte(startSpecifier),
7241                        /*IsStringLocation*/true,
7242                        getSpecifierRange(startSpecifier, specifierLen));
7243 }
7244 
7245 void CheckFormatHandler::HandleInvalidLengthModifier(
7246     const analyze_format_string::FormatSpecifier &FS,
7247     const analyze_format_string::ConversionSpecifier &CS,
7248     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7249   using namespace analyze_format_string;
7250 
7251   const LengthModifier &LM = FS.getLengthModifier();
7252   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7253 
7254   // See if we know how to fix this length modifier.
7255   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7256   if (FixedLM) {
7257     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7258                          getLocationOfByte(LM.getStart()),
7259                          /*IsStringLocation*/true,
7260                          getSpecifierRange(startSpecifier, specifierLen));
7261 
7262     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7263       << FixedLM->toString()
7264       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7265 
7266   } else {
7267     FixItHint Hint;
7268     if (DiagID == diag::warn_format_nonsensical_length)
7269       Hint = FixItHint::CreateRemoval(LMRange);
7270 
7271     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7272                          getLocationOfByte(LM.getStart()),
7273                          /*IsStringLocation*/true,
7274                          getSpecifierRange(startSpecifier, specifierLen),
7275                          Hint);
7276   }
7277 }
7278 
7279 void CheckFormatHandler::HandleNonStandardLengthModifier(
7280     const analyze_format_string::FormatSpecifier &FS,
7281     const char *startSpecifier, unsigned specifierLen) {
7282   using namespace analyze_format_string;
7283 
7284   const LengthModifier &LM = FS.getLengthModifier();
7285   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7286 
7287   // See if we know how to fix this length modifier.
7288   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7289   if (FixedLM) {
7290     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7291                            << LM.toString() << 0,
7292                          getLocationOfByte(LM.getStart()),
7293                          /*IsStringLocation*/true,
7294                          getSpecifierRange(startSpecifier, specifierLen));
7295 
7296     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7297       << FixedLM->toString()
7298       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7299 
7300   } else {
7301     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7302                            << LM.toString() << 0,
7303                          getLocationOfByte(LM.getStart()),
7304                          /*IsStringLocation*/true,
7305                          getSpecifierRange(startSpecifier, specifierLen));
7306   }
7307 }
7308 
7309 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7310     const analyze_format_string::ConversionSpecifier &CS,
7311     const char *startSpecifier, unsigned specifierLen) {
7312   using namespace analyze_format_string;
7313 
7314   // See if we know how to fix this conversion specifier.
7315   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7316   if (FixedCS) {
7317     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7318                           << CS.toString() << /*conversion specifier*/1,
7319                          getLocationOfByte(CS.getStart()),
7320                          /*IsStringLocation*/true,
7321                          getSpecifierRange(startSpecifier, specifierLen));
7322 
7323     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7324     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7325       << FixedCS->toString()
7326       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7327   } else {
7328     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7329                           << CS.toString() << /*conversion specifier*/1,
7330                          getLocationOfByte(CS.getStart()),
7331                          /*IsStringLocation*/true,
7332                          getSpecifierRange(startSpecifier, specifierLen));
7333   }
7334 }
7335 
7336 void CheckFormatHandler::HandlePosition(const char *startPos,
7337                                         unsigned posLen) {
7338   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7339                                getLocationOfByte(startPos),
7340                                /*IsStringLocation*/true,
7341                                getSpecifierRange(startPos, posLen));
7342 }
7343 
7344 void
7345 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7346                                      analyze_format_string::PositionContext p) {
7347   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7348                          << (unsigned) p,
7349                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7350                        getSpecifierRange(startPos, posLen));
7351 }
7352 
7353 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7354                                             unsigned posLen) {
7355   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7356                                getLocationOfByte(startPos),
7357                                /*IsStringLocation*/true,
7358                                getSpecifierRange(startPos, posLen));
7359 }
7360 
7361 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7362   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7363     // The presence of a null character is likely an error.
7364     EmitFormatDiagnostic(
7365       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7366       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7367       getFormatStringRange());
7368   }
7369 }
7370 
7371 // Note that this may return NULL if there was an error parsing or building
7372 // one of the argument expressions.
7373 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7374   return Args[FirstDataArg + i];
7375 }
7376 
7377 void CheckFormatHandler::DoneProcessing() {
7378   // Does the number of data arguments exceed the number of
7379   // format conversions in the format string?
7380   if (!HasVAListArg) {
7381       // Find any arguments that weren't covered.
7382     CoveredArgs.flip();
7383     signed notCoveredArg = CoveredArgs.find_first();
7384     if (notCoveredArg >= 0) {
7385       assert((unsigned)notCoveredArg < NumDataArgs);
7386       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7387     } else {
7388       UncoveredArg.setAllCovered();
7389     }
7390   }
7391 }
7392 
7393 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7394                                    const Expr *ArgExpr) {
7395   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7396          "Invalid state");
7397 
7398   if (!ArgExpr)
7399     return;
7400 
7401   SourceLocation Loc = ArgExpr->getBeginLoc();
7402 
7403   if (S.getSourceManager().isInSystemMacro(Loc))
7404     return;
7405 
7406   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7407   for (auto E : DiagnosticExprs)
7408     PDiag << E->getSourceRange();
7409 
7410   CheckFormatHandler::EmitFormatDiagnostic(
7411                                   S, IsFunctionCall, DiagnosticExprs[0],
7412                                   PDiag, Loc, /*IsStringLocation*/false,
7413                                   DiagnosticExprs[0]->getSourceRange());
7414 }
7415 
7416 bool
7417 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7418                                                      SourceLocation Loc,
7419                                                      const char *startSpec,
7420                                                      unsigned specifierLen,
7421                                                      const char *csStart,
7422                                                      unsigned csLen) {
7423   bool keepGoing = true;
7424   if (argIndex < NumDataArgs) {
7425     // Consider the argument coverered, even though the specifier doesn't
7426     // make sense.
7427     CoveredArgs.set(argIndex);
7428   }
7429   else {
7430     // If argIndex exceeds the number of data arguments we
7431     // don't issue a warning because that is just a cascade of warnings (and
7432     // they may have intended '%%' anyway). We don't want to continue processing
7433     // the format string after this point, however, as we will like just get
7434     // gibberish when trying to match arguments.
7435     keepGoing = false;
7436   }
7437 
7438   StringRef Specifier(csStart, csLen);
7439 
7440   // If the specifier in non-printable, it could be the first byte of a UTF-8
7441   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7442   // hex value.
7443   std::string CodePointStr;
7444   if (!llvm::sys::locale::isPrint(*csStart)) {
7445     llvm::UTF32 CodePoint;
7446     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7447     const llvm::UTF8 *E =
7448         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7449     llvm::ConversionResult Result =
7450         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7451 
7452     if (Result != llvm::conversionOK) {
7453       unsigned char FirstChar = *csStart;
7454       CodePoint = (llvm::UTF32)FirstChar;
7455     }
7456 
7457     llvm::raw_string_ostream OS(CodePointStr);
7458     if (CodePoint < 256)
7459       OS << "\\x" << llvm::format("%02x", CodePoint);
7460     else if (CodePoint <= 0xFFFF)
7461       OS << "\\u" << llvm::format("%04x", CodePoint);
7462     else
7463       OS << "\\U" << llvm::format("%08x", CodePoint);
7464     OS.flush();
7465     Specifier = CodePointStr;
7466   }
7467 
7468   EmitFormatDiagnostic(
7469       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7470       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7471 
7472   return keepGoing;
7473 }
7474 
7475 void
7476 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7477                                                       const char *startSpec,
7478                                                       unsigned specifierLen) {
7479   EmitFormatDiagnostic(
7480     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7481     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7482 }
7483 
7484 bool
7485 CheckFormatHandler::CheckNumArgs(
7486   const analyze_format_string::FormatSpecifier &FS,
7487   const analyze_format_string::ConversionSpecifier &CS,
7488   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7489 
7490   if (argIndex >= NumDataArgs) {
7491     PartialDiagnostic PDiag = FS.usesPositionalArg()
7492       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7493            << (argIndex+1) << NumDataArgs)
7494       : S.PDiag(diag::warn_printf_insufficient_data_args);
7495     EmitFormatDiagnostic(
7496       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7497       getSpecifierRange(startSpecifier, specifierLen));
7498 
7499     // Since more arguments than conversion tokens are given, by extension
7500     // all arguments are covered, so mark this as so.
7501     UncoveredArg.setAllCovered();
7502     return false;
7503   }
7504   return true;
7505 }
7506 
7507 template<typename Range>
7508 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7509                                               SourceLocation Loc,
7510                                               bool IsStringLocation,
7511                                               Range StringRange,
7512                                               ArrayRef<FixItHint> FixIt) {
7513   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7514                        Loc, IsStringLocation, StringRange, FixIt);
7515 }
7516 
7517 /// If the format string is not within the function call, emit a note
7518 /// so that the function call and string are in diagnostic messages.
7519 ///
7520 /// \param InFunctionCall if true, the format string is within the function
7521 /// call and only one diagnostic message will be produced.  Otherwise, an
7522 /// extra note will be emitted pointing to location of the format string.
7523 ///
7524 /// \param ArgumentExpr the expression that is passed as the format string
7525 /// argument in the function call.  Used for getting locations when two
7526 /// diagnostics are emitted.
7527 ///
7528 /// \param PDiag the callee should already have provided any strings for the
7529 /// diagnostic message.  This function only adds locations and fixits
7530 /// to diagnostics.
7531 ///
7532 /// \param Loc primary location for diagnostic.  If two diagnostics are
7533 /// required, one will be at Loc and a new SourceLocation will be created for
7534 /// the other one.
7535 ///
7536 /// \param IsStringLocation if true, Loc points to the format string should be
7537 /// used for the note.  Otherwise, Loc points to the argument list and will
7538 /// be used with PDiag.
7539 ///
7540 /// \param StringRange some or all of the string to highlight.  This is
7541 /// templated so it can accept either a CharSourceRange or a SourceRange.
7542 ///
7543 /// \param FixIt optional fix it hint for the format string.
7544 template <typename Range>
7545 void CheckFormatHandler::EmitFormatDiagnostic(
7546     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7547     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7548     Range StringRange, ArrayRef<FixItHint> FixIt) {
7549   if (InFunctionCall) {
7550     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7551     D << StringRange;
7552     D << FixIt;
7553   } else {
7554     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7555       << ArgumentExpr->getSourceRange();
7556 
7557     const Sema::SemaDiagnosticBuilder &Note =
7558       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7559              diag::note_format_string_defined);
7560 
7561     Note << StringRange;
7562     Note << FixIt;
7563   }
7564 }
7565 
7566 //===--- CHECK: Printf format string checking ------------------------------===//
7567 
7568 namespace {
7569 
7570 class CheckPrintfHandler : public CheckFormatHandler {
7571 public:
7572   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7573                      const Expr *origFormatExpr,
7574                      const Sema::FormatStringType type, unsigned firstDataArg,
7575                      unsigned numDataArgs, bool isObjC, const char *beg,
7576                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7577                      unsigned formatIdx, bool inFunctionCall,
7578                      Sema::VariadicCallType CallType,
7579                      llvm::SmallBitVector &CheckedVarArgs,
7580                      UncoveredArgHandler &UncoveredArg)
7581       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7582                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7583                            inFunctionCall, CallType, CheckedVarArgs,
7584                            UncoveredArg) {}
7585 
7586   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7587 
7588   /// Returns true if '%@' specifiers are allowed in the format string.
7589   bool allowsObjCArg() const {
7590     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7591            FSType == Sema::FST_OSTrace;
7592   }
7593 
7594   bool HandleInvalidPrintfConversionSpecifier(
7595                                       const analyze_printf::PrintfSpecifier &FS,
7596                                       const char *startSpecifier,
7597                                       unsigned specifierLen) override;
7598 
7599   void handleInvalidMaskType(StringRef MaskType) override;
7600 
7601   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7602                              const char *startSpecifier,
7603                              unsigned specifierLen) override;
7604   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7605                        const char *StartSpecifier,
7606                        unsigned SpecifierLen,
7607                        const Expr *E);
7608 
7609   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7610                     const char *startSpecifier, unsigned specifierLen);
7611   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7612                            const analyze_printf::OptionalAmount &Amt,
7613                            unsigned type,
7614                            const char *startSpecifier, unsigned specifierLen);
7615   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7616                   const analyze_printf::OptionalFlag &flag,
7617                   const char *startSpecifier, unsigned specifierLen);
7618   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7619                          const analyze_printf::OptionalFlag &ignoredFlag,
7620                          const analyze_printf::OptionalFlag &flag,
7621                          const char *startSpecifier, unsigned specifierLen);
7622   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7623                            const Expr *E);
7624 
7625   void HandleEmptyObjCModifierFlag(const char *startFlag,
7626                                    unsigned flagLen) override;
7627 
7628   void HandleInvalidObjCModifierFlag(const char *startFlag,
7629                                             unsigned flagLen) override;
7630 
7631   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7632                                            const char *flagsEnd,
7633                                            const char *conversionPosition)
7634                                              override;
7635 };
7636 
7637 } // namespace
7638 
7639 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7640                                       const analyze_printf::PrintfSpecifier &FS,
7641                                       const char *startSpecifier,
7642                                       unsigned specifierLen) {
7643   const analyze_printf::PrintfConversionSpecifier &CS =
7644     FS.getConversionSpecifier();
7645 
7646   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7647                                           getLocationOfByte(CS.getStart()),
7648                                           startSpecifier, specifierLen,
7649                                           CS.getStart(), CS.getLength());
7650 }
7651 
7652 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7653   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7654 }
7655 
7656 bool CheckPrintfHandler::HandleAmount(
7657                                const analyze_format_string::OptionalAmount &Amt,
7658                                unsigned k, const char *startSpecifier,
7659                                unsigned specifierLen) {
7660   if (Amt.hasDataArgument()) {
7661     if (!HasVAListArg) {
7662       unsigned argIndex = Amt.getArgIndex();
7663       if (argIndex >= NumDataArgs) {
7664         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7665                                << k,
7666                              getLocationOfByte(Amt.getStart()),
7667                              /*IsStringLocation*/true,
7668                              getSpecifierRange(startSpecifier, specifierLen));
7669         // Don't do any more checking.  We will just emit
7670         // spurious errors.
7671         return false;
7672       }
7673 
7674       // Type check the data argument.  It should be an 'int'.
7675       // Although not in conformance with C99, we also allow the argument to be
7676       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7677       // doesn't emit a warning for that case.
7678       CoveredArgs.set(argIndex);
7679       const Expr *Arg = getDataArg(argIndex);
7680       if (!Arg)
7681         return false;
7682 
7683       QualType T = Arg->getType();
7684 
7685       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7686       assert(AT.isValid());
7687 
7688       if (!AT.matchesType(S.Context, T)) {
7689         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7690                                << k << AT.getRepresentativeTypeName(S.Context)
7691                                << T << Arg->getSourceRange(),
7692                              getLocationOfByte(Amt.getStart()),
7693                              /*IsStringLocation*/true,
7694                              getSpecifierRange(startSpecifier, specifierLen));
7695         // Don't do any more checking.  We will just emit
7696         // spurious errors.
7697         return false;
7698       }
7699     }
7700   }
7701   return true;
7702 }
7703 
7704 void CheckPrintfHandler::HandleInvalidAmount(
7705                                       const analyze_printf::PrintfSpecifier &FS,
7706                                       const analyze_printf::OptionalAmount &Amt,
7707                                       unsigned type,
7708                                       const char *startSpecifier,
7709                                       unsigned specifierLen) {
7710   const analyze_printf::PrintfConversionSpecifier &CS =
7711     FS.getConversionSpecifier();
7712 
7713   FixItHint fixit =
7714     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7715       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7716                                  Amt.getConstantLength()))
7717       : FixItHint();
7718 
7719   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7720                          << type << CS.toString(),
7721                        getLocationOfByte(Amt.getStart()),
7722                        /*IsStringLocation*/true,
7723                        getSpecifierRange(startSpecifier, specifierLen),
7724                        fixit);
7725 }
7726 
7727 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7728                                     const analyze_printf::OptionalFlag &flag,
7729                                     const char *startSpecifier,
7730                                     unsigned specifierLen) {
7731   // Warn about pointless flag with a fixit removal.
7732   const analyze_printf::PrintfConversionSpecifier &CS =
7733     FS.getConversionSpecifier();
7734   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7735                          << flag.toString() << CS.toString(),
7736                        getLocationOfByte(flag.getPosition()),
7737                        /*IsStringLocation*/true,
7738                        getSpecifierRange(startSpecifier, specifierLen),
7739                        FixItHint::CreateRemoval(
7740                          getSpecifierRange(flag.getPosition(), 1)));
7741 }
7742 
7743 void CheckPrintfHandler::HandleIgnoredFlag(
7744                                 const analyze_printf::PrintfSpecifier &FS,
7745                                 const analyze_printf::OptionalFlag &ignoredFlag,
7746                                 const analyze_printf::OptionalFlag &flag,
7747                                 const char *startSpecifier,
7748                                 unsigned specifierLen) {
7749   // Warn about ignored flag with a fixit removal.
7750   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7751                          << ignoredFlag.toString() << flag.toString(),
7752                        getLocationOfByte(ignoredFlag.getPosition()),
7753                        /*IsStringLocation*/true,
7754                        getSpecifierRange(startSpecifier, specifierLen),
7755                        FixItHint::CreateRemoval(
7756                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7757 }
7758 
7759 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7760                                                      unsigned flagLen) {
7761   // Warn about an empty flag.
7762   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7763                        getLocationOfByte(startFlag),
7764                        /*IsStringLocation*/true,
7765                        getSpecifierRange(startFlag, flagLen));
7766 }
7767 
7768 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7769                                                        unsigned flagLen) {
7770   // Warn about an invalid flag.
7771   auto Range = getSpecifierRange(startFlag, flagLen);
7772   StringRef flag(startFlag, flagLen);
7773   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7774                       getLocationOfByte(startFlag),
7775                       /*IsStringLocation*/true,
7776                       Range, FixItHint::CreateRemoval(Range));
7777 }
7778 
7779 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7780     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7781     // Warn about using '[...]' without a '@' conversion.
7782     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7783     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7784     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7785                          getLocationOfByte(conversionPosition),
7786                          /*IsStringLocation*/true,
7787                          Range, FixItHint::CreateRemoval(Range));
7788 }
7789 
7790 // Determines if the specified is a C++ class or struct containing
7791 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7792 // "c_str()").
7793 template<typename MemberKind>
7794 static llvm::SmallPtrSet<MemberKind*, 1>
7795 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7796   const RecordType *RT = Ty->getAs<RecordType>();
7797   llvm::SmallPtrSet<MemberKind*, 1> Results;
7798 
7799   if (!RT)
7800     return Results;
7801   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7802   if (!RD || !RD->getDefinition())
7803     return Results;
7804 
7805   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7806                  Sema::LookupMemberName);
7807   R.suppressDiagnostics();
7808 
7809   // We just need to include all members of the right kind turned up by the
7810   // filter, at this point.
7811   if (S.LookupQualifiedName(R, RT->getDecl()))
7812     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7813       NamedDecl *decl = (*I)->getUnderlyingDecl();
7814       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7815         Results.insert(FK);
7816     }
7817   return Results;
7818 }
7819 
7820 /// Check if we could call '.c_str()' on an object.
7821 ///
7822 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7823 /// allow the call, or if it would be ambiguous).
7824 bool Sema::hasCStrMethod(const Expr *E) {
7825   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7826 
7827   MethodSet Results =
7828       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7829   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7830        MI != ME; ++MI)
7831     if ((*MI)->getMinRequiredArguments() == 0)
7832       return true;
7833   return false;
7834 }
7835 
7836 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7837 // better diagnostic if so. AT is assumed to be valid.
7838 // Returns true when a c_str() conversion method is found.
7839 bool CheckPrintfHandler::checkForCStrMembers(
7840     const analyze_printf::ArgType &AT, const Expr *E) {
7841   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7842 
7843   MethodSet Results =
7844       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7845 
7846   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7847        MI != ME; ++MI) {
7848     const CXXMethodDecl *Method = *MI;
7849     if (Method->getMinRequiredArguments() == 0 &&
7850         AT.matchesType(S.Context, Method->getReturnType())) {
7851       // FIXME: Suggest parens if the expression needs them.
7852       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7853       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7854           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7855       return true;
7856     }
7857   }
7858 
7859   return false;
7860 }
7861 
7862 bool
7863 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7864                                             &FS,
7865                                           const char *startSpecifier,
7866                                           unsigned specifierLen) {
7867   using namespace analyze_format_string;
7868   using namespace analyze_printf;
7869 
7870   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7871 
7872   if (FS.consumesDataArgument()) {
7873     if (atFirstArg) {
7874         atFirstArg = false;
7875         usesPositionalArgs = FS.usesPositionalArg();
7876     }
7877     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7878       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7879                                         startSpecifier, specifierLen);
7880       return false;
7881     }
7882   }
7883 
7884   // First check if the field width, precision, and conversion specifier
7885   // have matching data arguments.
7886   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7887                     startSpecifier, specifierLen)) {
7888     return false;
7889   }
7890 
7891   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7892                     startSpecifier, specifierLen)) {
7893     return false;
7894   }
7895 
7896   if (!CS.consumesDataArgument()) {
7897     // FIXME: Technically specifying a precision or field width here
7898     // makes no sense.  Worth issuing a warning at some point.
7899     return true;
7900   }
7901 
7902   // Consume the argument.
7903   unsigned argIndex = FS.getArgIndex();
7904   if (argIndex < NumDataArgs) {
7905     // The check to see if the argIndex is valid will come later.
7906     // We set the bit here because we may exit early from this
7907     // function if we encounter some other error.
7908     CoveredArgs.set(argIndex);
7909   }
7910 
7911   // FreeBSD kernel extensions.
7912   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7913       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7914     // We need at least two arguments.
7915     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7916       return false;
7917 
7918     // Claim the second argument.
7919     CoveredArgs.set(argIndex + 1);
7920 
7921     // Type check the first argument (int for %b, pointer for %D)
7922     const Expr *Ex = getDataArg(argIndex);
7923     const analyze_printf::ArgType &AT =
7924       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7925         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7926     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7927       EmitFormatDiagnostic(
7928           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7929               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7930               << false << Ex->getSourceRange(),
7931           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7932           getSpecifierRange(startSpecifier, specifierLen));
7933 
7934     // Type check the second argument (char * for both %b and %D)
7935     Ex = getDataArg(argIndex + 1);
7936     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7937     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7938       EmitFormatDiagnostic(
7939           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7940               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7941               << false << Ex->getSourceRange(),
7942           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7943           getSpecifierRange(startSpecifier, specifierLen));
7944 
7945      return true;
7946   }
7947 
7948   // Check for using an Objective-C specific conversion specifier
7949   // in a non-ObjC literal.
7950   if (!allowsObjCArg() && CS.isObjCArg()) {
7951     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7952                                                   specifierLen);
7953   }
7954 
7955   // %P can only be used with os_log.
7956   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7957     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7958                                                   specifierLen);
7959   }
7960 
7961   // %n is not allowed with os_log.
7962   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7963     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7964                          getLocationOfByte(CS.getStart()),
7965                          /*IsStringLocation*/ false,
7966                          getSpecifierRange(startSpecifier, specifierLen));
7967 
7968     return true;
7969   }
7970 
7971   // Only scalars are allowed for os_trace.
7972   if (FSType == Sema::FST_OSTrace &&
7973       (CS.getKind() == ConversionSpecifier::PArg ||
7974        CS.getKind() == ConversionSpecifier::sArg ||
7975        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7976     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7977                                                   specifierLen);
7978   }
7979 
7980   // Check for use of public/private annotation outside of os_log().
7981   if (FSType != Sema::FST_OSLog) {
7982     if (FS.isPublic().isSet()) {
7983       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7984                                << "public",
7985                            getLocationOfByte(FS.isPublic().getPosition()),
7986                            /*IsStringLocation*/ false,
7987                            getSpecifierRange(startSpecifier, specifierLen));
7988     }
7989     if (FS.isPrivate().isSet()) {
7990       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7991                                << "private",
7992                            getLocationOfByte(FS.isPrivate().getPosition()),
7993                            /*IsStringLocation*/ false,
7994                            getSpecifierRange(startSpecifier, specifierLen));
7995     }
7996   }
7997 
7998   // Check for invalid use of field width
7999   if (!FS.hasValidFieldWidth()) {
8000     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8001         startSpecifier, specifierLen);
8002   }
8003 
8004   // Check for invalid use of precision
8005   if (!FS.hasValidPrecision()) {
8006     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8007         startSpecifier, specifierLen);
8008   }
8009 
8010   // Precision is mandatory for %P specifier.
8011   if (CS.getKind() == ConversionSpecifier::PArg &&
8012       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8013     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8014                          getLocationOfByte(startSpecifier),
8015                          /*IsStringLocation*/ false,
8016                          getSpecifierRange(startSpecifier, specifierLen));
8017   }
8018 
8019   // Check each flag does not conflict with any other component.
8020   if (!FS.hasValidThousandsGroupingPrefix())
8021     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8022   if (!FS.hasValidLeadingZeros())
8023     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8024   if (!FS.hasValidPlusPrefix())
8025     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8026   if (!FS.hasValidSpacePrefix())
8027     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8028   if (!FS.hasValidAlternativeForm())
8029     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8030   if (!FS.hasValidLeftJustified())
8031     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8032 
8033   // Check that flags are not ignored by another flag
8034   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8035     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8036         startSpecifier, specifierLen);
8037   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8038     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8039             startSpecifier, specifierLen);
8040 
8041   // Check the length modifier is valid with the given conversion specifier.
8042   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8043                                  S.getLangOpts()))
8044     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8045                                 diag::warn_format_nonsensical_length);
8046   else if (!FS.hasStandardLengthModifier())
8047     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8048   else if (!FS.hasStandardLengthConversionCombination())
8049     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8050                                 diag::warn_format_non_standard_conversion_spec);
8051 
8052   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8053     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8054 
8055   // The remaining checks depend on the data arguments.
8056   if (HasVAListArg)
8057     return true;
8058 
8059   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8060     return false;
8061 
8062   const Expr *Arg = getDataArg(argIndex);
8063   if (!Arg)
8064     return true;
8065 
8066   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8067 }
8068 
8069 static bool requiresParensToAddCast(const Expr *E) {
8070   // FIXME: We should have a general way to reason about operator
8071   // precedence and whether parens are actually needed here.
8072   // Take care of a few common cases where they aren't.
8073   const Expr *Inside = E->IgnoreImpCasts();
8074   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8075     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8076 
8077   switch (Inside->getStmtClass()) {
8078   case Stmt::ArraySubscriptExprClass:
8079   case Stmt::CallExprClass:
8080   case Stmt::CharacterLiteralClass:
8081   case Stmt::CXXBoolLiteralExprClass:
8082   case Stmt::DeclRefExprClass:
8083   case Stmt::FloatingLiteralClass:
8084   case Stmt::IntegerLiteralClass:
8085   case Stmt::MemberExprClass:
8086   case Stmt::ObjCArrayLiteralClass:
8087   case Stmt::ObjCBoolLiteralExprClass:
8088   case Stmt::ObjCBoxedExprClass:
8089   case Stmt::ObjCDictionaryLiteralClass:
8090   case Stmt::ObjCEncodeExprClass:
8091   case Stmt::ObjCIvarRefExprClass:
8092   case Stmt::ObjCMessageExprClass:
8093   case Stmt::ObjCPropertyRefExprClass:
8094   case Stmt::ObjCStringLiteralClass:
8095   case Stmt::ObjCSubscriptRefExprClass:
8096   case Stmt::ParenExprClass:
8097   case Stmt::StringLiteralClass:
8098   case Stmt::UnaryOperatorClass:
8099     return false;
8100   default:
8101     return true;
8102   }
8103 }
8104 
8105 static std::pair<QualType, StringRef>
8106 shouldNotPrintDirectly(const ASTContext &Context,
8107                        QualType IntendedTy,
8108                        const Expr *E) {
8109   // Use a 'while' to peel off layers of typedefs.
8110   QualType TyTy = IntendedTy;
8111   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8112     StringRef Name = UserTy->getDecl()->getName();
8113     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8114       .Case("CFIndex", Context.getNSIntegerType())
8115       .Case("NSInteger", Context.getNSIntegerType())
8116       .Case("NSUInteger", Context.getNSUIntegerType())
8117       .Case("SInt32", Context.IntTy)
8118       .Case("UInt32", Context.UnsignedIntTy)
8119       .Default(QualType());
8120 
8121     if (!CastTy.isNull())
8122       return std::make_pair(CastTy, Name);
8123 
8124     TyTy = UserTy->desugar();
8125   }
8126 
8127   // Strip parens if necessary.
8128   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8129     return shouldNotPrintDirectly(Context,
8130                                   PE->getSubExpr()->getType(),
8131                                   PE->getSubExpr());
8132 
8133   // If this is a conditional expression, then its result type is constructed
8134   // via usual arithmetic conversions and thus there might be no necessary
8135   // typedef sugar there.  Recurse to operands to check for NSInteger &
8136   // Co. usage condition.
8137   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8138     QualType TrueTy, FalseTy;
8139     StringRef TrueName, FalseName;
8140 
8141     std::tie(TrueTy, TrueName) =
8142       shouldNotPrintDirectly(Context,
8143                              CO->getTrueExpr()->getType(),
8144                              CO->getTrueExpr());
8145     std::tie(FalseTy, FalseName) =
8146       shouldNotPrintDirectly(Context,
8147                              CO->getFalseExpr()->getType(),
8148                              CO->getFalseExpr());
8149 
8150     if (TrueTy == FalseTy)
8151       return std::make_pair(TrueTy, TrueName);
8152     else if (TrueTy.isNull())
8153       return std::make_pair(FalseTy, FalseName);
8154     else if (FalseTy.isNull())
8155       return std::make_pair(TrueTy, TrueName);
8156   }
8157 
8158   return std::make_pair(QualType(), StringRef());
8159 }
8160 
8161 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8162 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8163 /// type do not count.
8164 static bool
8165 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8166   QualType From = ICE->getSubExpr()->getType();
8167   QualType To = ICE->getType();
8168   // It's an integer promotion if the destination type is the promoted
8169   // source type.
8170   if (ICE->getCastKind() == CK_IntegralCast &&
8171       From->isPromotableIntegerType() &&
8172       S.Context.getPromotedIntegerType(From) == To)
8173     return true;
8174   // Look through vector types, since we do default argument promotion for
8175   // those in OpenCL.
8176   if (const auto *VecTy = From->getAs<ExtVectorType>())
8177     From = VecTy->getElementType();
8178   if (const auto *VecTy = To->getAs<ExtVectorType>())
8179     To = VecTy->getElementType();
8180   // It's a floating promotion if the source type is a lower rank.
8181   return ICE->getCastKind() == CK_FloatingCast &&
8182          S.Context.getFloatingTypeOrder(From, To) < 0;
8183 }
8184 
8185 bool
8186 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8187                                     const char *StartSpecifier,
8188                                     unsigned SpecifierLen,
8189                                     const Expr *E) {
8190   using namespace analyze_format_string;
8191   using namespace analyze_printf;
8192 
8193   // Now type check the data expression that matches the
8194   // format specifier.
8195   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8196   if (!AT.isValid())
8197     return true;
8198 
8199   QualType ExprTy = E->getType();
8200   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8201     ExprTy = TET->getUnderlyingExpr()->getType();
8202   }
8203 
8204   // Diagnose attempts to print a boolean value as a character. Unlike other
8205   // -Wformat diagnostics, this is fine from a type perspective, but it still
8206   // doesn't make sense.
8207   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8208       E->isKnownToHaveBooleanValue()) {
8209     const CharSourceRange &CSR =
8210         getSpecifierRange(StartSpecifier, SpecifierLen);
8211     SmallString<4> FSString;
8212     llvm::raw_svector_ostream os(FSString);
8213     FS.toString(os);
8214     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8215                              << FSString,
8216                          E->getExprLoc(), false, CSR);
8217     return true;
8218   }
8219 
8220   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8221   if (Match == analyze_printf::ArgType::Match)
8222     return true;
8223 
8224   // Look through argument promotions for our error message's reported type.
8225   // This includes the integral and floating promotions, but excludes array
8226   // and function pointer decay (seeing that an argument intended to be a
8227   // string has type 'char [6]' is probably more confusing than 'char *') and
8228   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8229   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8230     if (isArithmeticArgumentPromotion(S, ICE)) {
8231       E = ICE->getSubExpr();
8232       ExprTy = E->getType();
8233 
8234       // Check if we didn't match because of an implicit cast from a 'char'
8235       // or 'short' to an 'int'.  This is done because printf is a varargs
8236       // function.
8237       if (ICE->getType() == S.Context.IntTy ||
8238           ICE->getType() == S.Context.UnsignedIntTy) {
8239         // All further checking is done on the subexpression
8240         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8241             AT.matchesType(S.Context, ExprTy);
8242         if (ImplicitMatch == analyze_printf::ArgType::Match)
8243           return true;
8244         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8245             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8246           Match = ImplicitMatch;
8247       }
8248     }
8249   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8250     // Special case for 'a', which has type 'int' in C.
8251     // Note, however, that we do /not/ want to treat multibyte constants like
8252     // 'MooV' as characters! This form is deprecated but still exists.
8253     if (ExprTy == S.Context.IntTy)
8254       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8255         ExprTy = S.Context.CharTy;
8256   }
8257 
8258   // Look through enums to their underlying type.
8259   bool IsEnum = false;
8260   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8261     ExprTy = EnumTy->getDecl()->getIntegerType();
8262     IsEnum = true;
8263   }
8264 
8265   // %C in an Objective-C context prints a unichar, not a wchar_t.
8266   // If the argument is an integer of some kind, believe the %C and suggest
8267   // a cast instead of changing the conversion specifier.
8268   QualType IntendedTy = ExprTy;
8269   if (isObjCContext() &&
8270       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8271     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8272         !ExprTy->isCharType()) {
8273       // 'unichar' is defined as a typedef of unsigned short, but we should
8274       // prefer using the typedef if it is visible.
8275       IntendedTy = S.Context.UnsignedShortTy;
8276 
8277       // While we are here, check if the value is an IntegerLiteral that happens
8278       // to be within the valid range.
8279       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8280         const llvm::APInt &V = IL->getValue();
8281         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8282           return true;
8283       }
8284 
8285       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8286                           Sema::LookupOrdinaryName);
8287       if (S.LookupName(Result, S.getCurScope())) {
8288         NamedDecl *ND = Result.getFoundDecl();
8289         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8290           if (TD->getUnderlyingType() == IntendedTy)
8291             IntendedTy = S.Context.getTypedefType(TD);
8292       }
8293     }
8294   }
8295 
8296   // Special-case some of Darwin's platform-independence types by suggesting
8297   // casts to primitive types that are known to be large enough.
8298   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8299   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8300     QualType CastTy;
8301     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8302     if (!CastTy.isNull()) {
8303       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8304       // (long in ASTContext). Only complain to pedants.
8305       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8306           (AT.isSizeT() || AT.isPtrdiffT()) &&
8307           AT.matchesType(S.Context, CastTy))
8308         Match = ArgType::NoMatchPedantic;
8309       IntendedTy = CastTy;
8310       ShouldNotPrintDirectly = true;
8311     }
8312   }
8313 
8314   // We may be able to offer a FixItHint if it is a supported type.
8315   PrintfSpecifier fixedFS = FS;
8316   bool Success =
8317       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8318 
8319   if (Success) {
8320     // Get the fix string from the fixed format specifier
8321     SmallString<16> buf;
8322     llvm::raw_svector_ostream os(buf);
8323     fixedFS.toString(os);
8324 
8325     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8326 
8327     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8328       unsigned Diag;
8329       switch (Match) {
8330       case ArgType::Match: llvm_unreachable("expected non-matching");
8331       case ArgType::NoMatchPedantic:
8332         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8333         break;
8334       case ArgType::NoMatchTypeConfusion:
8335         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8336         break;
8337       case ArgType::NoMatch:
8338         Diag = diag::warn_format_conversion_argument_type_mismatch;
8339         break;
8340       }
8341 
8342       // In this case, the specifier is wrong and should be changed to match
8343       // the argument.
8344       EmitFormatDiagnostic(S.PDiag(Diag)
8345                                << AT.getRepresentativeTypeName(S.Context)
8346                                << IntendedTy << IsEnum << E->getSourceRange(),
8347                            E->getBeginLoc(),
8348                            /*IsStringLocation*/ false, SpecRange,
8349                            FixItHint::CreateReplacement(SpecRange, os.str()));
8350     } else {
8351       // The canonical type for formatting this value is different from the
8352       // actual type of the expression. (This occurs, for example, with Darwin's
8353       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8354       // should be printed as 'long' for 64-bit compatibility.)
8355       // Rather than emitting a normal format/argument mismatch, we want to
8356       // add a cast to the recommended type (and correct the format string
8357       // if necessary).
8358       SmallString<16> CastBuf;
8359       llvm::raw_svector_ostream CastFix(CastBuf);
8360       CastFix << "(";
8361       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8362       CastFix << ")";
8363 
8364       SmallVector<FixItHint,4> Hints;
8365       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8366         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8367 
8368       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8369         // If there's already a cast present, just replace it.
8370         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8371         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8372 
8373       } else if (!requiresParensToAddCast(E)) {
8374         // If the expression has high enough precedence,
8375         // just write the C-style cast.
8376         Hints.push_back(
8377             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8378       } else {
8379         // Otherwise, add parens around the expression as well as the cast.
8380         CastFix << "(";
8381         Hints.push_back(
8382             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8383 
8384         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8385         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8386       }
8387 
8388       if (ShouldNotPrintDirectly) {
8389         // The expression has a type that should not be printed directly.
8390         // We extract the name from the typedef because we don't want to show
8391         // the underlying type in the diagnostic.
8392         StringRef Name;
8393         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8394           Name = TypedefTy->getDecl()->getName();
8395         else
8396           Name = CastTyName;
8397         unsigned Diag = Match == ArgType::NoMatchPedantic
8398                             ? diag::warn_format_argument_needs_cast_pedantic
8399                             : diag::warn_format_argument_needs_cast;
8400         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8401                                            << E->getSourceRange(),
8402                              E->getBeginLoc(), /*IsStringLocation=*/false,
8403                              SpecRange, Hints);
8404       } else {
8405         // In this case, the expression could be printed using a different
8406         // specifier, but we've decided that the specifier is probably correct
8407         // and we should cast instead. Just use the normal warning message.
8408         EmitFormatDiagnostic(
8409             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8410                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8411                 << E->getSourceRange(),
8412             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8413       }
8414     }
8415   } else {
8416     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8417                                                    SpecifierLen);
8418     // Since the warning for passing non-POD types to variadic functions
8419     // was deferred until now, we emit a warning for non-POD
8420     // arguments here.
8421     switch (S.isValidVarArgType(ExprTy)) {
8422     case Sema::VAK_Valid:
8423     case Sema::VAK_ValidInCXX11: {
8424       unsigned Diag;
8425       switch (Match) {
8426       case ArgType::Match: llvm_unreachable("expected non-matching");
8427       case ArgType::NoMatchPedantic:
8428         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8429         break;
8430       case ArgType::NoMatchTypeConfusion:
8431         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8432         break;
8433       case ArgType::NoMatch:
8434         Diag = diag::warn_format_conversion_argument_type_mismatch;
8435         break;
8436       }
8437 
8438       EmitFormatDiagnostic(
8439           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8440                         << IsEnum << CSR << E->getSourceRange(),
8441           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8442       break;
8443     }
8444     case Sema::VAK_Undefined:
8445     case Sema::VAK_MSVCUndefined:
8446       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8447                                << S.getLangOpts().CPlusPlus11 << ExprTy
8448                                << CallType
8449                                << AT.getRepresentativeTypeName(S.Context) << CSR
8450                                << E->getSourceRange(),
8451                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8452       checkForCStrMembers(AT, E);
8453       break;
8454 
8455     case Sema::VAK_Invalid:
8456       if (ExprTy->isObjCObjectType())
8457         EmitFormatDiagnostic(
8458             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8459                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8460                 << AT.getRepresentativeTypeName(S.Context) << CSR
8461                 << E->getSourceRange(),
8462             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8463       else
8464         // FIXME: If this is an initializer list, suggest removing the braces
8465         // or inserting a cast to the target type.
8466         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8467             << isa<InitListExpr>(E) << ExprTy << CallType
8468             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8469       break;
8470     }
8471 
8472     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8473            "format string specifier index out of range");
8474     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8475   }
8476 
8477   return true;
8478 }
8479 
8480 //===--- CHECK: Scanf format string checking ------------------------------===//
8481 
8482 namespace {
8483 
8484 class CheckScanfHandler : public CheckFormatHandler {
8485 public:
8486   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8487                     const Expr *origFormatExpr, Sema::FormatStringType type,
8488                     unsigned firstDataArg, unsigned numDataArgs,
8489                     const char *beg, bool hasVAListArg,
8490                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8491                     bool inFunctionCall, Sema::VariadicCallType CallType,
8492                     llvm::SmallBitVector &CheckedVarArgs,
8493                     UncoveredArgHandler &UncoveredArg)
8494       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8495                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8496                            inFunctionCall, CallType, CheckedVarArgs,
8497                            UncoveredArg) {}
8498 
8499   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8500                             const char *startSpecifier,
8501                             unsigned specifierLen) override;
8502 
8503   bool HandleInvalidScanfConversionSpecifier(
8504           const analyze_scanf::ScanfSpecifier &FS,
8505           const char *startSpecifier,
8506           unsigned specifierLen) override;
8507 
8508   void HandleIncompleteScanList(const char *start, const char *end) override;
8509 };
8510 
8511 } // namespace
8512 
8513 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8514                                                  const char *end) {
8515   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8516                        getLocationOfByte(end), /*IsStringLocation*/true,
8517                        getSpecifierRange(start, end - start));
8518 }
8519 
8520 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8521                                         const analyze_scanf::ScanfSpecifier &FS,
8522                                         const char *startSpecifier,
8523                                         unsigned specifierLen) {
8524   const analyze_scanf::ScanfConversionSpecifier &CS =
8525     FS.getConversionSpecifier();
8526 
8527   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8528                                           getLocationOfByte(CS.getStart()),
8529                                           startSpecifier, specifierLen,
8530                                           CS.getStart(), CS.getLength());
8531 }
8532 
8533 bool CheckScanfHandler::HandleScanfSpecifier(
8534                                        const analyze_scanf::ScanfSpecifier &FS,
8535                                        const char *startSpecifier,
8536                                        unsigned specifierLen) {
8537   using namespace analyze_scanf;
8538   using namespace analyze_format_string;
8539 
8540   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8541 
8542   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8543   // be used to decide if we are using positional arguments consistently.
8544   if (FS.consumesDataArgument()) {
8545     if (atFirstArg) {
8546       atFirstArg = false;
8547       usesPositionalArgs = FS.usesPositionalArg();
8548     }
8549     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8550       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8551                                         startSpecifier, specifierLen);
8552       return false;
8553     }
8554   }
8555 
8556   // Check if the field with is non-zero.
8557   const OptionalAmount &Amt = FS.getFieldWidth();
8558   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8559     if (Amt.getConstantAmount() == 0) {
8560       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8561                                                    Amt.getConstantLength());
8562       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8563                            getLocationOfByte(Amt.getStart()),
8564                            /*IsStringLocation*/true, R,
8565                            FixItHint::CreateRemoval(R));
8566     }
8567   }
8568 
8569   if (!FS.consumesDataArgument()) {
8570     // FIXME: Technically specifying a precision or field width here
8571     // makes no sense.  Worth issuing a warning at some point.
8572     return true;
8573   }
8574 
8575   // Consume the argument.
8576   unsigned argIndex = FS.getArgIndex();
8577   if (argIndex < NumDataArgs) {
8578       // The check to see if the argIndex is valid will come later.
8579       // We set the bit here because we may exit early from this
8580       // function if we encounter some other error.
8581     CoveredArgs.set(argIndex);
8582   }
8583 
8584   // Check the length modifier is valid with the given conversion specifier.
8585   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8586                                  S.getLangOpts()))
8587     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8588                                 diag::warn_format_nonsensical_length);
8589   else if (!FS.hasStandardLengthModifier())
8590     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8591   else if (!FS.hasStandardLengthConversionCombination())
8592     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8593                                 diag::warn_format_non_standard_conversion_spec);
8594 
8595   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8596     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8597 
8598   // The remaining checks depend on the data arguments.
8599   if (HasVAListArg)
8600     return true;
8601 
8602   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8603     return false;
8604 
8605   // Check that the argument type matches the format specifier.
8606   const Expr *Ex = getDataArg(argIndex);
8607   if (!Ex)
8608     return true;
8609 
8610   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8611 
8612   if (!AT.isValid()) {
8613     return true;
8614   }
8615 
8616   analyze_format_string::ArgType::MatchKind Match =
8617       AT.matchesType(S.Context, Ex->getType());
8618   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8619   if (Match == analyze_format_string::ArgType::Match)
8620     return true;
8621 
8622   ScanfSpecifier fixedFS = FS;
8623   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8624                                  S.getLangOpts(), S.Context);
8625 
8626   unsigned Diag =
8627       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8628                : diag::warn_format_conversion_argument_type_mismatch;
8629 
8630   if (Success) {
8631     // Get the fix string from the fixed format specifier.
8632     SmallString<128> buf;
8633     llvm::raw_svector_ostream os(buf);
8634     fixedFS.toString(os);
8635 
8636     EmitFormatDiagnostic(
8637         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8638                       << Ex->getType() << false << Ex->getSourceRange(),
8639         Ex->getBeginLoc(),
8640         /*IsStringLocation*/ false,
8641         getSpecifierRange(startSpecifier, specifierLen),
8642         FixItHint::CreateReplacement(
8643             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8644   } else {
8645     EmitFormatDiagnostic(S.PDiag(Diag)
8646                              << AT.getRepresentativeTypeName(S.Context)
8647                              << Ex->getType() << false << Ex->getSourceRange(),
8648                          Ex->getBeginLoc(),
8649                          /*IsStringLocation*/ false,
8650                          getSpecifierRange(startSpecifier, specifierLen));
8651   }
8652 
8653   return true;
8654 }
8655 
8656 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8657                               const Expr *OrigFormatExpr,
8658                               ArrayRef<const Expr *> Args,
8659                               bool HasVAListArg, unsigned format_idx,
8660                               unsigned firstDataArg,
8661                               Sema::FormatStringType Type,
8662                               bool inFunctionCall,
8663                               Sema::VariadicCallType CallType,
8664                               llvm::SmallBitVector &CheckedVarArgs,
8665                               UncoveredArgHandler &UncoveredArg,
8666                               bool IgnoreStringsWithoutSpecifiers) {
8667   // CHECK: is the format string a wide literal?
8668   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8669     CheckFormatHandler::EmitFormatDiagnostic(
8670         S, inFunctionCall, Args[format_idx],
8671         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8672         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8673     return;
8674   }
8675 
8676   // Str - The format string.  NOTE: this is NOT null-terminated!
8677   StringRef StrRef = FExpr->getString();
8678   const char *Str = StrRef.data();
8679   // Account for cases where the string literal is truncated in a declaration.
8680   const ConstantArrayType *T =
8681     S.Context.getAsConstantArrayType(FExpr->getType());
8682   assert(T && "String literal not of constant array type!");
8683   size_t TypeSize = T->getSize().getZExtValue();
8684   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8685   const unsigned numDataArgs = Args.size() - firstDataArg;
8686 
8687   if (IgnoreStringsWithoutSpecifiers &&
8688       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
8689           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
8690     return;
8691 
8692   // Emit a warning if the string literal is truncated and does not contain an
8693   // embedded null character.
8694   if (TypeSize <= StrRef.size() &&
8695       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8696     CheckFormatHandler::EmitFormatDiagnostic(
8697         S, inFunctionCall, Args[format_idx],
8698         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8699         FExpr->getBeginLoc(),
8700         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8701     return;
8702   }
8703 
8704   // CHECK: empty format string?
8705   if (StrLen == 0 && numDataArgs > 0) {
8706     CheckFormatHandler::EmitFormatDiagnostic(
8707         S, inFunctionCall, Args[format_idx],
8708         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8709         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8710     return;
8711   }
8712 
8713   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8714       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8715       Type == Sema::FST_OSTrace) {
8716     CheckPrintfHandler H(
8717         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8718         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8719         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8720         CheckedVarArgs, UncoveredArg);
8721 
8722     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8723                                                   S.getLangOpts(),
8724                                                   S.Context.getTargetInfo(),
8725                                             Type == Sema::FST_FreeBSDKPrintf))
8726       H.DoneProcessing();
8727   } else if (Type == Sema::FST_Scanf) {
8728     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8729                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8730                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8731 
8732     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8733                                                  S.getLangOpts(),
8734                                                  S.Context.getTargetInfo()))
8735       H.DoneProcessing();
8736   } // TODO: handle other formats
8737 }
8738 
8739 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8740   // Str - The format string.  NOTE: this is NOT null-terminated!
8741   StringRef StrRef = FExpr->getString();
8742   const char *Str = StrRef.data();
8743   // Account for cases where the string literal is truncated in a declaration.
8744   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8745   assert(T && "String literal not of constant array type!");
8746   size_t TypeSize = T->getSize().getZExtValue();
8747   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8748   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8749                                                          getLangOpts(),
8750                                                          Context.getTargetInfo());
8751 }
8752 
8753 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8754 
8755 // Returns the related absolute value function that is larger, of 0 if one
8756 // does not exist.
8757 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8758   switch (AbsFunction) {
8759   default:
8760     return 0;
8761 
8762   case Builtin::BI__builtin_abs:
8763     return Builtin::BI__builtin_labs;
8764   case Builtin::BI__builtin_labs:
8765     return Builtin::BI__builtin_llabs;
8766   case Builtin::BI__builtin_llabs:
8767     return 0;
8768 
8769   case Builtin::BI__builtin_fabsf:
8770     return Builtin::BI__builtin_fabs;
8771   case Builtin::BI__builtin_fabs:
8772     return Builtin::BI__builtin_fabsl;
8773   case Builtin::BI__builtin_fabsl:
8774     return 0;
8775 
8776   case Builtin::BI__builtin_cabsf:
8777     return Builtin::BI__builtin_cabs;
8778   case Builtin::BI__builtin_cabs:
8779     return Builtin::BI__builtin_cabsl;
8780   case Builtin::BI__builtin_cabsl:
8781     return 0;
8782 
8783   case Builtin::BIabs:
8784     return Builtin::BIlabs;
8785   case Builtin::BIlabs:
8786     return Builtin::BIllabs;
8787   case Builtin::BIllabs:
8788     return 0;
8789 
8790   case Builtin::BIfabsf:
8791     return Builtin::BIfabs;
8792   case Builtin::BIfabs:
8793     return Builtin::BIfabsl;
8794   case Builtin::BIfabsl:
8795     return 0;
8796 
8797   case Builtin::BIcabsf:
8798    return Builtin::BIcabs;
8799   case Builtin::BIcabs:
8800     return Builtin::BIcabsl;
8801   case Builtin::BIcabsl:
8802     return 0;
8803   }
8804 }
8805 
8806 // Returns the argument type of the absolute value function.
8807 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8808                                              unsigned AbsType) {
8809   if (AbsType == 0)
8810     return QualType();
8811 
8812   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8813   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8814   if (Error != ASTContext::GE_None)
8815     return QualType();
8816 
8817   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8818   if (!FT)
8819     return QualType();
8820 
8821   if (FT->getNumParams() != 1)
8822     return QualType();
8823 
8824   return FT->getParamType(0);
8825 }
8826 
8827 // Returns the best absolute value function, or zero, based on type and
8828 // current absolute value function.
8829 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8830                                    unsigned AbsFunctionKind) {
8831   unsigned BestKind = 0;
8832   uint64_t ArgSize = Context.getTypeSize(ArgType);
8833   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8834        Kind = getLargerAbsoluteValueFunction(Kind)) {
8835     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8836     if (Context.getTypeSize(ParamType) >= ArgSize) {
8837       if (BestKind == 0)
8838         BestKind = Kind;
8839       else if (Context.hasSameType(ParamType, ArgType)) {
8840         BestKind = Kind;
8841         break;
8842       }
8843     }
8844   }
8845   return BestKind;
8846 }
8847 
8848 enum AbsoluteValueKind {
8849   AVK_Integer,
8850   AVK_Floating,
8851   AVK_Complex
8852 };
8853 
8854 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8855   if (T->isIntegralOrEnumerationType())
8856     return AVK_Integer;
8857   if (T->isRealFloatingType())
8858     return AVK_Floating;
8859   if (T->isAnyComplexType())
8860     return AVK_Complex;
8861 
8862   llvm_unreachable("Type not integer, floating, or complex");
8863 }
8864 
8865 // Changes the absolute value function to a different type.  Preserves whether
8866 // the function is a builtin.
8867 static unsigned changeAbsFunction(unsigned AbsKind,
8868                                   AbsoluteValueKind ValueKind) {
8869   switch (ValueKind) {
8870   case AVK_Integer:
8871     switch (AbsKind) {
8872     default:
8873       return 0;
8874     case Builtin::BI__builtin_fabsf:
8875     case Builtin::BI__builtin_fabs:
8876     case Builtin::BI__builtin_fabsl:
8877     case Builtin::BI__builtin_cabsf:
8878     case Builtin::BI__builtin_cabs:
8879     case Builtin::BI__builtin_cabsl:
8880       return Builtin::BI__builtin_abs;
8881     case Builtin::BIfabsf:
8882     case Builtin::BIfabs:
8883     case Builtin::BIfabsl:
8884     case Builtin::BIcabsf:
8885     case Builtin::BIcabs:
8886     case Builtin::BIcabsl:
8887       return Builtin::BIabs;
8888     }
8889   case AVK_Floating:
8890     switch (AbsKind) {
8891     default:
8892       return 0;
8893     case Builtin::BI__builtin_abs:
8894     case Builtin::BI__builtin_labs:
8895     case Builtin::BI__builtin_llabs:
8896     case Builtin::BI__builtin_cabsf:
8897     case Builtin::BI__builtin_cabs:
8898     case Builtin::BI__builtin_cabsl:
8899       return Builtin::BI__builtin_fabsf;
8900     case Builtin::BIabs:
8901     case Builtin::BIlabs:
8902     case Builtin::BIllabs:
8903     case Builtin::BIcabsf:
8904     case Builtin::BIcabs:
8905     case Builtin::BIcabsl:
8906       return Builtin::BIfabsf;
8907     }
8908   case AVK_Complex:
8909     switch (AbsKind) {
8910     default:
8911       return 0;
8912     case Builtin::BI__builtin_abs:
8913     case Builtin::BI__builtin_labs:
8914     case Builtin::BI__builtin_llabs:
8915     case Builtin::BI__builtin_fabsf:
8916     case Builtin::BI__builtin_fabs:
8917     case Builtin::BI__builtin_fabsl:
8918       return Builtin::BI__builtin_cabsf;
8919     case Builtin::BIabs:
8920     case Builtin::BIlabs:
8921     case Builtin::BIllabs:
8922     case Builtin::BIfabsf:
8923     case Builtin::BIfabs:
8924     case Builtin::BIfabsl:
8925       return Builtin::BIcabsf;
8926     }
8927   }
8928   llvm_unreachable("Unable to convert function");
8929 }
8930 
8931 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8932   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8933   if (!FnInfo)
8934     return 0;
8935 
8936   switch (FDecl->getBuiltinID()) {
8937   default:
8938     return 0;
8939   case Builtin::BI__builtin_abs:
8940   case Builtin::BI__builtin_fabs:
8941   case Builtin::BI__builtin_fabsf:
8942   case Builtin::BI__builtin_fabsl:
8943   case Builtin::BI__builtin_labs:
8944   case Builtin::BI__builtin_llabs:
8945   case Builtin::BI__builtin_cabs:
8946   case Builtin::BI__builtin_cabsf:
8947   case Builtin::BI__builtin_cabsl:
8948   case Builtin::BIabs:
8949   case Builtin::BIlabs:
8950   case Builtin::BIllabs:
8951   case Builtin::BIfabs:
8952   case Builtin::BIfabsf:
8953   case Builtin::BIfabsl:
8954   case Builtin::BIcabs:
8955   case Builtin::BIcabsf:
8956   case Builtin::BIcabsl:
8957     return FDecl->getBuiltinID();
8958   }
8959   llvm_unreachable("Unknown Builtin type");
8960 }
8961 
8962 // If the replacement is valid, emit a note with replacement function.
8963 // Additionally, suggest including the proper header if not already included.
8964 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8965                             unsigned AbsKind, QualType ArgType) {
8966   bool EmitHeaderHint = true;
8967   const char *HeaderName = nullptr;
8968   const char *FunctionName = nullptr;
8969   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8970     FunctionName = "std::abs";
8971     if (ArgType->isIntegralOrEnumerationType()) {
8972       HeaderName = "cstdlib";
8973     } else if (ArgType->isRealFloatingType()) {
8974       HeaderName = "cmath";
8975     } else {
8976       llvm_unreachable("Invalid Type");
8977     }
8978 
8979     // Lookup all std::abs
8980     if (NamespaceDecl *Std = S.getStdNamespace()) {
8981       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8982       R.suppressDiagnostics();
8983       S.LookupQualifiedName(R, Std);
8984 
8985       for (const auto *I : R) {
8986         const FunctionDecl *FDecl = nullptr;
8987         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8988           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8989         } else {
8990           FDecl = dyn_cast<FunctionDecl>(I);
8991         }
8992         if (!FDecl)
8993           continue;
8994 
8995         // Found std::abs(), check that they are the right ones.
8996         if (FDecl->getNumParams() != 1)
8997           continue;
8998 
8999         // Check that the parameter type can handle the argument.
9000         QualType ParamType = FDecl->getParamDecl(0)->getType();
9001         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9002             S.Context.getTypeSize(ArgType) <=
9003                 S.Context.getTypeSize(ParamType)) {
9004           // Found a function, don't need the header hint.
9005           EmitHeaderHint = false;
9006           break;
9007         }
9008       }
9009     }
9010   } else {
9011     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9012     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9013 
9014     if (HeaderName) {
9015       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9016       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9017       R.suppressDiagnostics();
9018       S.LookupName(R, S.getCurScope());
9019 
9020       if (R.isSingleResult()) {
9021         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9022         if (FD && FD->getBuiltinID() == AbsKind) {
9023           EmitHeaderHint = false;
9024         } else {
9025           return;
9026         }
9027       } else if (!R.empty()) {
9028         return;
9029       }
9030     }
9031   }
9032 
9033   S.Diag(Loc, diag::note_replace_abs_function)
9034       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9035 
9036   if (!HeaderName)
9037     return;
9038 
9039   if (!EmitHeaderHint)
9040     return;
9041 
9042   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9043                                                     << FunctionName;
9044 }
9045 
9046 template <std::size_t StrLen>
9047 static bool IsStdFunction(const FunctionDecl *FDecl,
9048                           const char (&Str)[StrLen]) {
9049   if (!FDecl)
9050     return false;
9051   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9052     return false;
9053   if (!FDecl->isInStdNamespace())
9054     return false;
9055 
9056   return true;
9057 }
9058 
9059 // Warn when using the wrong abs() function.
9060 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9061                                       const FunctionDecl *FDecl) {
9062   if (Call->getNumArgs() != 1)
9063     return;
9064 
9065   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9066   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9067   if (AbsKind == 0 && !IsStdAbs)
9068     return;
9069 
9070   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9071   QualType ParamType = Call->getArg(0)->getType();
9072 
9073   // Unsigned types cannot be negative.  Suggest removing the absolute value
9074   // function call.
9075   if (ArgType->isUnsignedIntegerType()) {
9076     const char *FunctionName =
9077         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9078     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9079     Diag(Call->getExprLoc(), diag::note_remove_abs)
9080         << FunctionName
9081         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9082     return;
9083   }
9084 
9085   // Taking the absolute value of a pointer is very suspicious, they probably
9086   // wanted to index into an array, dereference a pointer, call a function, etc.
9087   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9088     unsigned DiagType = 0;
9089     if (ArgType->isFunctionType())
9090       DiagType = 1;
9091     else if (ArgType->isArrayType())
9092       DiagType = 2;
9093 
9094     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9095     return;
9096   }
9097 
9098   // std::abs has overloads which prevent most of the absolute value problems
9099   // from occurring.
9100   if (IsStdAbs)
9101     return;
9102 
9103   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9104   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9105 
9106   // The argument and parameter are the same kind.  Check if they are the right
9107   // size.
9108   if (ArgValueKind == ParamValueKind) {
9109     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9110       return;
9111 
9112     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9113     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9114         << FDecl << ArgType << ParamType;
9115 
9116     if (NewAbsKind == 0)
9117       return;
9118 
9119     emitReplacement(*this, Call->getExprLoc(),
9120                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9121     return;
9122   }
9123 
9124   // ArgValueKind != ParamValueKind
9125   // The wrong type of absolute value function was used.  Attempt to find the
9126   // proper one.
9127   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9128   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9129   if (NewAbsKind == 0)
9130     return;
9131 
9132   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9133       << FDecl << ParamValueKind << ArgValueKind;
9134 
9135   emitReplacement(*this, Call->getExprLoc(),
9136                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9137 }
9138 
9139 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9140 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9141                                 const FunctionDecl *FDecl) {
9142   if (!Call || !FDecl) return;
9143 
9144   // Ignore template specializations and macros.
9145   if (inTemplateInstantiation()) return;
9146   if (Call->getExprLoc().isMacroID()) return;
9147 
9148   // Only care about the one template argument, two function parameter std::max
9149   if (Call->getNumArgs() != 2) return;
9150   if (!IsStdFunction(FDecl, "max")) return;
9151   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9152   if (!ArgList) return;
9153   if (ArgList->size() != 1) return;
9154 
9155   // Check that template type argument is unsigned integer.
9156   const auto& TA = ArgList->get(0);
9157   if (TA.getKind() != TemplateArgument::Type) return;
9158   QualType ArgType = TA.getAsType();
9159   if (!ArgType->isUnsignedIntegerType()) return;
9160 
9161   // See if either argument is a literal zero.
9162   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9163     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9164     if (!MTE) return false;
9165     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
9166     if (!Num) return false;
9167     if (Num->getValue() != 0) return false;
9168     return true;
9169   };
9170 
9171   const Expr *FirstArg = Call->getArg(0);
9172   const Expr *SecondArg = Call->getArg(1);
9173   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9174   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9175 
9176   // Only warn when exactly one argument is zero.
9177   if (IsFirstArgZero == IsSecondArgZero) return;
9178 
9179   SourceRange FirstRange = FirstArg->getSourceRange();
9180   SourceRange SecondRange = SecondArg->getSourceRange();
9181 
9182   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9183 
9184   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9185       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9186 
9187   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9188   SourceRange RemovalRange;
9189   if (IsFirstArgZero) {
9190     RemovalRange = SourceRange(FirstRange.getBegin(),
9191                                SecondRange.getBegin().getLocWithOffset(-1));
9192   } else {
9193     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9194                                SecondRange.getEnd());
9195   }
9196 
9197   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9198         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9199         << FixItHint::CreateRemoval(RemovalRange);
9200 }
9201 
9202 //===--- CHECK: Standard memory functions ---------------------------------===//
9203 
9204 /// Takes the expression passed to the size_t parameter of functions
9205 /// such as memcmp, strncat, etc and warns if it's a comparison.
9206 ///
9207 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9208 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9209                                            IdentifierInfo *FnName,
9210                                            SourceLocation FnLoc,
9211                                            SourceLocation RParenLoc) {
9212   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9213   if (!Size)
9214     return false;
9215 
9216   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9217   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9218     return false;
9219 
9220   SourceRange SizeRange = Size->getSourceRange();
9221   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9222       << SizeRange << FnName;
9223   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9224       << FnName
9225       << FixItHint::CreateInsertion(
9226              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9227       << FixItHint::CreateRemoval(RParenLoc);
9228   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9229       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9230       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9231                                     ")");
9232 
9233   return true;
9234 }
9235 
9236 /// Determine whether the given type is or contains a dynamic class type
9237 /// (e.g., whether it has a vtable).
9238 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9239                                                      bool &IsContained) {
9240   // Look through array types while ignoring qualifiers.
9241   const Type *Ty = T->getBaseElementTypeUnsafe();
9242   IsContained = false;
9243 
9244   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9245   RD = RD ? RD->getDefinition() : nullptr;
9246   if (!RD || RD->isInvalidDecl())
9247     return nullptr;
9248 
9249   if (RD->isDynamicClass())
9250     return RD;
9251 
9252   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9253   // It's impossible for a class to transitively contain itself by value, so
9254   // infinite recursion is impossible.
9255   for (auto *FD : RD->fields()) {
9256     bool SubContained;
9257     if (const CXXRecordDecl *ContainedRD =
9258             getContainedDynamicClass(FD->getType(), SubContained)) {
9259       IsContained = true;
9260       return ContainedRD;
9261     }
9262   }
9263 
9264   return nullptr;
9265 }
9266 
9267 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9268   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9269     if (Unary->getKind() == UETT_SizeOf)
9270       return Unary;
9271   return nullptr;
9272 }
9273 
9274 /// If E is a sizeof expression, returns its argument expression,
9275 /// otherwise returns NULL.
9276 static const Expr *getSizeOfExprArg(const Expr *E) {
9277   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9278     if (!SizeOf->isArgumentType())
9279       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9280   return nullptr;
9281 }
9282 
9283 /// If E is a sizeof expression, returns its argument type.
9284 static QualType getSizeOfArgType(const Expr *E) {
9285   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9286     return SizeOf->getTypeOfArgument();
9287   return QualType();
9288 }
9289 
9290 namespace {
9291 
9292 struct SearchNonTrivialToInitializeField
9293     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9294   using Super =
9295       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9296 
9297   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9298 
9299   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9300                      SourceLocation SL) {
9301     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9302       asDerived().visitArray(PDIK, AT, SL);
9303       return;
9304     }
9305 
9306     Super::visitWithKind(PDIK, FT, SL);
9307   }
9308 
9309   void visitARCStrong(QualType FT, SourceLocation SL) {
9310     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9311   }
9312   void visitARCWeak(QualType FT, SourceLocation SL) {
9313     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9314   }
9315   void visitStruct(QualType FT, SourceLocation SL) {
9316     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9317       visit(FD->getType(), FD->getLocation());
9318   }
9319   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9320                   const ArrayType *AT, SourceLocation SL) {
9321     visit(getContext().getBaseElementType(AT), SL);
9322   }
9323   void visitTrivial(QualType FT, SourceLocation SL) {}
9324 
9325   static void diag(QualType RT, const Expr *E, Sema &S) {
9326     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9327   }
9328 
9329   ASTContext &getContext() { return S.getASTContext(); }
9330 
9331   const Expr *E;
9332   Sema &S;
9333 };
9334 
9335 struct SearchNonTrivialToCopyField
9336     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9337   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9338 
9339   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9340 
9341   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9342                      SourceLocation SL) {
9343     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9344       asDerived().visitArray(PCK, AT, SL);
9345       return;
9346     }
9347 
9348     Super::visitWithKind(PCK, FT, SL);
9349   }
9350 
9351   void visitARCStrong(QualType FT, SourceLocation SL) {
9352     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9353   }
9354   void visitARCWeak(QualType FT, SourceLocation SL) {
9355     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9356   }
9357   void visitStruct(QualType FT, SourceLocation SL) {
9358     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9359       visit(FD->getType(), FD->getLocation());
9360   }
9361   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9362                   SourceLocation SL) {
9363     visit(getContext().getBaseElementType(AT), SL);
9364   }
9365   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9366                 SourceLocation SL) {}
9367   void visitTrivial(QualType FT, SourceLocation SL) {}
9368   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9369 
9370   static void diag(QualType RT, const Expr *E, Sema &S) {
9371     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9372   }
9373 
9374   ASTContext &getContext() { return S.getASTContext(); }
9375 
9376   const Expr *E;
9377   Sema &S;
9378 };
9379 
9380 }
9381 
9382 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9383 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9384   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9385 
9386   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9387     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9388       return false;
9389 
9390     return doesExprLikelyComputeSize(BO->getLHS()) ||
9391            doesExprLikelyComputeSize(BO->getRHS());
9392   }
9393 
9394   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9395 }
9396 
9397 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9398 ///
9399 /// \code
9400 ///   #define MACRO 0
9401 ///   foo(MACRO);
9402 ///   foo(0);
9403 /// \endcode
9404 ///
9405 /// This should return true for the first call to foo, but not for the second
9406 /// (regardless of whether foo is a macro or function).
9407 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9408                                         SourceLocation CallLoc,
9409                                         SourceLocation ArgLoc) {
9410   if (!CallLoc.isMacroID())
9411     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9412 
9413   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9414          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9415 }
9416 
9417 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9418 /// last two arguments transposed.
9419 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9420   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9421     return;
9422 
9423   const Expr *SizeArg =
9424     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9425 
9426   auto isLiteralZero = [](const Expr *E) {
9427     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9428   };
9429 
9430   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9431   SourceLocation CallLoc = Call->getRParenLoc();
9432   SourceManager &SM = S.getSourceManager();
9433   if (isLiteralZero(SizeArg) &&
9434       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9435 
9436     SourceLocation DiagLoc = SizeArg->getExprLoc();
9437 
9438     // Some platforms #define bzero to __builtin_memset. See if this is the
9439     // case, and if so, emit a better diagnostic.
9440     if (BId == Builtin::BIbzero ||
9441         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9442                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9443       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9444       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9445     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9446       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9447       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9448     }
9449     return;
9450   }
9451 
9452   // If the second argument to a memset is a sizeof expression and the third
9453   // isn't, this is also likely an error. This should catch
9454   // 'memset(buf, sizeof(buf), 0xff)'.
9455   if (BId == Builtin::BImemset &&
9456       doesExprLikelyComputeSize(Call->getArg(1)) &&
9457       !doesExprLikelyComputeSize(Call->getArg(2))) {
9458     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9459     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9460     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9461     return;
9462   }
9463 }
9464 
9465 /// Check for dangerous or invalid arguments to memset().
9466 ///
9467 /// This issues warnings on known problematic, dangerous or unspecified
9468 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9469 /// function calls.
9470 ///
9471 /// \param Call The call expression to diagnose.
9472 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9473                                    unsigned BId,
9474                                    IdentifierInfo *FnName) {
9475   assert(BId != 0);
9476 
9477   // It is possible to have a non-standard definition of memset.  Validate
9478   // we have enough arguments, and if not, abort further checking.
9479   unsigned ExpectedNumArgs =
9480       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9481   if (Call->getNumArgs() < ExpectedNumArgs)
9482     return;
9483 
9484   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9485                       BId == Builtin::BIstrndup ? 1 : 2);
9486   unsigned LenArg =
9487       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9488   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9489 
9490   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9491                                      Call->getBeginLoc(), Call->getRParenLoc()))
9492     return;
9493 
9494   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9495   CheckMemaccessSize(*this, BId, Call);
9496 
9497   // We have special checking when the length is a sizeof expression.
9498   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9499   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9500   llvm::FoldingSetNodeID SizeOfArgID;
9501 
9502   // Although widely used, 'bzero' is not a standard function. Be more strict
9503   // with the argument types before allowing diagnostics and only allow the
9504   // form bzero(ptr, sizeof(...)).
9505   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9506   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9507     return;
9508 
9509   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9510     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9511     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9512 
9513     QualType DestTy = Dest->getType();
9514     QualType PointeeTy;
9515     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9516       PointeeTy = DestPtrTy->getPointeeType();
9517 
9518       // Never warn about void type pointers. This can be used to suppress
9519       // false positives.
9520       if (PointeeTy->isVoidType())
9521         continue;
9522 
9523       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9524       // actually comparing the expressions for equality. Because computing the
9525       // expression IDs can be expensive, we only do this if the diagnostic is
9526       // enabled.
9527       if (SizeOfArg &&
9528           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9529                            SizeOfArg->getExprLoc())) {
9530         // We only compute IDs for expressions if the warning is enabled, and
9531         // cache the sizeof arg's ID.
9532         if (SizeOfArgID == llvm::FoldingSetNodeID())
9533           SizeOfArg->Profile(SizeOfArgID, Context, true);
9534         llvm::FoldingSetNodeID DestID;
9535         Dest->Profile(DestID, Context, true);
9536         if (DestID == SizeOfArgID) {
9537           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9538           //       over sizeof(src) as well.
9539           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9540           StringRef ReadableName = FnName->getName();
9541 
9542           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9543             if (UnaryOp->getOpcode() == UO_AddrOf)
9544               ActionIdx = 1; // If its an address-of operator, just remove it.
9545           if (!PointeeTy->isIncompleteType() &&
9546               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9547             ActionIdx = 2; // If the pointee's size is sizeof(char),
9548                            // suggest an explicit length.
9549 
9550           // If the function is defined as a builtin macro, do not show macro
9551           // expansion.
9552           SourceLocation SL = SizeOfArg->getExprLoc();
9553           SourceRange DSR = Dest->getSourceRange();
9554           SourceRange SSR = SizeOfArg->getSourceRange();
9555           SourceManager &SM = getSourceManager();
9556 
9557           if (SM.isMacroArgExpansion(SL)) {
9558             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9559             SL = SM.getSpellingLoc(SL);
9560             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9561                              SM.getSpellingLoc(DSR.getEnd()));
9562             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9563                              SM.getSpellingLoc(SSR.getEnd()));
9564           }
9565 
9566           DiagRuntimeBehavior(SL, SizeOfArg,
9567                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9568                                 << ReadableName
9569                                 << PointeeTy
9570                                 << DestTy
9571                                 << DSR
9572                                 << SSR);
9573           DiagRuntimeBehavior(SL, SizeOfArg,
9574                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9575                                 << ActionIdx
9576                                 << SSR);
9577 
9578           break;
9579         }
9580       }
9581 
9582       // Also check for cases where the sizeof argument is the exact same
9583       // type as the memory argument, and where it points to a user-defined
9584       // record type.
9585       if (SizeOfArgTy != QualType()) {
9586         if (PointeeTy->isRecordType() &&
9587             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9588           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9589                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9590                                 << FnName << SizeOfArgTy << ArgIdx
9591                                 << PointeeTy << Dest->getSourceRange()
9592                                 << LenExpr->getSourceRange());
9593           break;
9594         }
9595       }
9596     } else if (DestTy->isArrayType()) {
9597       PointeeTy = DestTy;
9598     }
9599 
9600     if (PointeeTy == QualType())
9601       continue;
9602 
9603     // Always complain about dynamic classes.
9604     bool IsContained;
9605     if (const CXXRecordDecl *ContainedRD =
9606             getContainedDynamicClass(PointeeTy, IsContained)) {
9607 
9608       unsigned OperationType = 0;
9609       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9610       // "overwritten" if we're warning about the destination for any call
9611       // but memcmp; otherwise a verb appropriate to the call.
9612       if (ArgIdx != 0 || IsCmp) {
9613         if (BId == Builtin::BImemcpy)
9614           OperationType = 1;
9615         else if(BId == Builtin::BImemmove)
9616           OperationType = 2;
9617         else if (IsCmp)
9618           OperationType = 3;
9619       }
9620 
9621       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9622                           PDiag(diag::warn_dyn_class_memaccess)
9623                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9624                               << IsContained << ContainedRD << OperationType
9625                               << Call->getCallee()->getSourceRange());
9626     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9627              BId != Builtin::BImemset)
9628       DiagRuntimeBehavior(
9629         Dest->getExprLoc(), Dest,
9630         PDiag(diag::warn_arc_object_memaccess)
9631           << ArgIdx << FnName << PointeeTy
9632           << Call->getCallee()->getSourceRange());
9633     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9634       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9635           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9636         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9637                             PDiag(diag::warn_cstruct_memaccess)
9638                                 << ArgIdx << FnName << PointeeTy << 0);
9639         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9640       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9641                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9642         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9643                             PDiag(diag::warn_cstruct_memaccess)
9644                                 << ArgIdx << FnName << PointeeTy << 1);
9645         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9646       } else {
9647         continue;
9648       }
9649     } else
9650       continue;
9651 
9652     DiagRuntimeBehavior(
9653       Dest->getExprLoc(), Dest,
9654       PDiag(diag::note_bad_memaccess_silence)
9655         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9656     break;
9657   }
9658 }
9659 
9660 // A little helper routine: ignore addition and subtraction of integer literals.
9661 // This intentionally does not ignore all integer constant expressions because
9662 // we don't want to remove sizeof().
9663 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9664   Ex = Ex->IgnoreParenCasts();
9665 
9666   while (true) {
9667     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9668     if (!BO || !BO->isAdditiveOp())
9669       break;
9670 
9671     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9672     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9673 
9674     if (isa<IntegerLiteral>(RHS))
9675       Ex = LHS;
9676     else if (isa<IntegerLiteral>(LHS))
9677       Ex = RHS;
9678     else
9679       break;
9680   }
9681 
9682   return Ex;
9683 }
9684 
9685 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9686                                                       ASTContext &Context) {
9687   // Only handle constant-sized or VLAs, but not flexible members.
9688   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9689     // Only issue the FIXIT for arrays of size > 1.
9690     if (CAT->getSize().getSExtValue() <= 1)
9691       return false;
9692   } else if (!Ty->isVariableArrayType()) {
9693     return false;
9694   }
9695   return true;
9696 }
9697 
9698 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9699 // be the size of the source, instead of the destination.
9700 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9701                                     IdentifierInfo *FnName) {
9702 
9703   // Don't crash if the user has the wrong number of arguments
9704   unsigned NumArgs = Call->getNumArgs();
9705   if ((NumArgs != 3) && (NumArgs != 4))
9706     return;
9707 
9708   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9709   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9710   const Expr *CompareWithSrc = nullptr;
9711 
9712   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9713                                      Call->getBeginLoc(), Call->getRParenLoc()))
9714     return;
9715 
9716   // Look for 'strlcpy(dst, x, sizeof(x))'
9717   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9718     CompareWithSrc = Ex;
9719   else {
9720     // Look for 'strlcpy(dst, x, strlen(x))'
9721     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9722       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9723           SizeCall->getNumArgs() == 1)
9724         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9725     }
9726   }
9727 
9728   if (!CompareWithSrc)
9729     return;
9730 
9731   // Determine if the argument to sizeof/strlen is equal to the source
9732   // argument.  In principle there's all kinds of things you could do
9733   // here, for instance creating an == expression and evaluating it with
9734   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9735   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9736   if (!SrcArgDRE)
9737     return;
9738 
9739   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9740   if (!CompareWithSrcDRE ||
9741       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9742     return;
9743 
9744   const Expr *OriginalSizeArg = Call->getArg(2);
9745   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9746       << OriginalSizeArg->getSourceRange() << FnName;
9747 
9748   // Output a FIXIT hint if the destination is an array (rather than a
9749   // pointer to an array).  This could be enhanced to handle some
9750   // pointers if we know the actual size, like if DstArg is 'array+2'
9751   // we could say 'sizeof(array)-2'.
9752   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9753   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9754     return;
9755 
9756   SmallString<128> sizeString;
9757   llvm::raw_svector_ostream OS(sizeString);
9758   OS << "sizeof(";
9759   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9760   OS << ")";
9761 
9762   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9763       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9764                                       OS.str());
9765 }
9766 
9767 /// Check if two expressions refer to the same declaration.
9768 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9769   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9770     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9771       return D1->getDecl() == D2->getDecl();
9772   return false;
9773 }
9774 
9775 static const Expr *getStrlenExprArg(const Expr *E) {
9776   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9777     const FunctionDecl *FD = CE->getDirectCallee();
9778     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9779       return nullptr;
9780     return CE->getArg(0)->IgnoreParenCasts();
9781   }
9782   return nullptr;
9783 }
9784 
9785 // Warn on anti-patterns as the 'size' argument to strncat.
9786 // The correct size argument should look like following:
9787 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9788 void Sema::CheckStrncatArguments(const CallExpr *CE,
9789                                  IdentifierInfo *FnName) {
9790   // Don't crash if the user has the wrong number of arguments.
9791   if (CE->getNumArgs() < 3)
9792     return;
9793   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9794   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9795   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9796 
9797   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9798                                      CE->getRParenLoc()))
9799     return;
9800 
9801   // Identify common expressions, which are wrongly used as the size argument
9802   // to strncat and may lead to buffer overflows.
9803   unsigned PatternType = 0;
9804   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9805     // - sizeof(dst)
9806     if (referToTheSameDecl(SizeOfArg, DstArg))
9807       PatternType = 1;
9808     // - sizeof(src)
9809     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9810       PatternType = 2;
9811   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9812     if (BE->getOpcode() == BO_Sub) {
9813       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9814       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9815       // - sizeof(dst) - strlen(dst)
9816       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9817           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9818         PatternType = 1;
9819       // - sizeof(src) - (anything)
9820       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9821         PatternType = 2;
9822     }
9823   }
9824 
9825   if (PatternType == 0)
9826     return;
9827 
9828   // Generate the diagnostic.
9829   SourceLocation SL = LenArg->getBeginLoc();
9830   SourceRange SR = LenArg->getSourceRange();
9831   SourceManager &SM = getSourceManager();
9832 
9833   // If the function is defined as a builtin macro, do not show macro expansion.
9834   if (SM.isMacroArgExpansion(SL)) {
9835     SL = SM.getSpellingLoc(SL);
9836     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9837                      SM.getSpellingLoc(SR.getEnd()));
9838   }
9839 
9840   // Check if the destination is an array (rather than a pointer to an array).
9841   QualType DstTy = DstArg->getType();
9842   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9843                                                                     Context);
9844   if (!isKnownSizeArray) {
9845     if (PatternType == 1)
9846       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9847     else
9848       Diag(SL, diag::warn_strncat_src_size) << SR;
9849     return;
9850   }
9851 
9852   if (PatternType == 1)
9853     Diag(SL, diag::warn_strncat_large_size) << SR;
9854   else
9855     Diag(SL, diag::warn_strncat_src_size) << SR;
9856 
9857   SmallString<128> sizeString;
9858   llvm::raw_svector_ostream OS(sizeString);
9859   OS << "sizeof(";
9860   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9861   OS << ") - ";
9862   OS << "strlen(";
9863   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9864   OS << ") - 1";
9865 
9866   Diag(SL, diag::note_strncat_wrong_size)
9867     << FixItHint::CreateReplacement(SR, OS.str());
9868 }
9869 
9870 void
9871 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9872                          SourceLocation ReturnLoc,
9873                          bool isObjCMethod,
9874                          const AttrVec *Attrs,
9875                          const FunctionDecl *FD) {
9876   // Check if the return value is null but should not be.
9877   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9878        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9879       CheckNonNullExpr(*this, RetValExp))
9880     Diag(ReturnLoc, diag::warn_null_ret)
9881       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9882 
9883   // C++11 [basic.stc.dynamic.allocation]p4:
9884   //   If an allocation function declared with a non-throwing
9885   //   exception-specification fails to allocate storage, it shall return
9886   //   a null pointer. Any other allocation function that fails to allocate
9887   //   storage shall indicate failure only by throwing an exception [...]
9888   if (FD) {
9889     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9890     if (Op == OO_New || Op == OO_Array_New) {
9891       const FunctionProtoType *Proto
9892         = FD->getType()->castAs<FunctionProtoType>();
9893       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9894           CheckNonNullExpr(*this, RetValExp))
9895         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9896           << FD << getLangOpts().CPlusPlus11;
9897     }
9898   }
9899 }
9900 
9901 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9902 
9903 /// Check for comparisons of floating point operands using != and ==.
9904 /// Issue a warning if these are no self-comparisons, as they are not likely
9905 /// to do what the programmer intended.
9906 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9907   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9908   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9909 
9910   // Special case: check for x == x (which is OK).
9911   // Do not emit warnings for such cases.
9912   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9913     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9914       if (DRL->getDecl() == DRR->getDecl())
9915         return;
9916 
9917   // Special case: check for comparisons against literals that can be exactly
9918   //  represented by APFloat.  In such cases, do not emit a warning.  This
9919   //  is a heuristic: often comparison against such literals are used to
9920   //  detect if a value in a variable has not changed.  This clearly can
9921   //  lead to false negatives.
9922   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9923     if (FLL->isExact())
9924       return;
9925   } else
9926     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9927       if (FLR->isExact())
9928         return;
9929 
9930   // Check for comparisons with builtin types.
9931   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9932     if (CL->getBuiltinCallee())
9933       return;
9934 
9935   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9936     if (CR->getBuiltinCallee())
9937       return;
9938 
9939   // Emit the diagnostic.
9940   Diag(Loc, diag::warn_floatingpoint_eq)
9941     << LHS->getSourceRange() << RHS->getSourceRange();
9942 }
9943 
9944 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9945 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9946 
9947 namespace {
9948 
9949 /// Structure recording the 'active' range of an integer-valued
9950 /// expression.
9951 struct IntRange {
9952   /// The number of bits active in the int.
9953   unsigned Width;
9954 
9955   /// True if the int is known not to have negative values.
9956   bool NonNegative;
9957 
9958   IntRange(unsigned Width, bool NonNegative)
9959       : Width(Width), NonNegative(NonNegative) {}
9960 
9961   /// Returns the range of the bool type.
9962   static IntRange forBoolType() {
9963     return IntRange(1, true);
9964   }
9965 
9966   /// Returns the range of an opaque value of the given integral type.
9967   static IntRange forValueOfType(ASTContext &C, QualType T) {
9968     return forValueOfCanonicalType(C,
9969                           T->getCanonicalTypeInternal().getTypePtr());
9970   }
9971 
9972   /// Returns the range of an opaque value of a canonical integral type.
9973   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9974     assert(T->isCanonicalUnqualified());
9975 
9976     if (const VectorType *VT = dyn_cast<VectorType>(T))
9977       T = VT->getElementType().getTypePtr();
9978     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9979       T = CT->getElementType().getTypePtr();
9980     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9981       T = AT->getValueType().getTypePtr();
9982 
9983     if (!C.getLangOpts().CPlusPlus) {
9984       // For enum types in C code, use the underlying datatype.
9985       if (const EnumType *ET = dyn_cast<EnumType>(T))
9986         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9987     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9988       // For enum types in C++, use the known bit width of the enumerators.
9989       EnumDecl *Enum = ET->getDecl();
9990       // In C++11, enums can have a fixed underlying type. Use this type to
9991       // compute the range.
9992       if (Enum->isFixed()) {
9993         return IntRange(C.getIntWidth(QualType(T, 0)),
9994                         !ET->isSignedIntegerOrEnumerationType());
9995       }
9996 
9997       unsigned NumPositive = Enum->getNumPositiveBits();
9998       unsigned NumNegative = Enum->getNumNegativeBits();
9999 
10000       if (NumNegative == 0)
10001         return IntRange(NumPositive, true/*NonNegative*/);
10002       else
10003         return IntRange(std::max(NumPositive + 1, NumNegative),
10004                         false/*NonNegative*/);
10005     }
10006 
10007     const BuiltinType *BT = cast<BuiltinType>(T);
10008     assert(BT->isInteger());
10009 
10010     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10011   }
10012 
10013   /// Returns the "target" range of a canonical integral type, i.e.
10014   /// the range of values expressible in the type.
10015   ///
10016   /// This matches forValueOfCanonicalType except that enums have the
10017   /// full range of their type, not the range of their enumerators.
10018   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10019     assert(T->isCanonicalUnqualified());
10020 
10021     if (const VectorType *VT = dyn_cast<VectorType>(T))
10022       T = VT->getElementType().getTypePtr();
10023     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10024       T = CT->getElementType().getTypePtr();
10025     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10026       T = AT->getValueType().getTypePtr();
10027     if (const EnumType *ET = dyn_cast<EnumType>(T))
10028       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10029 
10030     const BuiltinType *BT = cast<BuiltinType>(T);
10031     assert(BT->isInteger());
10032 
10033     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10034   }
10035 
10036   /// Returns the supremum of two ranges: i.e. their conservative merge.
10037   static IntRange join(IntRange L, IntRange R) {
10038     return IntRange(std::max(L.Width, R.Width),
10039                     L.NonNegative && R.NonNegative);
10040   }
10041 
10042   /// Returns the infinum of two ranges: i.e. their aggressive merge.
10043   static IntRange meet(IntRange L, IntRange R) {
10044     return IntRange(std::min(L.Width, R.Width),
10045                     L.NonNegative || R.NonNegative);
10046   }
10047 };
10048 
10049 } // namespace
10050 
10051 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10052                               unsigned MaxWidth) {
10053   if (value.isSigned() && value.isNegative())
10054     return IntRange(value.getMinSignedBits(), false);
10055 
10056   if (value.getBitWidth() > MaxWidth)
10057     value = value.trunc(MaxWidth);
10058 
10059   // isNonNegative() just checks the sign bit without considering
10060   // signedness.
10061   return IntRange(value.getActiveBits(), true);
10062 }
10063 
10064 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10065                               unsigned MaxWidth) {
10066   if (result.isInt())
10067     return GetValueRange(C, result.getInt(), MaxWidth);
10068 
10069   if (result.isVector()) {
10070     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10071     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10072       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10073       R = IntRange::join(R, El);
10074     }
10075     return R;
10076   }
10077 
10078   if (result.isComplexInt()) {
10079     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10080     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10081     return IntRange::join(R, I);
10082   }
10083 
10084   // This can happen with lossless casts to intptr_t of "based" lvalues.
10085   // Assume it might use arbitrary bits.
10086   // FIXME: The only reason we need to pass the type in here is to get
10087   // the sign right on this one case.  It would be nice if APValue
10088   // preserved this.
10089   assert(result.isLValue() || result.isAddrLabelDiff());
10090   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10091 }
10092 
10093 static QualType GetExprType(const Expr *E) {
10094   QualType Ty = E->getType();
10095   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10096     Ty = AtomicRHS->getValueType();
10097   return Ty;
10098 }
10099 
10100 /// Pseudo-evaluate the given integer expression, estimating the
10101 /// range of values it might take.
10102 ///
10103 /// \param MaxWidth - the width to which the value will be truncated
10104 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10105                              bool InConstantContext) {
10106   E = E->IgnoreParens();
10107 
10108   // Try a full evaluation first.
10109   Expr::EvalResult result;
10110   if (E->EvaluateAsRValue(result, C, InConstantContext))
10111     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10112 
10113   // I think we only want to look through implicit casts here; if the
10114   // user has an explicit widening cast, we should treat the value as
10115   // being of the new, wider type.
10116   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10117     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10118       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext);
10119 
10120     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10121 
10122     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10123                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10124 
10125     // Assume that non-integer casts can span the full range of the type.
10126     if (!isIntegerCast)
10127       return OutputTypeRange;
10128 
10129     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10130                                      std::min(MaxWidth, OutputTypeRange.Width),
10131                                      InConstantContext);
10132 
10133     // Bail out if the subexpr's range is as wide as the cast type.
10134     if (SubRange.Width >= OutputTypeRange.Width)
10135       return OutputTypeRange;
10136 
10137     // Otherwise, we take the smaller width, and we're non-negative if
10138     // either the output type or the subexpr is.
10139     return IntRange(SubRange.Width,
10140                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10141   }
10142 
10143   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10144     // If we can fold the condition, just take that operand.
10145     bool CondResult;
10146     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10147       return GetExprRange(C,
10148                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10149                           MaxWidth, InConstantContext);
10150 
10151     // Otherwise, conservatively merge.
10152     IntRange L =
10153         GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext);
10154     IntRange R =
10155         GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext);
10156     return IntRange::join(L, R);
10157   }
10158 
10159   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10160     switch (BO->getOpcode()) {
10161     case BO_Cmp:
10162       llvm_unreachable("builtin <=> should have class type");
10163 
10164     // Boolean-valued operations are single-bit and positive.
10165     case BO_LAnd:
10166     case BO_LOr:
10167     case BO_LT:
10168     case BO_GT:
10169     case BO_LE:
10170     case BO_GE:
10171     case BO_EQ:
10172     case BO_NE:
10173       return IntRange::forBoolType();
10174 
10175     // The type of the assignments is the type of the LHS, so the RHS
10176     // is not necessarily the same type.
10177     case BO_MulAssign:
10178     case BO_DivAssign:
10179     case BO_RemAssign:
10180     case BO_AddAssign:
10181     case BO_SubAssign:
10182     case BO_XorAssign:
10183     case BO_OrAssign:
10184       // TODO: bitfields?
10185       return IntRange::forValueOfType(C, GetExprType(E));
10186 
10187     // Simple assignments just pass through the RHS, which will have
10188     // been coerced to the LHS type.
10189     case BO_Assign:
10190       // TODO: bitfields?
10191       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10192 
10193     // Operations with opaque sources are black-listed.
10194     case BO_PtrMemD:
10195     case BO_PtrMemI:
10196       return IntRange::forValueOfType(C, GetExprType(E));
10197 
10198     // Bitwise-and uses the *infinum* of the two source ranges.
10199     case BO_And:
10200     case BO_AndAssign:
10201       return IntRange::meet(
10202           GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext),
10203           GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext));
10204 
10205     // Left shift gets black-listed based on a judgement call.
10206     case BO_Shl:
10207       // ...except that we want to treat '1 << (blah)' as logically
10208       // positive.  It's an important idiom.
10209       if (IntegerLiteral *I
10210             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10211         if (I->getValue() == 1) {
10212           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10213           return IntRange(R.Width, /*NonNegative*/ true);
10214         }
10215       }
10216       LLVM_FALLTHROUGH;
10217 
10218     case BO_ShlAssign:
10219       return IntRange::forValueOfType(C, GetExprType(E));
10220 
10221     // Right shift by a constant can narrow its left argument.
10222     case BO_Shr:
10223     case BO_ShrAssign: {
10224       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10225 
10226       // If the shift amount is a positive constant, drop the width by
10227       // that much.
10228       llvm::APSInt shift;
10229       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
10230           shift.isNonNegative()) {
10231         unsigned zext = shift.getZExtValue();
10232         if (zext >= L.Width)
10233           L.Width = (L.NonNegative ? 0 : 1);
10234         else
10235           L.Width -= zext;
10236       }
10237 
10238       return L;
10239     }
10240 
10241     // Comma acts as its right operand.
10242     case BO_Comma:
10243       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10244 
10245     // Black-list pointer subtractions.
10246     case BO_Sub:
10247       if (BO->getLHS()->getType()->isPointerType())
10248         return IntRange::forValueOfType(C, GetExprType(E));
10249       break;
10250 
10251     // The width of a division result is mostly determined by the size
10252     // of the LHS.
10253     case BO_Div: {
10254       // Don't 'pre-truncate' the operands.
10255       unsigned opWidth = C.getIntWidth(GetExprType(E));
10256       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10257 
10258       // If the divisor is constant, use that.
10259       llvm::APSInt divisor;
10260       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
10261         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
10262         if (log2 >= L.Width)
10263           L.Width = (L.NonNegative ? 0 : 1);
10264         else
10265           L.Width = std::min(L.Width - log2, MaxWidth);
10266         return L;
10267       }
10268 
10269       // Otherwise, just use the LHS's width.
10270       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10271       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10272     }
10273 
10274     // The result of a remainder can't be larger than the result of
10275     // either side.
10276     case BO_Rem: {
10277       // Don't 'pre-truncate' the operands.
10278       unsigned opWidth = C.getIntWidth(GetExprType(E));
10279       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext);
10280       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext);
10281 
10282       IntRange meet = IntRange::meet(L, R);
10283       meet.Width = std::min(meet.Width, MaxWidth);
10284       return meet;
10285     }
10286 
10287     // The default behavior is okay for these.
10288     case BO_Mul:
10289     case BO_Add:
10290     case BO_Xor:
10291     case BO_Or:
10292       break;
10293     }
10294 
10295     // The default case is to treat the operation as if it were closed
10296     // on the narrowest type that encompasses both operands.
10297     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext);
10298     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext);
10299     return IntRange::join(L, R);
10300   }
10301 
10302   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10303     switch (UO->getOpcode()) {
10304     // Boolean-valued operations are white-listed.
10305     case UO_LNot:
10306       return IntRange::forBoolType();
10307 
10308     // Operations with opaque sources are black-listed.
10309     case UO_Deref:
10310     case UO_AddrOf: // should be impossible
10311       return IntRange::forValueOfType(C, GetExprType(E));
10312 
10313     default:
10314       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext);
10315     }
10316   }
10317 
10318   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10319     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext);
10320 
10321   if (const auto *BitField = E->getSourceBitField())
10322     return IntRange(BitField->getBitWidthValue(C),
10323                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10324 
10325   return IntRange::forValueOfType(C, GetExprType(E));
10326 }
10327 
10328 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10329                              bool InConstantContext) {
10330   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext);
10331 }
10332 
10333 /// Checks whether the given value, which currently has the given
10334 /// source semantics, has the same value when coerced through the
10335 /// target semantics.
10336 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10337                                  const llvm::fltSemantics &Src,
10338                                  const llvm::fltSemantics &Tgt) {
10339   llvm::APFloat truncated = value;
10340 
10341   bool ignored;
10342   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10343   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10344 
10345   return truncated.bitwiseIsEqual(value);
10346 }
10347 
10348 /// Checks whether the given value, which currently has the given
10349 /// source semantics, has the same value when coerced through the
10350 /// target semantics.
10351 ///
10352 /// The value might be a vector of floats (or a complex number).
10353 static bool IsSameFloatAfterCast(const APValue &value,
10354                                  const llvm::fltSemantics &Src,
10355                                  const llvm::fltSemantics &Tgt) {
10356   if (value.isFloat())
10357     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10358 
10359   if (value.isVector()) {
10360     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10361       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10362         return false;
10363     return true;
10364   }
10365 
10366   assert(value.isComplexFloat());
10367   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10368           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10369 }
10370 
10371 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10372                                        bool IsListInit = false);
10373 
10374 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10375   // Suppress cases where we are comparing against an enum constant.
10376   if (const DeclRefExpr *DR =
10377       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10378     if (isa<EnumConstantDecl>(DR->getDecl()))
10379       return true;
10380 
10381   // Suppress cases where the value is expanded from a macro, unless that macro
10382   // is how a language represents a boolean literal. This is the case in both C
10383   // and Objective-C.
10384   SourceLocation BeginLoc = E->getBeginLoc();
10385   if (BeginLoc.isMacroID()) {
10386     StringRef MacroName = Lexer::getImmediateMacroName(
10387         BeginLoc, S.getSourceManager(), S.getLangOpts());
10388     return MacroName != "YES" && MacroName != "NO" &&
10389            MacroName != "true" && MacroName != "false";
10390   }
10391 
10392   return false;
10393 }
10394 
10395 static bool isKnownToHaveUnsignedValue(Expr *E) {
10396   return E->getType()->isIntegerType() &&
10397          (!E->getType()->isSignedIntegerType() ||
10398           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10399 }
10400 
10401 namespace {
10402 /// The promoted range of values of a type. In general this has the
10403 /// following structure:
10404 ///
10405 ///     |-----------| . . . |-----------|
10406 ///     ^           ^       ^           ^
10407 ///    Min       HoleMin  HoleMax      Max
10408 ///
10409 /// ... where there is only a hole if a signed type is promoted to unsigned
10410 /// (in which case Min and Max are the smallest and largest representable
10411 /// values).
10412 struct PromotedRange {
10413   // Min, or HoleMax if there is a hole.
10414   llvm::APSInt PromotedMin;
10415   // Max, or HoleMin if there is a hole.
10416   llvm::APSInt PromotedMax;
10417 
10418   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10419     if (R.Width == 0)
10420       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10421     else if (R.Width >= BitWidth && !Unsigned) {
10422       // Promotion made the type *narrower*. This happens when promoting
10423       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10424       // Treat all values of 'signed int' as being in range for now.
10425       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10426       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10427     } else {
10428       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10429                         .extOrTrunc(BitWidth);
10430       PromotedMin.setIsUnsigned(Unsigned);
10431 
10432       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10433                         .extOrTrunc(BitWidth);
10434       PromotedMax.setIsUnsigned(Unsigned);
10435     }
10436   }
10437 
10438   // Determine whether this range is contiguous (has no hole).
10439   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10440 
10441   // Where a constant value is within the range.
10442   enum ComparisonResult {
10443     LT = 0x1,
10444     LE = 0x2,
10445     GT = 0x4,
10446     GE = 0x8,
10447     EQ = 0x10,
10448     NE = 0x20,
10449     InRangeFlag = 0x40,
10450 
10451     Less = LE | LT | NE,
10452     Min = LE | InRangeFlag,
10453     InRange = InRangeFlag,
10454     Max = GE | InRangeFlag,
10455     Greater = GE | GT | NE,
10456 
10457     OnlyValue = LE | GE | EQ | InRangeFlag,
10458     InHole = NE
10459   };
10460 
10461   ComparisonResult compare(const llvm::APSInt &Value) const {
10462     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10463            Value.isUnsigned() == PromotedMin.isUnsigned());
10464     if (!isContiguous()) {
10465       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10466       if (Value.isMinValue()) return Min;
10467       if (Value.isMaxValue()) return Max;
10468       if (Value >= PromotedMin) return InRange;
10469       if (Value <= PromotedMax) return InRange;
10470       return InHole;
10471     }
10472 
10473     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10474     case -1: return Less;
10475     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10476     case 1:
10477       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10478       case -1: return InRange;
10479       case 0: return Max;
10480       case 1: return Greater;
10481       }
10482     }
10483 
10484     llvm_unreachable("impossible compare result");
10485   }
10486 
10487   static llvm::Optional<StringRef>
10488   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10489     if (Op == BO_Cmp) {
10490       ComparisonResult LTFlag = LT, GTFlag = GT;
10491       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10492 
10493       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10494       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10495       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10496       return llvm::None;
10497     }
10498 
10499     ComparisonResult TrueFlag, FalseFlag;
10500     if (Op == BO_EQ) {
10501       TrueFlag = EQ;
10502       FalseFlag = NE;
10503     } else if (Op == BO_NE) {
10504       TrueFlag = NE;
10505       FalseFlag = EQ;
10506     } else {
10507       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10508         TrueFlag = LT;
10509         FalseFlag = GE;
10510       } else {
10511         TrueFlag = GT;
10512         FalseFlag = LE;
10513       }
10514       if (Op == BO_GE || Op == BO_LE)
10515         std::swap(TrueFlag, FalseFlag);
10516     }
10517     if (R & TrueFlag)
10518       return StringRef("true");
10519     if (R & FalseFlag)
10520       return StringRef("false");
10521     return llvm::None;
10522   }
10523 };
10524 }
10525 
10526 static bool HasEnumType(Expr *E) {
10527   // Strip off implicit integral promotions.
10528   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10529     if (ICE->getCastKind() != CK_IntegralCast &&
10530         ICE->getCastKind() != CK_NoOp)
10531       break;
10532     E = ICE->getSubExpr();
10533   }
10534 
10535   return E->getType()->isEnumeralType();
10536 }
10537 
10538 static int classifyConstantValue(Expr *Constant) {
10539   // The values of this enumeration are used in the diagnostics
10540   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10541   enum ConstantValueKind {
10542     Miscellaneous = 0,
10543     LiteralTrue,
10544     LiteralFalse
10545   };
10546   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10547     return BL->getValue() ? ConstantValueKind::LiteralTrue
10548                           : ConstantValueKind::LiteralFalse;
10549   return ConstantValueKind::Miscellaneous;
10550 }
10551 
10552 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10553                                         Expr *Constant, Expr *Other,
10554                                         const llvm::APSInt &Value,
10555                                         bool RhsConstant) {
10556   if (S.inTemplateInstantiation())
10557     return false;
10558 
10559   Expr *OriginalOther = Other;
10560 
10561   Constant = Constant->IgnoreParenImpCasts();
10562   Other = Other->IgnoreParenImpCasts();
10563 
10564   // Suppress warnings on tautological comparisons between values of the same
10565   // enumeration type. There are only two ways we could warn on this:
10566   //  - If the constant is outside the range of representable values of
10567   //    the enumeration. In such a case, we should warn about the cast
10568   //    to enumeration type, not about the comparison.
10569   //  - If the constant is the maximum / minimum in-range value. For an
10570   //    enumeratin type, such comparisons can be meaningful and useful.
10571   if (Constant->getType()->isEnumeralType() &&
10572       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10573     return false;
10574 
10575   // TODO: Investigate using GetExprRange() to get tighter bounds
10576   // on the bit ranges.
10577   QualType OtherT = Other->getType();
10578   if (const auto *AT = OtherT->getAs<AtomicType>())
10579     OtherT = AT->getValueType();
10580   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10581 
10582   // Special case for ObjC BOOL on targets where its a typedef for a signed char
10583   // (Namely, macOS).
10584   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
10585                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
10586                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
10587 
10588   // Whether we're treating Other as being a bool because of the form of
10589   // expression despite it having another type (typically 'int' in C).
10590   bool OtherIsBooleanDespiteType =
10591       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10592   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
10593     OtherRange = IntRange::forBoolType();
10594 
10595   // Determine the promoted range of the other type and see if a comparison of
10596   // the constant against that range is tautological.
10597   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10598                                    Value.isUnsigned());
10599   auto Cmp = OtherPromotedRange.compare(Value);
10600   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10601   if (!Result)
10602     return false;
10603 
10604   // Suppress the diagnostic for an in-range comparison if the constant comes
10605   // from a macro or enumerator. We don't want to diagnose
10606   //
10607   //   some_long_value <= INT_MAX
10608   //
10609   // when sizeof(int) == sizeof(long).
10610   bool InRange = Cmp & PromotedRange::InRangeFlag;
10611   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10612     return false;
10613 
10614   // If this is a comparison to an enum constant, include that
10615   // constant in the diagnostic.
10616   const EnumConstantDecl *ED = nullptr;
10617   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10618     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10619 
10620   // Should be enough for uint128 (39 decimal digits)
10621   SmallString<64> PrettySourceValue;
10622   llvm::raw_svector_ostream OS(PrettySourceValue);
10623   if (ED) {
10624     OS << '\'' << *ED << "' (" << Value << ")";
10625   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
10626                Constant->IgnoreParenImpCasts())) {
10627     OS << (BL->getValue() ? "YES" : "NO");
10628   } else {
10629     OS << Value;
10630   }
10631 
10632   if (IsObjCSignedCharBool) {
10633     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10634                           S.PDiag(diag::warn_tautological_compare_objc_bool)
10635                               << OS.str() << *Result);
10636     return true;
10637   }
10638 
10639   // FIXME: We use a somewhat different formatting for the in-range cases and
10640   // cases involving boolean values for historical reasons. We should pick a
10641   // consistent way of presenting these diagnostics.
10642   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10643 
10644     S.DiagRuntimeBehavior(
10645         E->getOperatorLoc(), E,
10646         S.PDiag(!InRange ? diag::warn_out_of_range_compare
10647                          : diag::warn_tautological_bool_compare)
10648             << OS.str() << classifyConstantValue(Constant) << OtherT
10649             << OtherIsBooleanDespiteType << *Result
10650             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10651   } else {
10652     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10653                         ? (HasEnumType(OriginalOther)
10654                                ? diag::warn_unsigned_enum_always_true_comparison
10655                                : diag::warn_unsigned_always_true_comparison)
10656                         : diag::warn_tautological_constant_compare;
10657 
10658     S.Diag(E->getOperatorLoc(), Diag)
10659         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10660         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10661   }
10662 
10663   return true;
10664 }
10665 
10666 /// Analyze the operands of the given comparison.  Implements the
10667 /// fallback case from AnalyzeComparison.
10668 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10669   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10670   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10671 }
10672 
10673 /// Implements -Wsign-compare.
10674 ///
10675 /// \param E the binary operator to check for warnings
10676 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10677   // The type the comparison is being performed in.
10678   QualType T = E->getLHS()->getType();
10679 
10680   // Only analyze comparison operators where both sides have been converted to
10681   // the same type.
10682   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10683     return AnalyzeImpConvsInComparison(S, E);
10684 
10685   // Don't analyze value-dependent comparisons directly.
10686   if (E->isValueDependent())
10687     return AnalyzeImpConvsInComparison(S, E);
10688 
10689   Expr *LHS = E->getLHS();
10690   Expr *RHS = E->getRHS();
10691 
10692   if (T->isIntegralType(S.Context)) {
10693     llvm::APSInt RHSValue;
10694     llvm::APSInt LHSValue;
10695 
10696     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10697     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10698 
10699     // We don't care about expressions whose result is a constant.
10700     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10701       return AnalyzeImpConvsInComparison(S, E);
10702 
10703     // We only care about expressions where just one side is literal
10704     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10705       // Is the constant on the RHS or LHS?
10706       const bool RhsConstant = IsRHSIntegralLiteral;
10707       Expr *Const = RhsConstant ? RHS : LHS;
10708       Expr *Other = RhsConstant ? LHS : RHS;
10709       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10710 
10711       // Check whether an integer constant comparison results in a value
10712       // of 'true' or 'false'.
10713       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10714         return AnalyzeImpConvsInComparison(S, E);
10715     }
10716   }
10717 
10718   if (!T->hasUnsignedIntegerRepresentation()) {
10719     // We don't do anything special if this isn't an unsigned integral
10720     // comparison:  we're only interested in integral comparisons, and
10721     // signed comparisons only happen in cases we don't care to warn about.
10722     return AnalyzeImpConvsInComparison(S, E);
10723   }
10724 
10725   LHS = LHS->IgnoreParenImpCasts();
10726   RHS = RHS->IgnoreParenImpCasts();
10727 
10728   if (!S.getLangOpts().CPlusPlus) {
10729     // Avoid warning about comparison of integers with different signs when
10730     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10731     // the type of `E`.
10732     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10733       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10734     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10735       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10736   }
10737 
10738   // Check to see if one of the (unmodified) operands is of different
10739   // signedness.
10740   Expr *signedOperand, *unsignedOperand;
10741   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10742     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10743            "unsigned comparison between two signed integer expressions?");
10744     signedOperand = LHS;
10745     unsignedOperand = RHS;
10746   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10747     signedOperand = RHS;
10748     unsignedOperand = LHS;
10749   } else {
10750     return AnalyzeImpConvsInComparison(S, E);
10751   }
10752 
10753   // Otherwise, calculate the effective range of the signed operand.
10754   IntRange signedRange =
10755       GetExprRange(S.Context, signedOperand, S.isConstantEvaluated());
10756 
10757   // Go ahead and analyze implicit conversions in the operands.  Note
10758   // that we skip the implicit conversions on both sides.
10759   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10760   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10761 
10762   // If the signed range is non-negative, -Wsign-compare won't fire.
10763   if (signedRange.NonNegative)
10764     return;
10765 
10766   // For (in)equality comparisons, if the unsigned operand is a
10767   // constant which cannot collide with a overflowed signed operand,
10768   // then reinterpreting the signed operand as unsigned will not
10769   // change the result of the comparison.
10770   if (E->isEqualityOp()) {
10771     unsigned comparisonWidth = S.Context.getIntWidth(T);
10772     IntRange unsignedRange =
10773         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated());
10774 
10775     // We should never be unable to prove that the unsigned operand is
10776     // non-negative.
10777     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10778 
10779     if (unsignedRange.Width < comparisonWidth)
10780       return;
10781   }
10782 
10783   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10784                         S.PDiag(diag::warn_mixed_sign_comparison)
10785                             << LHS->getType() << RHS->getType()
10786                             << LHS->getSourceRange() << RHS->getSourceRange());
10787 }
10788 
10789 /// Analyzes an attempt to assign the given value to a bitfield.
10790 ///
10791 /// Returns true if there was something fishy about the attempt.
10792 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10793                                       SourceLocation InitLoc) {
10794   assert(Bitfield->isBitField());
10795   if (Bitfield->isInvalidDecl())
10796     return false;
10797 
10798   // White-list bool bitfields.
10799   QualType BitfieldType = Bitfield->getType();
10800   if (BitfieldType->isBooleanType())
10801      return false;
10802 
10803   if (BitfieldType->isEnumeralType()) {
10804     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
10805     // If the underlying enum type was not explicitly specified as an unsigned
10806     // type and the enum contain only positive values, MSVC++ will cause an
10807     // inconsistency by storing this as a signed type.
10808     if (S.getLangOpts().CPlusPlus11 &&
10809         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10810         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10811         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10812       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10813         << BitfieldEnumDecl->getNameAsString();
10814     }
10815   }
10816 
10817   if (Bitfield->getType()->isBooleanType())
10818     return false;
10819 
10820   // Ignore value- or type-dependent expressions.
10821   if (Bitfield->getBitWidth()->isValueDependent() ||
10822       Bitfield->getBitWidth()->isTypeDependent() ||
10823       Init->isValueDependent() ||
10824       Init->isTypeDependent())
10825     return false;
10826 
10827   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10828   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10829 
10830   Expr::EvalResult Result;
10831   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10832                                    Expr::SE_AllowSideEffects)) {
10833     // The RHS is not constant.  If the RHS has an enum type, make sure the
10834     // bitfield is wide enough to hold all the values of the enum without
10835     // truncation.
10836     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10837       EnumDecl *ED = EnumTy->getDecl();
10838       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10839 
10840       // Enum types are implicitly signed on Windows, so check if there are any
10841       // negative enumerators to see if the enum was intended to be signed or
10842       // not.
10843       bool SignedEnum = ED->getNumNegativeBits() > 0;
10844 
10845       // Check for surprising sign changes when assigning enum values to a
10846       // bitfield of different signedness.  If the bitfield is signed and we
10847       // have exactly the right number of bits to store this unsigned enum,
10848       // suggest changing the enum to an unsigned type. This typically happens
10849       // on Windows where unfixed enums always use an underlying type of 'int'.
10850       unsigned DiagID = 0;
10851       if (SignedEnum && !SignedBitfield) {
10852         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10853       } else if (SignedBitfield && !SignedEnum &&
10854                  ED->getNumPositiveBits() == FieldWidth) {
10855         DiagID = diag::warn_signed_bitfield_enum_conversion;
10856       }
10857 
10858       if (DiagID) {
10859         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10860         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10861         SourceRange TypeRange =
10862             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10863         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10864             << SignedEnum << TypeRange;
10865       }
10866 
10867       // Compute the required bitwidth. If the enum has negative values, we need
10868       // one more bit than the normal number of positive bits to represent the
10869       // sign bit.
10870       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10871                                                   ED->getNumNegativeBits())
10872                                        : ED->getNumPositiveBits();
10873 
10874       // Check the bitwidth.
10875       if (BitsNeeded > FieldWidth) {
10876         Expr *WidthExpr = Bitfield->getBitWidth();
10877         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10878             << Bitfield << ED;
10879         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10880             << BitsNeeded << ED << WidthExpr->getSourceRange();
10881       }
10882     }
10883 
10884     return false;
10885   }
10886 
10887   llvm::APSInt Value = Result.Val.getInt();
10888 
10889   unsigned OriginalWidth = Value.getBitWidth();
10890 
10891   if (!Value.isSigned() || Value.isNegative())
10892     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10893       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10894         OriginalWidth = Value.getMinSignedBits();
10895 
10896   if (OriginalWidth <= FieldWidth)
10897     return false;
10898 
10899   // Compute the value which the bitfield will contain.
10900   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10901   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10902 
10903   // Check whether the stored value is equal to the original value.
10904   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10905   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10906     return false;
10907 
10908   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10909   // therefore don't strictly fit into a signed bitfield of width 1.
10910   if (FieldWidth == 1 && Value == 1)
10911     return false;
10912 
10913   std::string PrettyValue = Value.toString(10);
10914   std::string PrettyTrunc = TruncatedValue.toString(10);
10915 
10916   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10917     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10918     << Init->getSourceRange();
10919 
10920   return true;
10921 }
10922 
10923 /// Analyze the given simple or compound assignment for warning-worthy
10924 /// operations.
10925 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10926   // Just recurse on the LHS.
10927   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10928 
10929   // We want to recurse on the RHS as normal unless we're assigning to
10930   // a bitfield.
10931   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10932     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10933                                   E->getOperatorLoc())) {
10934       // Recurse, ignoring any implicit conversions on the RHS.
10935       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10936                                         E->getOperatorLoc());
10937     }
10938   }
10939 
10940   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10941 
10942   // Diagnose implicitly sequentially-consistent atomic assignment.
10943   if (E->getLHS()->getType()->isAtomicType())
10944     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10945 }
10946 
10947 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10948 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10949                             SourceLocation CContext, unsigned diag,
10950                             bool pruneControlFlow = false) {
10951   if (pruneControlFlow) {
10952     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10953                           S.PDiag(diag)
10954                               << SourceType << T << E->getSourceRange()
10955                               << SourceRange(CContext));
10956     return;
10957   }
10958   S.Diag(E->getExprLoc(), diag)
10959     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10960 }
10961 
10962 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10963 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10964                             SourceLocation CContext,
10965                             unsigned diag, bool pruneControlFlow = false) {
10966   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10967 }
10968 
10969 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
10970   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
10971       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
10972 }
10973 
10974 static void adornObjCBoolConversionDiagWithTernaryFixit(
10975     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
10976   Expr *Ignored = SourceExpr->IgnoreImplicit();
10977   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
10978     Ignored = OVE->getSourceExpr();
10979   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
10980                      isa<BinaryOperator>(Ignored) ||
10981                      isa<CXXOperatorCallExpr>(Ignored);
10982   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
10983   if (NeedsParens)
10984     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
10985             << FixItHint::CreateInsertion(EndLoc, ")");
10986   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
10987 }
10988 
10989 /// Diagnose an implicit cast from a floating point value to an integer value.
10990 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10991                                     SourceLocation CContext) {
10992   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10993   const bool PruneWarnings = S.inTemplateInstantiation();
10994 
10995   Expr *InnerE = E->IgnoreParenImpCasts();
10996   // We also want to warn on, e.g., "int i = -1.234"
10997   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10998     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10999       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11000 
11001   const bool IsLiteral =
11002       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11003 
11004   llvm::APFloat Value(0.0);
11005   bool IsConstant =
11006     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11007   if (!IsConstant) {
11008     if (isObjCSignedCharBool(S, T)) {
11009       return adornObjCBoolConversionDiagWithTernaryFixit(
11010           S, E,
11011           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11012               << E->getType());
11013     }
11014 
11015     return DiagnoseImpCast(S, E, T, CContext,
11016                            diag::warn_impcast_float_integer, PruneWarnings);
11017   }
11018 
11019   bool isExact = false;
11020 
11021   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11022                             T->hasUnsignedIntegerRepresentation());
11023   llvm::APFloat::opStatus Result = Value.convertToInteger(
11024       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11025 
11026   // FIXME: Force the precision of the source value down so we don't print
11027   // digits which are usually useless (we don't really care here if we
11028   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11029   // would automatically print the shortest representation, but it's a bit
11030   // tricky to implement.
11031   SmallString<16> PrettySourceValue;
11032   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11033   precision = (precision * 59 + 195) / 196;
11034   Value.toString(PrettySourceValue, precision);
11035 
11036   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11037     return adornObjCBoolConversionDiagWithTernaryFixit(
11038         S, E,
11039         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11040             << PrettySourceValue);
11041   }
11042 
11043   if (Result == llvm::APFloat::opOK && isExact) {
11044     if (IsLiteral) return;
11045     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11046                            PruneWarnings);
11047   }
11048 
11049   // Conversion of a floating-point value to a non-bool integer where the
11050   // integral part cannot be represented by the integer type is undefined.
11051   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11052     return DiagnoseImpCast(
11053         S, E, T, CContext,
11054         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11055                   : diag::warn_impcast_float_to_integer_out_of_range,
11056         PruneWarnings);
11057 
11058   unsigned DiagID = 0;
11059   if (IsLiteral) {
11060     // Warn on floating point literal to integer.
11061     DiagID = diag::warn_impcast_literal_float_to_integer;
11062   } else if (IntegerValue == 0) {
11063     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11064       return DiagnoseImpCast(S, E, T, CContext,
11065                              diag::warn_impcast_float_integer, PruneWarnings);
11066     }
11067     // Warn on non-zero to zero conversion.
11068     DiagID = diag::warn_impcast_float_to_integer_zero;
11069   } else {
11070     if (IntegerValue.isUnsigned()) {
11071       if (!IntegerValue.isMaxValue()) {
11072         return DiagnoseImpCast(S, E, T, CContext,
11073                                diag::warn_impcast_float_integer, PruneWarnings);
11074       }
11075     } else {  // IntegerValue.isSigned()
11076       if (!IntegerValue.isMaxSignedValue() &&
11077           !IntegerValue.isMinSignedValue()) {
11078         return DiagnoseImpCast(S, E, T, CContext,
11079                                diag::warn_impcast_float_integer, PruneWarnings);
11080       }
11081     }
11082     // Warn on evaluatable floating point expression to integer conversion.
11083     DiagID = diag::warn_impcast_float_to_integer;
11084   }
11085 
11086   SmallString<16> PrettyTargetValue;
11087   if (IsBool)
11088     PrettyTargetValue = Value.isZero() ? "false" : "true";
11089   else
11090     IntegerValue.toString(PrettyTargetValue);
11091 
11092   if (PruneWarnings) {
11093     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11094                           S.PDiag(DiagID)
11095                               << E->getType() << T.getUnqualifiedType()
11096                               << PrettySourceValue << PrettyTargetValue
11097                               << E->getSourceRange() << SourceRange(CContext));
11098   } else {
11099     S.Diag(E->getExprLoc(), DiagID)
11100         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11101         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11102   }
11103 }
11104 
11105 /// Analyze the given compound assignment for the possible losing of
11106 /// floating-point precision.
11107 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11108   assert(isa<CompoundAssignOperator>(E) &&
11109          "Must be compound assignment operation");
11110   // Recurse on the LHS and RHS in here
11111   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11112   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11113 
11114   if (E->getLHS()->getType()->isAtomicType())
11115     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11116 
11117   // Now check the outermost expression
11118   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11119   const auto *RBT = cast<CompoundAssignOperator>(E)
11120                         ->getComputationResultType()
11121                         ->getAs<BuiltinType>();
11122 
11123   // The below checks assume source is floating point.
11124   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11125 
11126   // If source is floating point but target is an integer.
11127   if (ResultBT->isInteger())
11128     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11129                            E->getExprLoc(), diag::warn_impcast_float_integer);
11130 
11131   if (!ResultBT->isFloatingPoint())
11132     return;
11133 
11134   // If both source and target are floating points, warn about losing precision.
11135   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11136       QualType(ResultBT, 0), QualType(RBT, 0));
11137   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11138     // warn about dropping FP rank.
11139     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11140                     diag::warn_impcast_float_result_precision);
11141 }
11142 
11143 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11144                                       IntRange Range) {
11145   if (!Range.Width) return "0";
11146 
11147   llvm::APSInt ValueInRange = Value;
11148   ValueInRange.setIsSigned(!Range.NonNegative);
11149   ValueInRange = ValueInRange.trunc(Range.Width);
11150   return ValueInRange.toString(10);
11151 }
11152 
11153 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11154   if (!isa<ImplicitCastExpr>(Ex))
11155     return false;
11156 
11157   Expr *InnerE = Ex->IgnoreParenImpCasts();
11158   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11159   const Type *Source =
11160     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11161   if (Target->isDependentType())
11162     return false;
11163 
11164   const BuiltinType *FloatCandidateBT =
11165     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11166   const Type *BoolCandidateType = ToBool ? Target : Source;
11167 
11168   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11169           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11170 }
11171 
11172 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11173                                              SourceLocation CC) {
11174   unsigned NumArgs = TheCall->getNumArgs();
11175   for (unsigned i = 0; i < NumArgs; ++i) {
11176     Expr *CurrA = TheCall->getArg(i);
11177     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11178       continue;
11179 
11180     bool IsSwapped = ((i > 0) &&
11181         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11182     IsSwapped |= ((i < (NumArgs - 1)) &&
11183         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11184     if (IsSwapped) {
11185       // Warn on this floating-point to bool conversion.
11186       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11187                       CurrA->getType(), CC,
11188                       diag::warn_impcast_floating_point_to_bool);
11189     }
11190   }
11191 }
11192 
11193 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11194                                    SourceLocation CC) {
11195   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11196                         E->getExprLoc()))
11197     return;
11198 
11199   // Don't warn on functions which have return type nullptr_t.
11200   if (isa<CallExpr>(E))
11201     return;
11202 
11203   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11204   const Expr::NullPointerConstantKind NullKind =
11205       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11206   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11207     return;
11208 
11209   // Return if target type is a safe conversion.
11210   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11211       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11212     return;
11213 
11214   SourceLocation Loc = E->getSourceRange().getBegin();
11215 
11216   // Venture through the macro stacks to get to the source of macro arguments.
11217   // The new location is a better location than the complete location that was
11218   // passed in.
11219   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11220   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11221 
11222   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11223   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11224     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11225         Loc, S.SourceMgr, S.getLangOpts());
11226     if (MacroName == "NULL")
11227       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11228   }
11229 
11230   // Only warn if the null and context location are in the same macro expansion.
11231   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11232     return;
11233 
11234   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11235       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11236       << FixItHint::CreateReplacement(Loc,
11237                                       S.getFixItZeroLiteralForType(T, Loc));
11238 }
11239 
11240 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11241                                   ObjCArrayLiteral *ArrayLiteral);
11242 
11243 static void
11244 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11245                            ObjCDictionaryLiteral *DictionaryLiteral);
11246 
11247 /// Check a single element within a collection literal against the
11248 /// target element type.
11249 static void checkObjCCollectionLiteralElement(Sema &S,
11250                                               QualType TargetElementType,
11251                                               Expr *Element,
11252                                               unsigned ElementKind) {
11253   // Skip a bitcast to 'id' or qualified 'id'.
11254   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11255     if (ICE->getCastKind() == CK_BitCast &&
11256         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11257       Element = ICE->getSubExpr();
11258   }
11259 
11260   QualType ElementType = Element->getType();
11261   ExprResult ElementResult(Element);
11262   if (ElementType->getAs<ObjCObjectPointerType>() &&
11263       S.CheckSingleAssignmentConstraints(TargetElementType,
11264                                          ElementResult,
11265                                          false, false)
11266         != Sema::Compatible) {
11267     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11268         << ElementType << ElementKind << TargetElementType
11269         << Element->getSourceRange();
11270   }
11271 
11272   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11273     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11274   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11275     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11276 }
11277 
11278 /// Check an Objective-C array literal being converted to the given
11279 /// target type.
11280 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11281                                   ObjCArrayLiteral *ArrayLiteral) {
11282   if (!S.NSArrayDecl)
11283     return;
11284 
11285   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11286   if (!TargetObjCPtr)
11287     return;
11288 
11289   if (TargetObjCPtr->isUnspecialized() ||
11290       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11291         != S.NSArrayDecl->getCanonicalDecl())
11292     return;
11293 
11294   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11295   if (TypeArgs.size() != 1)
11296     return;
11297 
11298   QualType TargetElementType = TypeArgs[0];
11299   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11300     checkObjCCollectionLiteralElement(S, TargetElementType,
11301                                       ArrayLiteral->getElement(I),
11302                                       0);
11303   }
11304 }
11305 
11306 /// Check an Objective-C dictionary literal being converted to the given
11307 /// target type.
11308 static void
11309 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11310                            ObjCDictionaryLiteral *DictionaryLiteral) {
11311   if (!S.NSDictionaryDecl)
11312     return;
11313 
11314   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11315   if (!TargetObjCPtr)
11316     return;
11317 
11318   if (TargetObjCPtr->isUnspecialized() ||
11319       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11320         != S.NSDictionaryDecl->getCanonicalDecl())
11321     return;
11322 
11323   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11324   if (TypeArgs.size() != 2)
11325     return;
11326 
11327   QualType TargetKeyType = TypeArgs[0];
11328   QualType TargetObjectType = TypeArgs[1];
11329   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11330     auto Element = DictionaryLiteral->getKeyValueElement(I);
11331     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11332     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11333   }
11334 }
11335 
11336 // Helper function to filter out cases for constant width constant conversion.
11337 // Don't warn on char array initialization or for non-decimal values.
11338 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11339                                           SourceLocation CC) {
11340   // If initializing from a constant, and the constant starts with '0',
11341   // then it is a binary, octal, or hexadecimal.  Allow these constants
11342   // to fill all the bits, even if there is a sign change.
11343   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11344     const char FirstLiteralCharacter =
11345         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11346     if (FirstLiteralCharacter == '0')
11347       return false;
11348   }
11349 
11350   // If the CC location points to a '{', and the type is char, then assume
11351   // assume it is an array initialization.
11352   if (CC.isValid() && T->isCharType()) {
11353     const char FirstContextCharacter =
11354         S.getSourceManager().getCharacterData(CC)[0];
11355     if (FirstContextCharacter == '{')
11356       return false;
11357   }
11358 
11359   return true;
11360 }
11361 
11362 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11363   const auto *IL = dyn_cast<IntegerLiteral>(E);
11364   if (!IL) {
11365     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11366       if (UO->getOpcode() == UO_Minus)
11367         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11368     }
11369   }
11370 
11371   return IL;
11372 }
11373 
11374 static void CheckConditionalWithEnumTypes(Sema &S, SourceLocation Loc,
11375                                           Expr *LHS, Expr *RHS) {
11376   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
11377   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
11378 
11379   const auto *LHSEnumType = LHSStrippedType->getAs<EnumType>();
11380   if (!LHSEnumType)
11381     return;
11382   const auto *RHSEnumType = RHSStrippedType->getAs<EnumType>();
11383   if (!RHSEnumType)
11384     return;
11385 
11386   // Ignore anonymous enums.
11387   if (!LHSEnumType->getDecl()->hasNameForLinkage())
11388     return;
11389   if (!RHSEnumType->getDecl()->hasNameForLinkage())
11390     return;
11391 
11392   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
11393     return;
11394 
11395   S.Diag(Loc, diag::warn_conditional_mixed_enum_types)
11396       << LHSStrippedType << RHSStrippedType << LHS->getSourceRange()
11397       << RHS->getSourceRange();
11398 }
11399 
11400 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11401   E = E->IgnoreParenImpCasts();
11402   SourceLocation ExprLoc = E->getExprLoc();
11403 
11404   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11405     BinaryOperator::Opcode Opc = BO->getOpcode();
11406     Expr::EvalResult Result;
11407     // Do not diagnose unsigned shifts.
11408     if (Opc == BO_Shl) {
11409       const auto *LHS = getIntegerLiteral(BO->getLHS());
11410       const auto *RHS = getIntegerLiteral(BO->getRHS());
11411       if (LHS && LHS->getValue() == 0)
11412         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11413       else if (!E->isValueDependent() && LHS && RHS &&
11414                RHS->getValue().isNonNegative() &&
11415                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11416         S.Diag(ExprLoc, diag::warn_left_shift_always)
11417             << (Result.Val.getInt() != 0);
11418       else if (E->getType()->isSignedIntegerType())
11419         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11420     }
11421   }
11422 
11423   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11424     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11425     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11426     if (!LHS || !RHS)
11427       return;
11428     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11429         (RHS->getValue() == 0 || RHS->getValue() == 1))
11430       // Do not diagnose common idioms.
11431       return;
11432     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11433       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11434   }
11435 }
11436 
11437 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11438                                     SourceLocation CC,
11439                                     bool *ICContext = nullptr,
11440                                     bool IsListInit = false) {
11441   if (E->isTypeDependent() || E->isValueDependent()) return;
11442 
11443   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11444   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11445   if (Source == Target) return;
11446   if (Target->isDependentType()) return;
11447 
11448   // If the conversion context location is invalid don't complain. We also
11449   // don't want to emit a warning if the issue occurs from the expansion of
11450   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11451   // delay this check as long as possible. Once we detect we are in that
11452   // scenario, we just return.
11453   if (CC.isInvalid())
11454     return;
11455 
11456   if (Source->isAtomicType())
11457     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11458 
11459   // Diagnose implicit casts to bool.
11460   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11461     if (isa<StringLiteral>(E))
11462       // Warn on string literal to bool.  Checks for string literals in logical
11463       // and expressions, for instance, assert(0 && "error here"), are
11464       // prevented by a check in AnalyzeImplicitConversions().
11465       return DiagnoseImpCast(S, E, T, CC,
11466                              diag::warn_impcast_string_literal_to_bool);
11467     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11468         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11469       // This covers the literal expressions that evaluate to Objective-C
11470       // objects.
11471       return DiagnoseImpCast(S, E, T, CC,
11472                              diag::warn_impcast_objective_c_literal_to_bool);
11473     }
11474     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11475       // Warn on pointer to bool conversion that is always true.
11476       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11477                                      SourceRange(CC));
11478     }
11479   }
11480 
11481   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
11482   // is a typedef for signed char (macOS), then that constant value has to be 1
11483   // or 0.
11484   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
11485     Expr::EvalResult Result;
11486     if (E->EvaluateAsInt(Result, S.getASTContext(),
11487                          Expr::SE_AllowSideEffects)) {
11488       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
11489         adornObjCBoolConversionDiagWithTernaryFixit(
11490             S, E,
11491             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
11492                 << Result.Val.getInt().toString(10));
11493       }
11494       return;
11495     }
11496   }
11497 
11498   // Check implicit casts from Objective-C collection literals to specialized
11499   // collection types, e.g., NSArray<NSString *> *.
11500   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
11501     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
11502   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
11503     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
11504 
11505   // Strip vector types.
11506   if (isa<VectorType>(Source)) {
11507     if (!isa<VectorType>(Target)) {
11508       if (S.SourceMgr.isInSystemMacro(CC))
11509         return;
11510       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
11511     }
11512 
11513     // If the vector cast is cast between two vectors of the same size, it is
11514     // a bitcast, not a conversion.
11515     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
11516       return;
11517 
11518     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
11519     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
11520   }
11521   if (auto VecTy = dyn_cast<VectorType>(Target))
11522     Target = VecTy->getElementType().getTypePtr();
11523 
11524   // Strip complex types.
11525   if (isa<ComplexType>(Source)) {
11526     if (!isa<ComplexType>(Target)) {
11527       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
11528         return;
11529 
11530       return DiagnoseImpCast(S, E, T, CC,
11531                              S.getLangOpts().CPlusPlus
11532                                  ? diag::err_impcast_complex_scalar
11533                                  : diag::warn_impcast_complex_scalar);
11534     }
11535 
11536     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11537     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11538   }
11539 
11540   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11541   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11542 
11543   // If the source is floating point...
11544   if (SourceBT && SourceBT->isFloatingPoint()) {
11545     // ...and the target is floating point...
11546     if (TargetBT && TargetBT->isFloatingPoint()) {
11547       // ...then warn if we're dropping FP rank.
11548 
11549       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11550           QualType(SourceBT, 0), QualType(TargetBT, 0));
11551       if (Order > 0) {
11552         // Don't warn about float constants that are precisely
11553         // representable in the target type.
11554         Expr::EvalResult result;
11555         if (E->EvaluateAsRValue(result, S.Context)) {
11556           // Value might be a float, a float vector, or a float complex.
11557           if (IsSameFloatAfterCast(result.Val,
11558                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11559                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11560             return;
11561         }
11562 
11563         if (S.SourceMgr.isInSystemMacro(CC))
11564           return;
11565 
11566         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11567       }
11568       // ... or possibly if we're increasing rank, too
11569       else if (Order < 0) {
11570         if (S.SourceMgr.isInSystemMacro(CC))
11571           return;
11572 
11573         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11574       }
11575       return;
11576     }
11577 
11578     // If the target is integral, always warn.
11579     if (TargetBT && TargetBT->isInteger()) {
11580       if (S.SourceMgr.isInSystemMacro(CC))
11581         return;
11582 
11583       DiagnoseFloatingImpCast(S, E, T, CC);
11584     }
11585 
11586     // Detect the case where a call result is converted from floating-point to
11587     // to bool, and the final argument to the call is converted from bool, to
11588     // discover this typo:
11589     //
11590     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11591     //
11592     // FIXME: This is an incredibly special case; is there some more general
11593     // way to detect this class of misplaced-parentheses bug?
11594     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11595       // Check last argument of function call to see if it is an
11596       // implicit cast from a type matching the type the result
11597       // is being cast to.
11598       CallExpr *CEx = cast<CallExpr>(E);
11599       if (unsigned NumArgs = CEx->getNumArgs()) {
11600         Expr *LastA = CEx->getArg(NumArgs - 1);
11601         Expr *InnerE = LastA->IgnoreParenImpCasts();
11602         if (isa<ImplicitCastExpr>(LastA) &&
11603             InnerE->getType()->isBooleanType()) {
11604           // Warn on this floating-point to bool conversion
11605           DiagnoseImpCast(S, E, T, CC,
11606                           diag::warn_impcast_floating_point_to_bool);
11607         }
11608       }
11609     }
11610     return;
11611   }
11612 
11613   // Valid casts involving fixed point types should be accounted for here.
11614   if (Source->isFixedPointType()) {
11615     if (Target->isUnsaturatedFixedPointType()) {
11616       Expr::EvalResult Result;
11617       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
11618                                   S.isConstantEvaluated())) {
11619         APFixedPoint Value = Result.Val.getFixedPoint();
11620         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11621         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11622         if (Value > MaxVal || Value < MinVal) {
11623           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11624                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11625                                     << Value.toString() << T
11626                                     << E->getSourceRange()
11627                                     << clang::SourceRange(CC));
11628           return;
11629         }
11630       }
11631     } else if (Target->isIntegerType()) {
11632       Expr::EvalResult Result;
11633       if (!S.isConstantEvaluated() &&
11634           E->EvaluateAsFixedPoint(Result, S.Context,
11635                                   Expr::SE_AllowSideEffects)) {
11636         APFixedPoint FXResult = Result.Val.getFixedPoint();
11637 
11638         bool Overflowed;
11639         llvm::APSInt IntResult = FXResult.convertToInt(
11640             S.Context.getIntWidth(T),
11641             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11642 
11643         if (Overflowed) {
11644           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11645                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11646                                     << FXResult.toString() << T
11647                                     << E->getSourceRange()
11648                                     << clang::SourceRange(CC));
11649           return;
11650         }
11651       }
11652     }
11653   } else if (Target->isUnsaturatedFixedPointType()) {
11654     if (Source->isIntegerType()) {
11655       Expr::EvalResult Result;
11656       if (!S.isConstantEvaluated() &&
11657           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11658         llvm::APSInt Value = Result.Val.getInt();
11659 
11660         bool Overflowed;
11661         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11662             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11663 
11664         if (Overflowed) {
11665           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11666                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11667                                     << Value.toString(/*Radix=*/10) << T
11668                                     << E->getSourceRange()
11669                                     << clang::SourceRange(CC));
11670           return;
11671         }
11672       }
11673     }
11674   }
11675 
11676   // If we are casting an integer type to a floating point type without
11677   // initialization-list syntax, we might lose accuracy if the floating
11678   // point type has a narrower significand than the integer type.
11679   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
11680       TargetBT->isFloatingType() && !IsListInit) {
11681     // Determine the number of precision bits in the source integer type.
11682     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11683     unsigned int SourcePrecision = SourceRange.Width;
11684 
11685     // Determine the number of precision bits in the
11686     // target floating point type.
11687     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
11688         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11689 
11690     if (SourcePrecision > 0 && TargetPrecision > 0 &&
11691         SourcePrecision > TargetPrecision) {
11692 
11693       llvm::APSInt SourceInt;
11694       if (E->isIntegerConstantExpr(SourceInt, S.Context)) {
11695         // If the source integer is a constant, convert it to the target
11696         // floating point type. Issue a warning if the value changes
11697         // during the whole conversion.
11698         llvm::APFloat TargetFloatValue(
11699             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
11700         llvm::APFloat::opStatus ConversionStatus =
11701             TargetFloatValue.convertFromAPInt(
11702                 SourceInt, SourceBT->isSignedInteger(),
11703                 llvm::APFloat::rmNearestTiesToEven);
11704 
11705         if (ConversionStatus != llvm::APFloat::opOK) {
11706           std::string PrettySourceValue = SourceInt.toString(10);
11707           SmallString<32> PrettyTargetValue;
11708           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
11709 
11710           S.DiagRuntimeBehavior(
11711               E->getExprLoc(), E,
11712               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
11713                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
11714                   << E->getSourceRange() << clang::SourceRange(CC));
11715         }
11716       } else {
11717         // Otherwise, the implicit conversion may lose precision.
11718         DiagnoseImpCast(S, E, T, CC,
11719                         diag::warn_impcast_integer_float_precision);
11720       }
11721     }
11722   }
11723 
11724   DiagnoseNullConversion(S, E, T, CC);
11725 
11726   S.DiscardMisalignedMemberAddress(Target, E);
11727 
11728   if (Target->isBooleanType())
11729     DiagnoseIntInBoolContext(S, E);
11730 
11731   if (!Source->isIntegerType() || !Target->isIntegerType())
11732     return;
11733 
11734   // TODO: remove this early return once the false positives for constant->bool
11735   // in templates, macros, etc, are reduced or removed.
11736   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11737     return;
11738 
11739   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
11740       !E->isKnownToHaveBooleanValue()) {
11741     return adornObjCBoolConversionDiagWithTernaryFixit(
11742         S, E,
11743         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
11744             << E->getType());
11745   }
11746 
11747   IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated());
11748   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11749 
11750   if (SourceRange.Width > TargetRange.Width) {
11751     // If the source is a constant, use a default-on diagnostic.
11752     // TODO: this should happen for bitfield stores, too.
11753     Expr::EvalResult Result;
11754     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
11755                          S.isConstantEvaluated())) {
11756       llvm::APSInt Value(32);
11757       Value = Result.Val.getInt();
11758 
11759       if (S.SourceMgr.isInSystemMacro(CC))
11760         return;
11761 
11762       std::string PrettySourceValue = Value.toString(10);
11763       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11764 
11765       S.DiagRuntimeBehavior(
11766           E->getExprLoc(), E,
11767           S.PDiag(diag::warn_impcast_integer_precision_constant)
11768               << PrettySourceValue << PrettyTargetValue << E->getType() << T
11769               << E->getSourceRange() << clang::SourceRange(CC));
11770       return;
11771     }
11772 
11773     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11774     if (S.SourceMgr.isInSystemMacro(CC))
11775       return;
11776 
11777     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11778       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11779                              /* pruneControlFlow */ true);
11780     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11781   }
11782 
11783   if (TargetRange.Width > SourceRange.Width) {
11784     if (auto *UO = dyn_cast<UnaryOperator>(E))
11785       if (UO->getOpcode() == UO_Minus)
11786         if (Source->isUnsignedIntegerType()) {
11787           if (Target->isUnsignedIntegerType())
11788             return DiagnoseImpCast(S, E, T, CC,
11789                                    diag::warn_impcast_high_order_zero_bits);
11790           if (Target->isSignedIntegerType())
11791             return DiagnoseImpCast(S, E, T, CC,
11792                                    diag::warn_impcast_nonnegative_result);
11793         }
11794   }
11795 
11796   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11797       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11798     // Warn when doing a signed to signed conversion, warn if the positive
11799     // source value is exactly the width of the target type, which will
11800     // cause a negative value to be stored.
11801 
11802     Expr::EvalResult Result;
11803     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11804         !S.SourceMgr.isInSystemMacro(CC)) {
11805       llvm::APSInt Value = Result.Val.getInt();
11806       if (isSameWidthConstantConversion(S, E, T, CC)) {
11807         std::string PrettySourceValue = Value.toString(10);
11808         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11809 
11810         S.DiagRuntimeBehavior(
11811             E->getExprLoc(), E,
11812             S.PDiag(diag::warn_impcast_integer_precision_constant)
11813                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11814                 << E->getSourceRange() << clang::SourceRange(CC));
11815         return;
11816       }
11817     }
11818 
11819     // Fall through for non-constants to give a sign conversion warning.
11820   }
11821 
11822   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11823       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11824        SourceRange.Width == TargetRange.Width)) {
11825     if (S.SourceMgr.isInSystemMacro(CC))
11826       return;
11827 
11828     unsigned DiagID = diag::warn_impcast_integer_sign;
11829 
11830     // Traditionally, gcc has warned about this under -Wsign-compare.
11831     // We also want to warn about it in -Wconversion.
11832     // So if -Wconversion is off, use a completely identical diagnostic
11833     // in the sign-compare group.
11834     // The conditional-checking code will
11835     if (ICContext) {
11836       DiagID = diag::warn_impcast_integer_sign_conditional;
11837       *ICContext = true;
11838     }
11839 
11840     return DiagnoseImpCast(S, E, T, CC, DiagID);
11841   }
11842 
11843   // Diagnose conversions between different enumeration types.
11844   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11845   // type, to give us better diagnostics.
11846   QualType SourceType = E->getType();
11847   if (!S.getLangOpts().CPlusPlus) {
11848     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11849       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11850         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11851         SourceType = S.Context.getTypeDeclType(Enum);
11852         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11853       }
11854   }
11855 
11856   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11857     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11858       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11859           TargetEnum->getDecl()->hasNameForLinkage() &&
11860           SourceEnum != TargetEnum) {
11861         if (S.SourceMgr.isInSystemMacro(CC))
11862           return;
11863 
11864         return DiagnoseImpCast(S, E, SourceType, T, CC,
11865                                diag::warn_impcast_different_enum_types);
11866       }
11867 }
11868 
11869 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11870                                      SourceLocation CC, QualType T);
11871 
11872 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11873                                     SourceLocation CC, bool &ICContext) {
11874   E = E->IgnoreParenImpCasts();
11875 
11876   if (isa<ConditionalOperator>(E))
11877     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11878 
11879   AnalyzeImplicitConversions(S, E, CC);
11880   if (E->getType() != T)
11881     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11882 }
11883 
11884 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11885                                      SourceLocation CC, QualType T) {
11886   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11887 
11888   bool Suspicious = false;
11889   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11890   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11891   CheckConditionalWithEnumTypes(S, E->getBeginLoc(), E->getTrueExpr(),
11892                                 E->getFalseExpr());
11893 
11894   if (T->isBooleanType())
11895     DiagnoseIntInBoolContext(S, E);
11896 
11897   // If -Wconversion would have warned about either of the candidates
11898   // for a signedness conversion to the context type...
11899   if (!Suspicious) return;
11900 
11901   // ...but it's currently ignored...
11902   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11903     return;
11904 
11905   // ...then check whether it would have warned about either of the
11906   // candidates for a signedness conversion to the condition type.
11907   if (E->getType() == T) return;
11908 
11909   Suspicious = false;
11910   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11911                           E->getType(), CC, &Suspicious);
11912   if (!Suspicious)
11913     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11914                             E->getType(), CC, &Suspicious);
11915 }
11916 
11917 /// Check conversion of given expression to boolean.
11918 /// Input argument E is a logical expression.
11919 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11920   if (S.getLangOpts().Bool)
11921     return;
11922   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11923     return;
11924   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11925 }
11926 
11927 /// AnalyzeImplicitConversions - Find and report any interesting
11928 /// implicit conversions in the given expression.  There are a couple
11929 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11930 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
11931                                        bool IsListInit/*= false*/) {
11932   QualType T = OrigE->getType();
11933   Expr *E = OrigE->IgnoreParenImpCasts();
11934 
11935   // Propagate whether we are in a C++ list initialization expression.
11936   // If so, we do not issue warnings for implicit int-float conversion
11937   // precision loss, because C++11 narrowing already handles it.
11938   IsListInit =
11939       IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
11940 
11941   if (E->isTypeDependent() || E->isValueDependent())
11942     return;
11943 
11944   if (const auto *UO = dyn_cast<UnaryOperator>(E))
11945     if (UO->getOpcode() == UO_Not &&
11946         UO->getSubExpr()->isKnownToHaveBooleanValue())
11947       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
11948           << OrigE->getSourceRange() << T->isBooleanType()
11949           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
11950 
11951   // For conditional operators, we analyze the arguments as if they
11952   // were being fed directly into the output.
11953   if (isa<ConditionalOperator>(E)) {
11954     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11955     CheckConditionalOperator(S, CO, CC, T);
11956     return;
11957   }
11958 
11959   // Check implicit argument conversions for function calls.
11960   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11961     CheckImplicitArgumentConversions(S, Call, CC);
11962 
11963   // Go ahead and check any implicit conversions we might have skipped.
11964   // The non-canonical typecheck is just an optimization;
11965   // CheckImplicitConversion will filter out dead implicit conversions.
11966   if (E->getType() != T)
11967     CheckImplicitConversion(S, E, T, CC, nullptr, IsListInit);
11968 
11969   // Now continue drilling into this expression.
11970 
11971   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11972     // The bound subexpressions in a PseudoObjectExpr are not reachable
11973     // as transitive children.
11974     // FIXME: Use a more uniform representation for this.
11975     for (auto *SE : POE->semantics())
11976       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11977         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit);
11978   }
11979 
11980   // Skip past explicit casts.
11981   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11982     E = CE->getSubExpr()->IgnoreParenImpCasts();
11983     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11984       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11985     return AnalyzeImplicitConversions(S, E, CC, IsListInit);
11986   }
11987 
11988   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11989     // Do a somewhat different check with comparison operators.
11990     if (BO->isComparisonOp())
11991       return AnalyzeComparison(S, BO);
11992 
11993     // And with simple assignments.
11994     if (BO->getOpcode() == BO_Assign)
11995       return AnalyzeAssignment(S, BO);
11996     // And with compound assignments.
11997     if (BO->isAssignmentOp())
11998       return AnalyzeCompoundAssignment(S, BO);
11999   }
12000 
12001   // These break the otherwise-useful invariant below.  Fortunately,
12002   // we don't really need to recurse into them, because any internal
12003   // expressions should have been analyzed already when they were
12004   // built into statements.
12005   if (isa<StmtExpr>(E)) return;
12006 
12007   // Don't descend into unevaluated contexts.
12008   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12009 
12010   // Now just recurse over the expression's children.
12011   CC = E->getExprLoc();
12012   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12013   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12014   for (Stmt *SubStmt : E->children()) {
12015     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12016     if (!ChildExpr)
12017       continue;
12018 
12019     if (IsLogicalAndOperator &&
12020         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12021       // Ignore checking string literals that are in logical and operators.
12022       // This is a common pattern for asserts.
12023       continue;
12024     AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit);
12025   }
12026 
12027   if (BO && BO->isLogicalOp()) {
12028     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12029     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12030       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12031 
12032     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12033     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12034       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12035   }
12036 
12037   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12038     if (U->getOpcode() == UO_LNot) {
12039       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12040     } else if (U->getOpcode() != UO_AddrOf) {
12041       if (U->getSubExpr()->getType()->isAtomicType())
12042         S.Diag(U->getSubExpr()->getBeginLoc(),
12043                diag::warn_atomic_implicit_seq_cst);
12044     }
12045   }
12046 }
12047 
12048 /// Diagnose integer type and any valid implicit conversion to it.
12049 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12050   // Taking into account implicit conversions,
12051   // allow any integer.
12052   if (!E->getType()->isIntegerType()) {
12053     S.Diag(E->getBeginLoc(),
12054            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12055     return true;
12056   }
12057   // Potentially emit standard warnings for implicit conversions if enabled
12058   // using -Wconversion.
12059   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12060   return false;
12061 }
12062 
12063 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12064 // Returns true when emitting a warning about taking the address of a reference.
12065 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12066                               const PartialDiagnostic &PD) {
12067   E = E->IgnoreParenImpCasts();
12068 
12069   const FunctionDecl *FD = nullptr;
12070 
12071   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12072     if (!DRE->getDecl()->getType()->isReferenceType())
12073       return false;
12074   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12075     if (!M->getMemberDecl()->getType()->isReferenceType())
12076       return false;
12077   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12078     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12079       return false;
12080     FD = Call->getDirectCallee();
12081   } else {
12082     return false;
12083   }
12084 
12085   SemaRef.Diag(E->getExprLoc(), PD);
12086 
12087   // If possible, point to location of function.
12088   if (FD) {
12089     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12090   }
12091 
12092   return true;
12093 }
12094 
12095 // Returns true if the SourceLocation is expanded from any macro body.
12096 // Returns false if the SourceLocation is invalid, is from not in a macro
12097 // expansion, or is from expanded from a top-level macro argument.
12098 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12099   if (Loc.isInvalid())
12100     return false;
12101 
12102   while (Loc.isMacroID()) {
12103     if (SM.isMacroBodyExpansion(Loc))
12104       return true;
12105     Loc = SM.getImmediateMacroCallerLoc(Loc);
12106   }
12107 
12108   return false;
12109 }
12110 
12111 /// Diagnose pointers that are always non-null.
12112 /// \param E the expression containing the pointer
12113 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12114 /// compared to a null pointer
12115 /// \param IsEqual True when the comparison is equal to a null pointer
12116 /// \param Range Extra SourceRange to highlight in the diagnostic
12117 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12118                                         Expr::NullPointerConstantKind NullKind,
12119                                         bool IsEqual, SourceRange Range) {
12120   if (!E)
12121     return;
12122 
12123   // Don't warn inside macros.
12124   if (E->getExprLoc().isMacroID()) {
12125     const SourceManager &SM = getSourceManager();
12126     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12127         IsInAnyMacroBody(SM, Range.getBegin()))
12128       return;
12129   }
12130   E = E->IgnoreImpCasts();
12131 
12132   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12133 
12134   if (isa<CXXThisExpr>(E)) {
12135     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12136                                 : diag::warn_this_bool_conversion;
12137     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12138     return;
12139   }
12140 
12141   bool IsAddressOf = false;
12142 
12143   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12144     if (UO->getOpcode() != UO_AddrOf)
12145       return;
12146     IsAddressOf = true;
12147     E = UO->getSubExpr();
12148   }
12149 
12150   if (IsAddressOf) {
12151     unsigned DiagID = IsCompare
12152                           ? diag::warn_address_of_reference_null_compare
12153                           : diag::warn_address_of_reference_bool_conversion;
12154     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12155                                          << IsEqual;
12156     if (CheckForReference(*this, E, PD)) {
12157       return;
12158     }
12159   }
12160 
12161   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12162     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12163     std::string Str;
12164     llvm::raw_string_ostream S(Str);
12165     E->printPretty(S, nullptr, getPrintingPolicy());
12166     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12167                                 : diag::warn_cast_nonnull_to_bool;
12168     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12169       << E->getSourceRange() << Range << IsEqual;
12170     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12171   };
12172 
12173   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12174   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12175     if (auto *Callee = Call->getDirectCallee()) {
12176       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12177         ComplainAboutNonnullParamOrCall(A);
12178         return;
12179       }
12180     }
12181   }
12182 
12183   // Expect to find a single Decl.  Skip anything more complicated.
12184   ValueDecl *D = nullptr;
12185   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12186     D = R->getDecl();
12187   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12188     D = M->getMemberDecl();
12189   }
12190 
12191   // Weak Decls can be null.
12192   if (!D || D->isWeak())
12193     return;
12194 
12195   // Check for parameter decl with nonnull attribute
12196   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12197     if (getCurFunction() &&
12198         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12199       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12200         ComplainAboutNonnullParamOrCall(A);
12201         return;
12202       }
12203 
12204       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12205         // Skip function template not specialized yet.
12206         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12207           return;
12208         auto ParamIter = llvm::find(FD->parameters(), PV);
12209         assert(ParamIter != FD->param_end());
12210         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12211 
12212         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12213           if (!NonNull->args_size()) {
12214               ComplainAboutNonnullParamOrCall(NonNull);
12215               return;
12216           }
12217 
12218           for (const ParamIdx &ArgNo : NonNull->args()) {
12219             if (ArgNo.getASTIndex() == ParamNo) {
12220               ComplainAboutNonnullParamOrCall(NonNull);
12221               return;
12222             }
12223           }
12224         }
12225       }
12226     }
12227   }
12228 
12229   QualType T = D->getType();
12230   const bool IsArray = T->isArrayType();
12231   const bool IsFunction = T->isFunctionType();
12232 
12233   // Address of function is used to silence the function warning.
12234   if (IsAddressOf && IsFunction) {
12235     return;
12236   }
12237 
12238   // Found nothing.
12239   if (!IsAddressOf && !IsFunction && !IsArray)
12240     return;
12241 
12242   // Pretty print the expression for the diagnostic.
12243   std::string Str;
12244   llvm::raw_string_ostream S(Str);
12245   E->printPretty(S, nullptr, getPrintingPolicy());
12246 
12247   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12248                               : diag::warn_impcast_pointer_to_bool;
12249   enum {
12250     AddressOf,
12251     FunctionPointer,
12252     ArrayPointer
12253   } DiagType;
12254   if (IsAddressOf)
12255     DiagType = AddressOf;
12256   else if (IsFunction)
12257     DiagType = FunctionPointer;
12258   else if (IsArray)
12259     DiagType = ArrayPointer;
12260   else
12261     llvm_unreachable("Could not determine diagnostic.");
12262   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12263                                 << Range << IsEqual;
12264 
12265   if (!IsFunction)
12266     return;
12267 
12268   // Suggest '&' to silence the function warning.
12269   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12270       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12271 
12272   // Check to see if '()' fixit should be emitted.
12273   QualType ReturnType;
12274   UnresolvedSet<4> NonTemplateOverloads;
12275   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12276   if (ReturnType.isNull())
12277     return;
12278 
12279   if (IsCompare) {
12280     // There are two cases here.  If there is null constant, the only suggest
12281     // for a pointer return type.  If the null is 0, then suggest if the return
12282     // type is a pointer or an integer type.
12283     if (!ReturnType->isPointerType()) {
12284       if (NullKind == Expr::NPCK_ZeroExpression ||
12285           NullKind == Expr::NPCK_ZeroLiteral) {
12286         if (!ReturnType->isIntegerType())
12287           return;
12288       } else {
12289         return;
12290       }
12291     }
12292   } else { // !IsCompare
12293     // For function to bool, only suggest if the function pointer has bool
12294     // return type.
12295     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12296       return;
12297   }
12298   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12299       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12300 }
12301 
12302 /// Diagnoses "dangerous" implicit conversions within the given
12303 /// expression (which is a full expression).  Implements -Wconversion
12304 /// and -Wsign-compare.
12305 ///
12306 /// \param CC the "context" location of the implicit conversion, i.e.
12307 ///   the most location of the syntactic entity requiring the implicit
12308 ///   conversion
12309 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12310   // Don't diagnose in unevaluated contexts.
12311   if (isUnevaluatedContext())
12312     return;
12313 
12314   // Don't diagnose for value- or type-dependent expressions.
12315   if (E->isTypeDependent() || E->isValueDependent())
12316     return;
12317 
12318   // Check for array bounds violations in cases where the check isn't triggered
12319   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12320   // ArraySubscriptExpr is on the RHS of a variable initialization.
12321   CheckArrayAccess(E);
12322 
12323   // This is not the right CC for (e.g.) a variable initialization.
12324   AnalyzeImplicitConversions(*this, E, CC);
12325 }
12326 
12327 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12328 /// Input argument E is a logical expression.
12329 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12330   ::CheckBoolLikeConversion(*this, E, CC);
12331 }
12332 
12333 /// Diagnose when expression is an integer constant expression and its evaluation
12334 /// results in integer overflow
12335 void Sema::CheckForIntOverflow (Expr *E) {
12336   // Use a work list to deal with nested struct initializers.
12337   SmallVector<Expr *, 2> Exprs(1, E);
12338 
12339   do {
12340     Expr *OriginalE = Exprs.pop_back_val();
12341     Expr *E = OriginalE->IgnoreParenCasts();
12342 
12343     if (isa<BinaryOperator>(E)) {
12344       E->EvaluateForOverflow(Context);
12345       continue;
12346     }
12347 
12348     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12349       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12350     else if (isa<ObjCBoxedExpr>(OriginalE))
12351       E->EvaluateForOverflow(Context);
12352     else if (auto Call = dyn_cast<CallExpr>(E))
12353       Exprs.append(Call->arg_begin(), Call->arg_end());
12354     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12355       Exprs.append(Message->arg_begin(), Message->arg_end());
12356   } while (!Exprs.empty());
12357 }
12358 
12359 namespace {
12360 
12361 /// Visitor for expressions which looks for unsequenced operations on the
12362 /// same object.
12363 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
12364   using Base = EvaluatedExprVisitor<SequenceChecker>;
12365 
12366   /// A tree of sequenced regions within an expression. Two regions are
12367   /// unsequenced if one is an ancestor or a descendent of the other. When we
12368   /// finish processing an expression with sequencing, such as a comma
12369   /// expression, we fold its tree nodes into its parent, since they are
12370   /// unsequenced with respect to nodes we will visit later.
12371   class SequenceTree {
12372     struct Value {
12373       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12374       unsigned Parent : 31;
12375       unsigned Merged : 1;
12376     };
12377     SmallVector<Value, 8> Values;
12378 
12379   public:
12380     /// A region within an expression which may be sequenced with respect
12381     /// to some other region.
12382     class Seq {
12383       friend class SequenceTree;
12384 
12385       unsigned Index;
12386 
12387       explicit Seq(unsigned N) : Index(N) {}
12388 
12389     public:
12390       Seq() : Index(0) {}
12391     };
12392 
12393     SequenceTree() { Values.push_back(Value(0)); }
12394     Seq root() const { return Seq(0); }
12395 
12396     /// Create a new sequence of operations, which is an unsequenced
12397     /// subset of \p Parent. This sequence of operations is sequenced with
12398     /// respect to other children of \p Parent.
12399     Seq allocate(Seq Parent) {
12400       Values.push_back(Value(Parent.Index));
12401       return Seq(Values.size() - 1);
12402     }
12403 
12404     /// Merge a sequence of operations into its parent.
12405     void merge(Seq S) {
12406       Values[S.Index].Merged = true;
12407     }
12408 
12409     /// Determine whether two operations are unsequenced. This operation
12410     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12411     /// should have been merged into its parent as appropriate.
12412     bool isUnsequenced(Seq Cur, Seq Old) {
12413       unsigned C = representative(Cur.Index);
12414       unsigned Target = representative(Old.Index);
12415       while (C >= Target) {
12416         if (C == Target)
12417           return true;
12418         C = Values[C].Parent;
12419       }
12420       return false;
12421     }
12422 
12423   private:
12424     /// Pick a representative for a sequence.
12425     unsigned representative(unsigned K) {
12426       if (Values[K].Merged)
12427         // Perform path compression as we go.
12428         return Values[K].Parent = representative(Values[K].Parent);
12429       return K;
12430     }
12431   };
12432 
12433   /// An object for which we can track unsequenced uses.
12434   using Object = NamedDecl *;
12435 
12436   /// Different flavors of object usage which we track. We only track the
12437   /// least-sequenced usage of each kind.
12438   enum UsageKind {
12439     /// A read of an object. Multiple unsequenced reads are OK.
12440     UK_Use,
12441 
12442     /// A modification of an object which is sequenced before the value
12443     /// computation of the expression, such as ++n in C++.
12444     UK_ModAsValue,
12445 
12446     /// A modification of an object which is not sequenced before the value
12447     /// computation of the expression, such as n++.
12448     UK_ModAsSideEffect,
12449 
12450     UK_Count = UK_ModAsSideEffect + 1
12451   };
12452 
12453   struct Usage {
12454     Expr *Use;
12455     SequenceTree::Seq Seq;
12456 
12457     Usage() : Use(nullptr), Seq() {}
12458   };
12459 
12460   struct UsageInfo {
12461     Usage Uses[UK_Count];
12462 
12463     /// Have we issued a diagnostic for this variable already?
12464     bool Diagnosed;
12465 
12466     UsageInfo() : Uses(), Diagnosed(false) {}
12467   };
12468   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
12469 
12470   Sema &SemaRef;
12471 
12472   /// Sequenced regions within the expression.
12473   SequenceTree Tree;
12474 
12475   /// Declaration modifications and references which we have seen.
12476   UsageInfoMap UsageMap;
12477 
12478   /// The region we are currently within.
12479   SequenceTree::Seq Region;
12480 
12481   /// Filled in with declarations which were modified as a side-effect
12482   /// (that is, post-increment operations).
12483   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
12484 
12485   /// Expressions to check later. We defer checking these to reduce
12486   /// stack usage.
12487   SmallVectorImpl<Expr *> &WorkList;
12488 
12489   /// RAII object wrapping the visitation of a sequenced subexpression of an
12490   /// expression. At the end of this process, the side-effects of the evaluation
12491   /// become sequenced with respect to the value computation of the result, so
12492   /// we downgrade any UK_ModAsSideEffect within the evaluation to
12493   /// UK_ModAsValue.
12494   struct SequencedSubexpression {
12495     SequencedSubexpression(SequenceChecker &Self)
12496       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
12497       Self.ModAsSideEffect = &ModAsSideEffect;
12498     }
12499 
12500     ~SequencedSubexpression() {
12501       for (auto &M : llvm::reverse(ModAsSideEffect)) {
12502         UsageInfo &U = Self.UsageMap[M.first];
12503         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
12504         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
12505         SideEffectUsage = M.second;
12506       }
12507       Self.ModAsSideEffect = OldModAsSideEffect;
12508     }
12509 
12510     SequenceChecker &Self;
12511     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
12512     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
12513   };
12514 
12515   /// RAII object wrapping the visitation of a subexpression which we might
12516   /// choose to evaluate as a constant. If any subexpression is evaluated and
12517   /// found to be non-constant, this allows us to suppress the evaluation of
12518   /// the outer expression.
12519   class EvaluationTracker {
12520   public:
12521     EvaluationTracker(SequenceChecker &Self)
12522         : Self(Self), Prev(Self.EvalTracker) {
12523       Self.EvalTracker = this;
12524     }
12525 
12526     ~EvaluationTracker() {
12527       Self.EvalTracker = Prev;
12528       if (Prev)
12529         Prev->EvalOK &= EvalOK;
12530     }
12531 
12532     bool evaluate(const Expr *E, bool &Result) {
12533       if (!EvalOK || E->isValueDependent())
12534         return false;
12535       EvalOK = E->EvaluateAsBooleanCondition(
12536           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
12537       return EvalOK;
12538     }
12539 
12540   private:
12541     SequenceChecker &Self;
12542     EvaluationTracker *Prev;
12543     bool EvalOK = true;
12544   } *EvalTracker = nullptr;
12545 
12546   /// Find the object which is produced by the specified expression,
12547   /// if any.
12548   Object getObject(Expr *E, bool Mod) const {
12549     E = E->IgnoreParenCasts();
12550     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12551       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
12552         return getObject(UO->getSubExpr(), Mod);
12553     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12554       if (BO->getOpcode() == BO_Comma)
12555         return getObject(BO->getRHS(), Mod);
12556       if (Mod && BO->isAssignmentOp())
12557         return getObject(BO->getLHS(), Mod);
12558     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12559       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
12560       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
12561         return ME->getMemberDecl();
12562     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12563       // FIXME: If this is a reference, map through to its value.
12564       return DRE->getDecl();
12565     return nullptr;
12566   }
12567 
12568   /// Note that an object was modified or used by an expression.
12569   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
12570     Usage &U = UI.Uses[UK];
12571     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
12572       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
12573         ModAsSideEffect->push_back(std::make_pair(O, U));
12574       U.Use = Ref;
12575       U.Seq = Region;
12576     }
12577   }
12578 
12579   /// Check whether a modification or use conflicts with a prior usage.
12580   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
12581                   bool IsModMod) {
12582     if (UI.Diagnosed)
12583       return;
12584 
12585     const Usage &U = UI.Uses[OtherKind];
12586     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
12587       return;
12588 
12589     Expr *Mod = U.Use;
12590     Expr *ModOrUse = Ref;
12591     if (OtherKind == UK_Use)
12592       std::swap(Mod, ModOrUse);
12593 
12594     SemaRef.DiagRuntimeBehavior(
12595         Mod->getExprLoc(), {Mod, ModOrUse},
12596         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
12597                                : diag::warn_unsequenced_mod_use)
12598             << O << SourceRange(ModOrUse->getExprLoc()));
12599     UI.Diagnosed = true;
12600   }
12601 
12602   void notePreUse(Object O, Expr *Use) {
12603     UsageInfo &U = UsageMap[O];
12604     // Uses conflict with other modifications.
12605     checkUsage(O, U, Use, UK_ModAsValue, false);
12606   }
12607 
12608   void notePostUse(Object O, Expr *Use) {
12609     UsageInfo &U = UsageMap[O];
12610     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
12611     addUsage(U, O, Use, UK_Use);
12612   }
12613 
12614   void notePreMod(Object O, Expr *Mod) {
12615     UsageInfo &U = UsageMap[O];
12616     // Modifications conflict with other modifications and with uses.
12617     checkUsage(O, U, Mod, UK_ModAsValue, true);
12618     checkUsage(O, U, Mod, UK_Use, false);
12619   }
12620 
12621   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12622     UsageInfo &U = UsageMap[O];
12623     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12624     addUsage(U, O, Use, UK);
12625   }
12626 
12627 public:
12628   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12629       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12630     Visit(E);
12631   }
12632 
12633   void VisitStmt(Stmt *S) {
12634     // Skip all statements which aren't expressions for now.
12635   }
12636 
12637   void VisitExpr(Expr *E) {
12638     // By default, just recurse to evaluated subexpressions.
12639     Base::VisitStmt(E);
12640   }
12641 
12642   void VisitCastExpr(CastExpr *E) {
12643     Object O = Object();
12644     if (E->getCastKind() == CK_LValueToRValue)
12645       O = getObject(E->getSubExpr(), false);
12646 
12647     if (O)
12648       notePreUse(O, E);
12649     VisitExpr(E);
12650     if (O)
12651       notePostUse(O, E);
12652   }
12653 
12654   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12655     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12656     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12657     SequenceTree::Seq OldRegion = Region;
12658 
12659     {
12660       SequencedSubexpression SeqBefore(*this);
12661       Region = BeforeRegion;
12662       Visit(SequencedBefore);
12663     }
12664 
12665     Region = AfterRegion;
12666     Visit(SequencedAfter);
12667 
12668     Region = OldRegion;
12669 
12670     Tree.merge(BeforeRegion);
12671     Tree.merge(AfterRegion);
12672   }
12673 
12674   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12675     // C++17 [expr.sub]p1:
12676     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12677     //   expression E1 is sequenced before the expression E2.
12678     if (SemaRef.getLangOpts().CPlusPlus17)
12679       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12680     else
12681       Base::VisitStmt(ASE);
12682   }
12683 
12684   void VisitBinComma(BinaryOperator *BO) {
12685     // C++11 [expr.comma]p1:
12686     //   Every value computation and side effect associated with the left
12687     //   expression is sequenced before every value computation and side
12688     //   effect associated with the right expression.
12689     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12690   }
12691 
12692   void VisitBinAssign(BinaryOperator *BO) {
12693     // The modification is sequenced after the value computation of the LHS
12694     // and RHS, so check it before inspecting the operands and update the
12695     // map afterwards.
12696     Object O = getObject(BO->getLHS(), true);
12697     if (!O)
12698       return VisitExpr(BO);
12699 
12700     notePreMod(O, BO);
12701 
12702     // C++11 [expr.ass]p7:
12703     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12704     //   only once.
12705     //
12706     // Therefore, for a compound assignment operator, O is considered used
12707     // everywhere except within the evaluation of E1 itself.
12708     if (isa<CompoundAssignOperator>(BO))
12709       notePreUse(O, BO);
12710 
12711     Visit(BO->getLHS());
12712 
12713     if (isa<CompoundAssignOperator>(BO))
12714       notePostUse(O, BO);
12715 
12716     Visit(BO->getRHS());
12717 
12718     // C++11 [expr.ass]p1:
12719     //   the assignment is sequenced [...] before the value computation of the
12720     //   assignment expression.
12721     // C11 6.5.16/3 has no such rule.
12722     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12723                                                        : UK_ModAsSideEffect);
12724   }
12725 
12726   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12727     VisitBinAssign(CAO);
12728   }
12729 
12730   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12731   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12732   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12733     Object O = getObject(UO->getSubExpr(), true);
12734     if (!O)
12735       return VisitExpr(UO);
12736 
12737     notePreMod(O, UO);
12738     Visit(UO->getSubExpr());
12739     // C++11 [expr.pre.incr]p1:
12740     //   the expression ++x is equivalent to x+=1
12741     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12742                                                        : UK_ModAsSideEffect);
12743   }
12744 
12745   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12746   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12747   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12748     Object O = getObject(UO->getSubExpr(), true);
12749     if (!O)
12750       return VisitExpr(UO);
12751 
12752     notePreMod(O, UO);
12753     Visit(UO->getSubExpr());
12754     notePostMod(O, UO, UK_ModAsSideEffect);
12755   }
12756 
12757   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12758   void VisitBinLOr(BinaryOperator *BO) {
12759     // The side-effects of the LHS of an '&&' are sequenced before the
12760     // value computation of the RHS, and hence before the value computation
12761     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12762     // as if they were unconditionally sequenced.
12763     EvaluationTracker Eval(*this);
12764     {
12765       SequencedSubexpression Sequenced(*this);
12766       Visit(BO->getLHS());
12767     }
12768 
12769     bool Result;
12770     if (Eval.evaluate(BO->getLHS(), Result)) {
12771       if (!Result)
12772         Visit(BO->getRHS());
12773     } else {
12774       // Check for unsequenced operations in the RHS, treating it as an
12775       // entirely separate evaluation.
12776       //
12777       // FIXME: If there are operations in the RHS which are unsequenced
12778       // with respect to operations outside the RHS, and those operations
12779       // are unconditionally evaluated, diagnose them.
12780       WorkList.push_back(BO->getRHS());
12781     }
12782   }
12783   void VisitBinLAnd(BinaryOperator *BO) {
12784     EvaluationTracker Eval(*this);
12785     {
12786       SequencedSubexpression Sequenced(*this);
12787       Visit(BO->getLHS());
12788     }
12789 
12790     bool Result;
12791     if (Eval.evaluate(BO->getLHS(), Result)) {
12792       if (Result)
12793         Visit(BO->getRHS());
12794     } else {
12795       WorkList.push_back(BO->getRHS());
12796     }
12797   }
12798 
12799   // Only visit the condition, unless we can be sure which subexpression will
12800   // be chosen.
12801   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12802     EvaluationTracker Eval(*this);
12803     {
12804       SequencedSubexpression Sequenced(*this);
12805       Visit(CO->getCond());
12806     }
12807 
12808     bool Result;
12809     if (Eval.evaluate(CO->getCond(), Result))
12810       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12811     else {
12812       WorkList.push_back(CO->getTrueExpr());
12813       WorkList.push_back(CO->getFalseExpr());
12814     }
12815   }
12816 
12817   void VisitCallExpr(CallExpr *CE) {
12818     // C++11 [intro.execution]p15:
12819     //   When calling a function [...], every value computation and side effect
12820     //   associated with any argument expression, or with the postfix expression
12821     //   designating the called function, is sequenced before execution of every
12822     //   expression or statement in the body of the function [and thus before
12823     //   the value computation of its result].
12824     SequencedSubexpression Sequenced(*this);
12825     Base::VisitCallExpr(CE);
12826 
12827     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12828   }
12829 
12830   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12831     // This is a call, so all subexpressions are sequenced before the result.
12832     SequencedSubexpression Sequenced(*this);
12833 
12834     if (!CCE->isListInitialization())
12835       return VisitExpr(CCE);
12836 
12837     // In C++11, list initializations are sequenced.
12838     SmallVector<SequenceTree::Seq, 32> Elts;
12839     SequenceTree::Seq Parent = Region;
12840     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12841                                         E = CCE->arg_end();
12842          I != E; ++I) {
12843       Region = Tree.allocate(Parent);
12844       Elts.push_back(Region);
12845       Visit(*I);
12846     }
12847 
12848     // Forget that the initializers are sequenced.
12849     Region = Parent;
12850     for (unsigned I = 0; I < Elts.size(); ++I)
12851       Tree.merge(Elts[I]);
12852   }
12853 
12854   void VisitInitListExpr(InitListExpr *ILE) {
12855     if (!SemaRef.getLangOpts().CPlusPlus11)
12856       return VisitExpr(ILE);
12857 
12858     // In C++11, list initializations are sequenced.
12859     SmallVector<SequenceTree::Seq, 32> Elts;
12860     SequenceTree::Seq Parent = Region;
12861     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12862       Expr *E = ILE->getInit(I);
12863       if (!E) continue;
12864       Region = Tree.allocate(Parent);
12865       Elts.push_back(Region);
12866       Visit(E);
12867     }
12868 
12869     // Forget that the initializers are sequenced.
12870     Region = Parent;
12871     for (unsigned I = 0; I < Elts.size(); ++I)
12872       Tree.merge(Elts[I]);
12873   }
12874 };
12875 
12876 } // namespace
12877 
12878 void Sema::CheckUnsequencedOperations(Expr *E) {
12879   SmallVector<Expr *, 8> WorkList;
12880   WorkList.push_back(E);
12881   while (!WorkList.empty()) {
12882     Expr *Item = WorkList.pop_back_val();
12883     SequenceChecker(*this, Item, WorkList);
12884   }
12885 }
12886 
12887 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12888                               bool IsConstexpr) {
12889   llvm::SaveAndRestore<bool> ConstantContext(
12890       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
12891   CheckImplicitConversions(E, CheckLoc);
12892   if (!E->isInstantiationDependent())
12893     CheckUnsequencedOperations(E);
12894   if (!IsConstexpr && !E->isValueDependent())
12895     CheckForIntOverflow(E);
12896   DiagnoseMisalignedMembers();
12897 }
12898 
12899 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12900                                        FieldDecl *BitField,
12901                                        Expr *Init) {
12902   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12903 }
12904 
12905 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12906                                          SourceLocation Loc) {
12907   if (!PType->isVariablyModifiedType())
12908     return;
12909   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12910     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12911     return;
12912   }
12913   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12914     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12915     return;
12916   }
12917   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12918     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12919     return;
12920   }
12921 
12922   const ArrayType *AT = S.Context.getAsArrayType(PType);
12923   if (!AT)
12924     return;
12925 
12926   if (AT->getSizeModifier() != ArrayType::Star) {
12927     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12928     return;
12929   }
12930 
12931   S.Diag(Loc, diag::err_array_star_in_function_definition);
12932 }
12933 
12934 /// CheckParmsForFunctionDef - Check that the parameters of the given
12935 /// function are appropriate for the definition of a function. This
12936 /// takes care of any checks that cannot be performed on the
12937 /// declaration itself, e.g., that the types of each of the function
12938 /// parameters are complete.
12939 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12940                                     bool CheckParameterNames) {
12941   bool HasInvalidParm = false;
12942   for (ParmVarDecl *Param : Parameters) {
12943     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12944     // function declarator that is part of a function definition of
12945     // that function shall not have incomplete type.
12946     //
12947     // This is also C++ [dcl.fct]p6.
12948     if (!Param->isInvalidDecl() &&
12949         RequireCompleteType(Param->getLocation(), Param->getType(),
12950                             diag::err_typecheck_decl_incomplete_type)) {
12951       Param->setInvalidDecl();
12952       HasInvalidParm = true;
12953     }
12954 
12955     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12956     // declaration of each parameter shall include an identifier.
12957     if (CheckParameterNames &&
12958         Param->getIdentifier() == nullptr &&
12959         !Param->isImplicit() &&
12960         !getLangOpts().CPlusPlus)
12961       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12962 
12963     // C99 6.7.5.3p12:
12964     //   If the function declarator is not part of a definition of that
12965     //   function, parameters may have incomplete type and may use the [*]
12966     //   notation in their sequences of declarator specifiers to specify
12967     //   variable length array types.
12968     QualType PType = Param->getOriginalType();
12969     // FIXME: This diagnostic should point the '[*]' if source-location
12970     // information is added for it.
12971     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12972 
12973     // If the parameter is a c++ class type and it has to be destructed in the
12974     // callee function, declare the destructor so that it can be called by the
12975     // callee function. Do not perform any direct access check on the dtor here.
12976     if (!Param->isInvalidDecl()) {
12977       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12978         if (!ClassDecl->isInvalidDecl() &&
12979             !ClassDecl->hasIrrelevantDestructor() &&
12980             !ClassDecl->isDependentContext() &&
12981             ClassDecl->isParamDestroyedInCallee()) {
12982           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12983           MarkFunctionReferenced(Param->getLocation(), Destructor);
12984           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12985         }
12986       }
12987     }
12988 
12989     // Parameters with the pass_object_size attribute only need to be marked
12990     // constant at function definitions. Because we lack information about
12991     // whether we're on a declaration or definition when we're instantiating the
12992     // attribute, we need to check for constness here.
12993     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12994       if (!Param->getType().isConstQualified())
12995         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12996             << Attr->getSpelling() << 1;
12997 
12998     // Check for parameter names shadowing fields from the class.
12999     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13000       // The owning context for the parameter should be the function, but we
13001       // want to see if this function's declaration context is a record.
13002       DeclContext *DC = Param->getDeclContext();
13003       if (DC && DC->isFunctionOrMethod()) {
13004         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13005           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13006                                      RD, /*DeclIsField*/ false);
13007       }
13008     }
13009   }
13010 
13011   return HasInvalidParm;
13012 }
13013 
13014 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
13015 /// or MemberExpr.
13016 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
13017                               ASTContext &Context) {
13018   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
13019     return Context.getDeclAlign(DRE->getDecl());
13020 
13021   if (const auto *ME = dyn_cast<MemberExpr>(E))
13022     return Context.getDeclAlign(ME->getMemberDecl());
13023 
13024   return TypeAlign;
13025 }
13026 
13027 /// CheckCastAlign - Implements -Wcast-align, which warns when a
13028 /// pointer cast increases the alignment requirements.
13029 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
13030   // This is actually a lot of work to potentially be doing on every
13031   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
13032   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
13033     return;
13034 
13035   // Ignore dependent types.
13036   if (T->isDependentType() || Op->getType()->isDependentType())
13037     return;
13038 
13039   // Require that the destination be a pointer type.
13040   const PointerType *DestPtr = T->getAs<PointerType>();
13041   if (!DestPtr) return;
13042 
13043   // If the destination has alignment 1, we're done.
13044   QualType DestPointee = DestPtr->getPointeeType();
13045   if (DestPointee->isIncompleteType()) return;
13046   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
13047   if (DestAlign.isOne()) return;
13048 
13049   // Require that the source be a pointer type.
13050   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
13051   if (!SrcPtr) return;
13052   QualType SrcPointee = SrcPtr->getPointeeType();
13053 
13054   // Whitelist casts from cv void*.  We already implicitly
13055   // whitelisted casts to cv void*, since they have alignment 1.
13056   // Also whitelist casts involving incomplete types, which implicitly
13057   // includes 'void'.
13058   if (SrcPointee->isIncompleteType()) return;
13059 
13060   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
13061 
13062   if (auto *CE = dyn_cast<CastExpr>(Op)) {
13063     if (CE->getCastKind() == CK_ArrayToPointerDecay)
13064       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
13065   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
13066     if (UO->getOpcode() == UO_AddrOf)
13067       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
13068   }
13069 
13070   if (SrcAlign >= DestAlign) return;
13071 
13072   Diag(TRange.getBegin(), diag::warn_cast_align)
13073     << Op->getType() << T
13074     << static_cast<unsigned>(SrcAlign.getQuantity())
13075     << static_cast<unsigned>(DestAlign.getQuantity())
13076     << TRange << Op->getSourceRange();
13077 }
13078 
13079 /// Check whether this array fits the idiom of a size-one tail padded
13080 /// array member of a struct.
13081 ///
13082 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
13083 /// commonly used to emulate flexible arrays in C89 code.
13084 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
13085                                     const NamedDecl *ND) {
13086   if (Size != 1 || !ND) return false;
13087 
13088   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
13089   if (!FD) return false;
13090 
13091   // Don't consider sizes resulting from macro expansions or template argument
13092   // substitution to form C89 tail-padded arrays.
13093 
13094   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
13095   while (TInfo) {
13096     TypeLoc TL = TInfo->getTypeLoc();
13097     // Look through typedefs.
13098     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
13099       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
13100       TInfo = TDL->getTypeSourceInfo();
13101       continue;
13102     }
13103     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
13104       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
13105       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
13106         return false;
13107     }
13108     break;
13109   }
13110 
13111   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
13112   if (!RD) return false;
13113   if (RD->isUnion()) return false;
13114   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13115     if (!CRD->isStandardLayout()) return false;
13116   }
13117 
13118   // See if this is the last field decl in the record.
13119   const Decl *D = FD;
13120   while ((D = D->getNextDeclInContext()))
13121     if (isa<FieldDecl>(D))
13122       return false;
13123   return true;
13124 }
13125 
13126 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
13127                             const ArraySubscriptExpr *ASE,
13128                             bool AllowOnePastEnd, bool IndexNegated) {
13129   // Already diagnosed by the constant evaluator.
13130   if (isConstantEvaluated())
13131     return;
13132 
13133   IndexExpr = IndexExpr->IgnoreParenImpCasts();
13134   if (IndexExpr->isValueDependent())
13135     return;
13136 
13137   const Type *EffectiveType =
13138       BaseExpr->getType()->getPointeeOrArrayElementType();
13139   BaseExpr = BaseExpr->IgnoreParenCasts();
13140   const ConstantArrayType *ArrayTy =
13141       Context.getAsConstantArrayType(BaseExpr->getType());
13142 
13143   if (!ArrayTy)
13144     return;
13145 
13146   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
13147   if (EffectiveType->isDependentType() || BaseType->isDependentType())
13148     return;
13149 
13150   Expr::EvalResult Result;
13151   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
13152     return;
13153 
13154   llvm::APSInt index = Result.Val.getInt();
13155   if (IndexNegated)
13156     index = -index;
13157 
13158   const NamedDecl *ND = nullptr;
13159   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13160     ND = DRE->getDecl();
13161   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13162     ND = ME->getMemberDecl();
13163 
13164   if (index.isUnsigned() || !index.isNegative()) {
13165     // It is possible that the type of the base expression after
13166     // IgnoreParenCasts is incomplete, even though the type of the base
13167     // expression before IgnoreParenCasts is complete (see PR39746 for an
13168     // example). In this case we have no information about whether the array
13169     // access exceeds the array bounds. However we can still diagnose an array
13170     // access which precedes the array bounds.
13171     if (BaseType->isIncompleteType())
13172       return;
13173 
13174     llvm::APInt size = ArrayTy->getSize();
13175     if (!size.isStrictlyPositive())
13176       return;
13177 
13178     if (BaseType != EffectiveType) {
13179       // Make sure we're comparing apples to apples when comparing index to size
13180       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
13181       uint64_t array_typesize = Context.getTypeSize(BaseType);
13182       // Handle ptrarith_typesize being zero, such as when casting to void*
13183       if (!ptrarith_typesize) ptrarith_typesize = 1;
13184       if (ptrarith_typesize != array_typesize) {
13185         // There's a cast to a different size type involved
13186         uint64_t ratio = array_typesize / ptrarith_typesize;
13187         // TODO: Be smarter about handling cases where array_typesize is not a
13188         // multiple of ptrarith_typesize
13189         if (ptrarith_typesize * ratio == array_typesize)
13190           size *= llvm::APInt(size.getBitWidth(), ratio);
13191       }
13192     }
13193 
13194     if (size.getBitWidth() > index.getBitWidth())
13195       index = index.zext(size.getBitWidth());
13196     else if (size.getBitWidth() < index.getBitWidth())
13197       size = size.zext(index.getBitWidth());
13198 
13199     // For array subscripting the index must be less than size, but for pointer
13200     // arithmetic also allow the index (offset) to be equal to size since
13201     // computing the next address after the end of the array is legal and
13202     // commonly done e.g. in C++ iterators and range-based for loops.
13203     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
13204       return;
13205 
13206     // Also don't warn for arrays of size 1 which are members of some
13207     // structure. These are often used to approximate flexible arrays in C89
13208     // code.
13209     if (IsTailPaddedMemberArray(*this, size, ND))
13210       return;
13211 
13212     // Suppress the warning if the subscript expression (as identified by the
13213     // ']' location) and the index expression are both from macro expansions
13214     // within a system header.
13215     if (ASE) {
13216       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
13217           ASE->getRBracketLoc());
13218       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
13219         SourceLocation IndexLoc =
13220             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
13221         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
13222           return;
13223       }
13224     }
13225 
13226     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
13227     if (ASE)
13228       DiagID = diag::warn_array_index_exceeds_bounds;
13229 
13230     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13231                         PDiag(DiagID) << index.toString(10, true)
13232                                       << size.toString(10, true)
13233                                       << (unsigned)size.getLimitedValue(~0U)
13234                                       << IndexExpr->getSourceRange());
13235   } else {
13236     unsigned DiagID = diag::warn_array_index_precedes_bounds;
13237     if (!ASE) {
13238       DiagID = diag::warn_ptr_arith_precedes_bounds;
13239       if (index.isNegative()) index = -index;
13240     }
13241 
13242     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
13243                         PDiag(DiagID) << index.toString(10, true)
13244                                       << IndexExpr->getSourceRange());
13245   }
13246 
13247   if (!ND) {
13248     // Try harder to find a NamedDecl to point at in the note.
13249     while (const ArraySubscriptExpr *ASE =
13250            dyn_cast<ArraySubscriptExpr>(BaseExpr))
13251       BaseExpr = ASE->getBase()->IgnoreParenCasts();
13252     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
13253       ND = DRE->getDecl();
13254     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
13255       ND = ME->getMemberDecl();
13256   }
13257 
13258   if (ND)
13259     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
13260                         PDiag(diag::note_array_declared_here)
13261                             << ND->getDeclName());
13262 }
13263 
13264 void Sema::CheckArrayAccess(const Expr *expr) {
13265   int AllowOnePastEnd = 0;
13266   while (expr) {
13267     expr = expr->IgnoreParenImpCasts();
13268     switch (expr->getStmtClass()) {
13269       case Stmt::ArraySubscriptExprClass: {
13270         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
13271         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
13272                          AllowOnePastEnd > 0);
13273         expr = ASE->getBase();
13274         break;
13275       }
13276       case Stmt::MemberExprClass: {
13277         expr = cast<MemberExpr>(expr)->getBase();
13278         break;
13279       }
13280       case Stmt::OMPArraySectionExprClass: {
13281         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
13282         if (ASE->getLowerBound())
13283           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
13284                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
13285         return;
13286       }
13287       case Stmt::UnaryOperatorClass: {
13288         // Only unwrap the * and & unary operators
13289         const UnaryOperator *UO = cast<UnaryOperator>(expr);
13290         expr = UO->getSubExpr();
13291         switch (UO->getOpcode()) {
13292           case UO_AddrOf:
13293             AllowOnePastEnd++;
13294             break;
13295           case UO_Deref:
13296             AllowOnePastEnd--;
13297             break;
13298           default:
13299             return;
13300         }
13301         break;
13302       }
13303       case Stmt::ConditionalOperatorClass: {
13304         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
13305         if (const Expr *lhs = cond->getLHS())
13306           CheckArrayAccess(lhs);
13307         if (const Expr *rhs = cond->getRHS())
13308           CheckArrayAccess(rhs);
13309         return;
13310       }
13311       case Stmt::CXXOperatorCallExprClass: {
13312         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
13313         for (const auto *Arg : OCE->arguments())
13314           CheckArrayAccess(Arg);
13315         return;
13316       }
13317       default:
13318         return;
13319     }
13320   }
13321 }
13322 
13323 //===--- CHECK: Objective-C retain cycles ----------------------------------//
13324 
13325 namespace {
13326 
13327 struct RetainCycleOwner {
13328   VarDecl *Variable = nullptr;
13329   SourceRange Range;
13330   SourceLocation Loc;
13331   bool Indirect = false;
13332 
13333   RetainCycleOwner() = default;
13334 
13335   void setLocsFrom(Expr *e) {
13336     Loc = e->getExprLoc();
13337     Range = e->getSourceRange();
13338   }
13339 };
13340 
13341 } // namespace
13342 
13343 /// Consider whether capturing the given variable can possibly lead to
13344 /// a retain cycle.
13345 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
13346   // In ARC, it's captured strongly iff the variable has __strong
13347   // lifetime.  In MRR, it's captured strongly if the variable is
13348   // __block and has an appropriate type.
13349   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13350     return false;
13351 
13352   owner.Variable = var;
13353   if (ref)
13354     owner.setLocsFrom(ref);
13355   return true;
13356 }
13357 
13358 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
13359   while (true) {
13360     e = e->IgnoreParens();
13361     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
13362       switch (cast->getCastKind()) {
13363       case CK_BitCast:
13364       case CK_LValueBitCast:
13365       case CK_LValueToRValue:
13366       case CK_ARCReclaimReturnedObject:
13367         e = cast->getSubExpr();
13368         continue;
13369 
13370       default:
13371         return false;
13372       }
13373     }
13374 
13375     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
13376       ObjCIvarDecl *ivar = ref->getDecl();
13377       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
13378         return false;
13379 
13380       // Try to find a retain cycle in the base.
13381       if (!findRetainCycleOwner(S, ref->getBase(), owner))
13382         return false;
13383 
13384       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
13385       owner.Indirect = true;
13386       return true;
13387     }
13388 
13389     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
13390       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
13391       if (!var) return false;
13392       return considerVariable(var, ref, owner);
13393     }
13394 
13395     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
13396       if (member->isArrow()) return false;
13397 
13398       // Don't count this as an indirect ownership.
13399       e = member->getBase();
13400       continue;
13401     }
13402 
13403     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
13404       // Only pay attention to pseudo-objects on property references.
13405       ObjCPropertyRefExpr *pre
13406         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
13407                                               ->IgnoreParens());
13408       if (!pre) return false;
13409       if (pre->isImplicitProperty()) return false;
13410       ObjCPropertyDecl *property = pre->getExplicitProperty();
13411       if (!property->isRetaining() &&
13412           !(property->getPropertyIvarDecl() &&
13413             property->getPropertyIvarDecl()->getType()
13414               .getObjCLifetime() == Qualifiers::OCL_Strong))
13415           return false;
13416 
13417       owner.Indirect = true;
13418       if (pre->isSuperReceiver()) {
13419         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
13420         if (!owner.Variable)
13421           return false;
13422         owner.Loc = pre->getLocation();
13423         owner.Range = pre->getSourceRange();
13424         return true;
13425       }
13426       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
13427                               ->getSourceExpr());
13428       continue;
13429     }
13430 
13431     // Array ivars?
13432 
13433     return false;
13434   }
13435 }
13436 
13437 namespace {
13438 
13439   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
13440     ASTContext &Context;
13441     VarDecl *Variable;
13442     Expr *Capturer = nullptr;
13443     bool VarWillBeReased = false;
13444 
13445     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
13446         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
13447           Context(Context), Variable(variable) {}
13448 
13449     void VisitDeclRefExpr(DeclRefExpr *ref) {
13450       if (ref->getDecl() == Variable && !Capturer)
13451         Capturer = ref;
13452     }
13453 
13454     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
13455       if (Capturer) return;
13456       Visit(ref->getBase());
13457       if (Capturer && ref->isFreeIvar())
13458         Capturer = ref;
13459     }
13460 
13461     void VisitBlockExpr(BlockExpr *block) {
13462       // Look inside nested blocks
13463       if (block->getBlockDecl()->capturesVariable(Variable))
13464         Visit(block->getBlockDecl()->getBody());
13465     }
13466 
13467     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
13468       if (Capturer) return;
13469       if (OVE->getSourceExpr())
13470         Visit(OVE->getSourceExpr());
13471     }
13472 
13473     void VisitBinaryOperator(BinaryOperator *BinOp) {
13474       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
13475         return;
13476       Expr *LHS = BinOp->getLHS();
13477       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
13478         if (DRE->getDecl() != Variable)
13479           return;
13480         if (Expr *RHS = BinOp->getRHS()) {
13481           RHS = RHS->IgnoreParenCasts();
13482           llvm::APSInt Value;
13483           VarWillBeReased =
13484             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
13485         }
13486       }
13487     }
13488   };
13489 
13490 } // namespace
13491 
13492 /// Check whether the given argument is a block which captures a
13493 /// variable.
13494 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
13495   assert(owner.Variable && owner.Loc.isValid());
13496 
13497   e = e->IgnoreParenCasts();
13498 
13499   // Look through [^{...} copy] and Block_copy(^{...}).
13500   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
13501     Selector Cmd = ME->getSelector();
13502     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
13503       e = ME->getInstanceReceiver();
13504       if (!e)
13505         return nullptr;
13506       e = e->IgnoreParenCasts();
13507     }
13508   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
13509     if (CE->getNumArgs() == 1) {
13510       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
13511       if (Fn) {
13512         const IdentifierInfo *FnI = Fn->getIdentifier();
13513         if (FnI && FnI->isStr("_Block_copy")) {
13514           e = CE->getArg(0)->IgnoreParenCasts();
13515         }
13516       }
13517     }
13518   }
13519 
13520   BlockExpr *block = dyn_cast<BlockExpr>(e);
13521   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
13522     return nullptr;
13523 
13524   FindCaptureVisitor visitor(S.Context, owner.Variable);
13525   visitor.Visit(block->getBlockDecl()->getBody());
13526   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
13527 }
13528 
13529 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
13530                                 RetainCycleOwner &owner) {
13531   assert(capturer);
13532   assert(owner.Variable && owner.Loc.isValid());
13533 
13534   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
13535     << owner.Variable << capturer->getSourceRange();
13536   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
13537     << owner.Indirect << owner.Range;
13538 }
13539 
13540 /// Check for a keyword selector that starts with the word 'add' or
13541 /// 'set'.
13542 static bool isSetterLikeSelector(Selector sel) {
13543   if (sel.isUnarySelector()) return false;
13544 
13545   StringRef str = sel.getNameForSlot(0);
13546   while (!str.empty() && str.front() == '_') str = str.substr(1);
13547   if (str.startswith("set"))
13548     str = str.substr(3);
13549   else if (str.startswith("add")) {
13550     // Specially whitelist 'addOperationWithBlock:'.
13551     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
13552       return false;
13553     str = str.substr(3);
13554   }
13555   else
13556     return false;
13557 
13558   if (str.empty()) return true;
13559   return !isLowercase(str.front());
13560 }
13561 
13562 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
13563                                                     ObjCMessageExpr *Message) {
13564   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
13565                                                 Message->getReceiverInterface(),
13566                                                 NSAPI::ClassId_NSMutableArray);
13567   if (!IsMutableArray) {
13568     return None;
13569   }
13570 
13571   Selector Sel = Message->getSelector();
13572 
13573   Optional<NSAPI::NSArrayMethodKind> MKOpt =
13574     S.NSAPIObj->getNSArrayMethodKind(Sel);
13575   if (!MKOpt) {
13576     return None;
13577   }
13578 
13579   NSAPI::NSArrayMethodKind MK = *MKOpt;
13580 
13581   switch (MK) {
13582     case NSAPI::NSMutableArr_addObject:
13583     case NSAPI::NSMutableArr_insertObjectAtIndex:
13584     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
13585       return 0;
13586     case NSAPI::NSMutableArr_replaceObjectAtIndex:
13587       return 1;
13588 
13589     default:
13590       return None;
13591   }
13592 
13593   return None;
13594 }
13595 
13596 static
13597 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
13598                                                   ObjCMessageExpr *Message) {
13599   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
13600                                             Message->getReceiverInterface(),
13601                                             NSAPI::ClassId_NSMutableDictionary);
13602   if (!IsMutableDictionary) {
13603     return None;
13604   }
13605 
13606   Selector Sel = Message->getSelector();
13607 
13608   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
13609     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
13610   if (!MKOpt) {
13611     return None;
13612   }
13613 
13614   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
13615 
13616   switch (MK) {
13617     case NSAPI::NSMutableDict_setObjectForKey:
13618     case NSAPI::NSMutableDict_setValueForKey:
13619     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
13620       return 0;
13621 
13622     default:
13623       return None;
13624   }
13625 
13626   return None;
13627 }
13628 
13629 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13630   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13631                                                 Message->getReceiverInterface(),
13632                                                 NSAPI::ClassId_NSMutableSet);
13633 
13634   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13635                                             Message->getReceiverInterface(),
13636                                             NSAPI::ClassId_NSMutableOrderedSet);
13637   if (!IsMutableSet && !IsMutableOrderedSet) {
13638     return None;
13639   }
13640 
13641   Selector Sel = Message->getSelector();
13642 
13643   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13644   if (!MKOpt) {
13645     return None;
13646   }
13647 
13648   NSAPI::NSSetMethodKind MK = *MKOpt;
13649 
13650   switch (MK) {
13651     case NSAPI::NSMutableSet_addObject:
13652     case NSAPI::NSOrderedSet_setObjectAtIndex:
13653     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13654     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13655       return 0;
13656     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13657       return 1;
13658   }
13659 
13660   return None;
13661 }
13662 
13663 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13664   if (!Message->isInstanceMessage()) {
13665     return;
13666   }
13667 
13668   Optional<int> ArgOpt;
13669 
13670   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13671       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13672       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13673     return;
13674   }
13675 
13676   int ArgIndex = *ArgOpt;
13677 
13678   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13679   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13680     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13681   }
13682 
13683   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13684     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13685       if (ArgRE->isObjCSelfExpr()) {
13686         Diag(Message->getSourceRange().getBegin(),
13687              diag::warn_objc_circular_container)
13688           << ArgRE->getDecl() << StringRef("'super'");
13689       }
13690     }
13691   } else {
13692     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13693 
13694     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13695       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13696     }
13697 
13698     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13699       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13700         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13701           ValueDecl *Decl = ReceiverRE->getDecl();
13702           Diag(Message->getSourceRange().getBegin(),
13703                diag::warn_objc_circular_container)
13704             << Decl << Decl;
13705           if (!ArgRE->isObjCSelfExpr()) {
13706             Diag(Decl->getLocation(),
13707                  diag::note_objc_circular_container_declared_here)
13708               << Decl;
13709           }
13710         }
13711       }
13712     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13713       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13714         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13715           ObjCIvarDecl *Decl = IvarRE->getDecl();
13716           Diag(Message->getSourceRange().getBegin(),
13717                diag::warn_objc_circular_container)
13718             << Decl << Decl;
13719           Diag(Decl->getLocation(),
13720                diag::note_objc_circular_container_declared_here)
13721             << Decl;
13722         }
13723       }
13724     }
13725   }
13726 }
13727 
13728 /// Check a message send to see if it's likely to cause a retain cycle.
13729 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13730   // Only check instance methods whose selector looks like a setter.
13731   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13732     return;
13733 
13734   // Try to find a variable that the receiver is strongly owned by.
13735   RetainCycleOwner owner;
13736   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13737     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13738       return;
13739   } else {
13740     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13741     owner.Variable = getCurMethodDecl()->getSelfDecl();
13742     owner.Loc = msg->getSuperLoc();
13743     owner.Range = msg->getSuperLoc();
13744   }
13745 
13746   // Check whether the receiver is captured by any of the arguments.
13747   const ObjCMethodDecl *MD = msg->getMethodDecl();
13748   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13749     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13750       // noescape blocks should not be retained by the method.
13751       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13752         continue;
13753       return diagnoseRetainCycle(*this, capturer, owner);
13754     }
13755   }
13756 }
13757 
13758 /// Check a property assign to see if it's likely to cause a retain cycle.
13759 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13760   RetainCycleOwner owner;
13761   if (!findRetainCycleOwner(*this, receiver, owner))
13762     return;
13763 
13764   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13765     diagnoseRetainCycle(*this, capturer, owner);
13766 }
13767 
13768 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13769   RetainCycleOwner Owner;
13770   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13771     return;
13772 
13773   // Because we don't have an expression for the variable, we have to set the
13774   // location explicitly here.
13775   Owner.Loc = Var->getLocation();
13776   Owner.Range = Var->getSourceRange();
13777 
13778   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13779     diagnoseRetainCycle(*this, Capturer, Owner);
13780 }
13781 
13782 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13783                                      Expr *RHS, bool isProperty) {
13784   // Check if RHS is an Objective-C object literal, which also can get
13785   // immediately zapped in a weak reference.  Note that we explicitly
13786   // allow ObjCStringLiterals, since those are designed to never really die.
13787   RHS = RHS->IgnoreParenImpCasts();
13788 
13789   // This enum needs to match with the 'select' in
13790   // warn_objc_arc_literal_assign (off-by-1).
13791   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13792   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13793     return false;
13794 
13795   S.Diag(Loc, diag::warn_arc_literal_assign)
13796     << (unsigned) Kind
13797     << (isProperty ? 0 : 1)
13798     << RHS->getSourceRange();
13799 
13800   return true;
13801 }
13802 
13803 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13804                                     Qualifiers::ObjCLifetime LT,
13805                                     Expr *RHS, bool isProperty) {
13806   // Strip off any implicit cast added to get to the one ARC-specific.
13807   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13808     if (cast->getCastKind() == CK_ARCConsumeObject) {
13809       S.Diag(Loc, diag::warn_arc_retained_assign)
13810         << (LT == Qualifiers::OCL_ExplicitNone)
13811         << (isProperty ? 0 : 1)
13812         << RHS->getSourceRange();
13813       return true;
13814     }
13815     RHS = cast->getSubExpr();
13816   }
13817 
13818   if (LT == Qualifiers::OCL_Weak &&
13819       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13820     return true;
13821 
13822   return false;
13823 }
13824 
13825 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13826                               QualType LHS, Expr *RHS) {
13827   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13828 
13829   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13830     return false;
13831 
13832   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13833     return true;
13834 
13835   return false;
13836 }
13837 
13838 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13839                               Expr *LHS, Expr *RHS) {
13840   QualType LHSType;
13841   // PropertyRef on LHS type need be directly obtained from
13842   // its declaration as it has a PseudoType.
13843   ObjCPropertyRefExpr *PRE
13844     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13845   if (PRE && !PRE->isImplicitProperty()) {
13846     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13847     if (PD)
13848       LHSType = PD->getType();
13849   }
13850 
13851   if (LHSType.isNull())
13852     LHSType = LHS->getType();
13853 
13854   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13855 
13856   if (LT == Qualifiers::OCL_Weak) {
13857     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13858       getCurFunction()->markSafeWeakUse(LHS);
13859   }
13860 
13861   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13862     return;
13863 
13864   // FIXME. Check for other life times.
13865   if (LT != Qualifiers::OCL_None)
13866     return;
13867 
13868   if (PRE) {
13869     if (PRE->isImplicitProperty())
13870       return;
13871     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13872     if (!PD)
13873       return;
13874 
13875     unsigned Attributes = PD->getPropertyAttributes();
13876     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13877       // when 'assign' attribute was not explicitly specified
13878       // by user, ignore it and rely on property type itself
13879       // for lifetime info.
13880       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13881       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13882           LHSType->isObjCRetainableType())
13883         return;
13884 
13885       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13886         if (cast->getCastKind() == CK_ARCConsumeObject) {
13887           Diag(Loc, diag::warn_arc_retained_property_assign)
13888           << RHS->getSourceRange();
13889           return;
13890         }
13891         RHS = cast->getSubExpr();
13892       }
13893     }
13894     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13895       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13896         return;
13897     }
13898   }
13899 }
13900 
13901 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13902 
13903 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13904                                         SourceLocation StmtLoc,
13905                                         const NullStmt *Body) {
13906   // Do not warn if the body is a macro that expands to nothing, e.g:
13907   //
13908   // #define CALL(x)
13909   // if (condition)
13910   //   CALL(0);
13911   if (Body->hasLeadingEmptyMacro())
13912     return false;
13913 
13914   // Get line numbers of statement and body.
13915   bool StmtLineInvalid;
13916   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13917                                                       &StmtLineInvalid);
13918   if (StmtLineInvalid)
13919     return false;
13920 
13921   bool BodyLineInvalid;
13922   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13923                                                       &BodyLineInvalid);
13924   if (BodyLineInvalid)
13925     return false;
13926 
13927   // Warn if null statement and body are on the same line.
13928   if (StmtLine != BodyLine)
13929     return false;
13930 
13931   return true;
13932 }
13933 
13934 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13935                                  const Stmt *Body,
13936                                  unsigned DiagID) {
13937   // Since this is a syntactic check, don't emit diagnostic for template
13938   // instantiations, this just adds noise.
13939   if (CurrentInstantiationScope)
13940     return;
13941 
13942   // The body should be a null statement.
13943   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13944   if (!NBody)
13945     return;
13946 
13947   // Do the usual checks.
13948   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13949     return;
13950 
13951   Diag(NBody->getSemiLoc(), DiagID);
13952   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13953 }
13954 
13955 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13956                                  const Stmt *PossibleBody) {
13957   assert(!CurrentInstantiationScope); // Ensured by caller
13958 
13959   SourceLocation StmtLoc;
13960   const Stmt *Body;
13961   unsigned DiagID;
13962   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13963     StmtLoc = FS->getRParenLoc();
13964     Body = FS->getBody();
13965     DiagID = diag::warn_empty_for_body;
13966   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13967     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13968     Body = WS->getBody();
13969     DiagID = diag::warn_empty_while_body;
13970   } else
13971     return; // Neither `for' nor `while'.
13972 
13973   // The body should be a null statement.
13974   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13975   if (!NBody)
13976     return;
13977 
13978   // Skip expensive checks if diagnostic is disabled.
13979   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13980     return;
13981 
13982   // Do the usual checks.
13983   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13984     return;
13985 
13986   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13987   // noise level low, emit diagnostics only if for/while is followed by a
13988   // CompoundStmt, e.g.:
13989   //    for (int i = 0; i < n; i++);
13990   //    {
13991   //      a(i);
13992   //    }
13993   // or if for/while is followed by a statement with more indentation
13994   // than for/while itself:
13995   //    for (int i = 0; i < n; i++);
13996   //      a(i);
13997   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13998   if (!ProbableTypo) {
13999     bool BodyColInvalid;
14000     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
14001         PossibleBody->getBeginLoc(), &BodyColInvalid);
14002     if (BodyColInvalid)
14003       return;
14004 
14005     bool StmtColInvalid;
14006     unsigned StmtCol =
14007         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
14008     if (StmtColInvalid)
14009       return;
14010 
14011     if (BodyCol > StmtCol)
14012       ProbableTypo = true;
14013   }
14014 
14015   if (ProbableTypo) {
14016     Diag(NBody->getSemiLoc(), DiagID);
14017     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
14018   }
14019 }
14020 
14021 //===--- CHECK: Warn on self move with std::move. -------------------------===//
14022 
14023 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
14024 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
14025                              SourceLocation OpLoc) {
14026   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
14027     return;
14028 
14029   if (inTemplateInstantiation())
14030     return;
14031 
14032   // Strip parens and casts away.
14033   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14034   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14035 
14036   // Check for a call expression
14037   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
14038   if (!CE || CE->getNumArgs() != 1)
14039     return;
14040 
14041   // Check for a call to std::move
14042   if (!CE->isCallToStdMove())
14043     return;
14044 
14045   // Get argument from std::move
14046   RHSExpr = CE->getArg(0);
14047 
14048   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14049   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14050 
14051   // Two DeclRefExpr's, check that the decls are the same.
14052   if (LHSDeclRef && RHSDeclRef) {
14053     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14054       return;
14055     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14056         RHSDeclRef->getDecl()->getCanonicalDecl())
14057       return;
14058 
14059     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14060                                         << LHSExpr->getSourceRange()
14061                                         << RHSExpr->getSourceRange();
14062     return;
14063   }
14064 
14065   // Member variables require a different approach to check for self moves.
14066   // MemberExpr's are the same if every nested MemberExpr refers to the same
14067   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
14068   // the base Expr's are CXXThisExpr's.
14069   const Expr *LHSBase = LHSExpr;
14070   const Expr *RHSBase = RHSExpr;
14071   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
14072   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
14073   if (!LHSME || !RHSME)
14074     return;
14075 
14076   while (LHSME && RHSME) {
14077     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
14078         RHSME->getMemberDecl()->getCanonicalDecl())
14079       return;
14080 
14081     LHSBase = LHSME->getBase();
14082     RHSBase = RHSME->getBase();
14083     LHSME = dyn_cast<MemberExpr>(LHSBase);
14084     RHSME = dyn_cast<MemberExpr>(RHSBase);
14085   }
14086 
14087   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
14088   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
14089   if (LHSDeclRef && RHSDeclRef) {
14090     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
14091       return;
14092     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
14093         RHSDeclRef->getDecl()->getCanonicalDecl())
14094       return;
14095 
14096     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14097                                         << LHSExpr->getSourceRange()
14098                                         << RHSExpr->getSourceRange();
14099     return;
14100   }
14101 
14102   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
14103     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
14104                                         << LHSExpr->getSourceRange()
14105                                         << RHSExpr->getSourceRange();
14106 }
14107 
14108 //===--- Layout compatibility ----------------------------------------------//
14109 
14110 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
14111 
14112 /// Check if two enumeration types are layout-compatible.
14113 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
14114   // C++11 [dcl.enum] p8:
14115   // Two enumeration types are layout-compatible if they have the same
14116   // underlying type.
14117   return ED1->isComplete() && ED2->isComplete() &&
14118          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
14119 }
14120 
14121 /// Check if two fields are layout-compatible.
14122 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
14123                                FieldDecl *Field2) {
14124   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
14125     return false;
14126 
14127   if (Field1->isBitField() != Field2->isBitField())
14128     return false;
14129 
14130   if (Field1->isBitField()) {
14131     // Make sure that the bit-fields are the same length.
14132     unsigned Bits1 = Field1->getBitWidthValue(C);
14133     unsigned Bits2 = Field2->getBitWidthValue(C);
14134 
14135     if (Bits1 != Bits2)
14136       return false;
14137   }
14138 
14139   return true;
14140 }
14141 
14142 /// Check if two standard-layout structs are layout-compatible.
14143 /// (C++11 [class.mem] p17)
14144 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
14145                                      RecordDecl *RD2) {
14146   // If both records are C++ classes, check that base classes match.
14147   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
14148     // If one of records is a CXXRecordDecl we are in C++ mode,
14149     // thus the other one is a CXXRecordDecl, too.
14150     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
14151     // Check number of base classes.
14152     if (D1CXX->getNumBases() != D2CXX->getNumBases())
14153       return false;
14154 
14155     // Check the base classes.
14156     for (CXXRecordDecl::base_class_const_iterator
14157                Base1 = D1CXX->bases_begin(),
14158            BaseEnd1 = D1CXX->bases_end(),
14159               Base2 = D2CXX->bases_begin();
14160          Base1 != BaseEnd1;
14161          ++Base1, ++Base2) {
14162       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
14163         return false;
14164     }
14165   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
14166     // If only RD2 is a C++ class, it should have zero base classes.
14167     if (D2CXX->getNumBases() > 0)
14168       return false;
14169   }
14170 
14171   // Check the fields.
14172   RecordDecl::field_iterator Field2 = RD2->field_begin(),
14173                              Field2End = RD2->field_end(),
14174                              Field1 = RD1->field_begin(),
14175                              Field1End = RD1->field_end();
14176   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
14177     if (!isLayoutCompatible(C, *Field1, *Field2))
14178       return false;
14179   }
14180   if (Field1 != Field1End || Field2 != Field2End)
14181     return false;
14182 
14183   return true;
14184 }
14185 
14186 /// Check if two standard-layout unions are layout-compatible.
14187 /// (C++11 [class.mem] p18)
14188 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
14189                                     RecordDecl *RD2) {
14190   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
14191   for (auto *Field2 : RD2->fields())
14192     UnmatchedFields.insert(Field2);
14193 
14194   for (auto *Field1 : RD1->fields()) {
14195     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
14196         I = UnmatchedFields.begin(),
14197         E = UnmatchedFields.end();
14198 
14199     for ( ; I != E; ++I) {
14200       if (isLayoutCompatible(C, Field1, *I)) {
14201         bool Result = UnmatchedFields.erase(*I);
14202         (void) Result;
14203         assert(Result);
14204         break;
14205       }
14206     }
14207     if (I == E)
14208       return false;
14209   }
14210 
14211   return UnmatchedFields.empty();
14212 }
14213 
14214 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
14215                                RecordDecl *RD2) {
14216   if (RD1->isUnion() != RD2->isUnion())
14217     return false;
14218 
14219   if (RD1->isUnion())
14220     return isLayoutCompatibleUnion(C, RD1, RD2);
14221   else
14222     return isLayoutCompatibleStruct(C, RD1, RD2);
14223 }
14224 
14225 /// Check if two types are layout-compatible in C++11 sense.
14226 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
14227   if (T1.isNull() || T2.isNull())
14228     return false;
14229 
14230   // C++11 [basic.types] p11:
14231   // If two types T1 and T2 are the same type, then T1 and T2 are
14232   // layout-compatible types.
14233   if (C.hasSameType(T1, T2))
14234     return true;
14235 
14236   T1 = T1.getCanonicalType().getUnqualifiedType();
14237   T2 = T2.getCanonicalType().getUnqualifiedType();
14238 
14239   const Type::TypeClass TC1 = T1->getTypeClass();
14240   const Type::TypeClass TC2 = T2->getTypeClass();
14241 
14242   if (TC1 != TC2)
14243     return false;
14244 
14245   if (TC1 == Type::Enum) {
14246     return isLayoutCompatible(C,
14247                               cast<EnumType>(T1)->getDecl(),
14248                               cast<EnumType>(T2)->getDecl());
14249   } else if (TC1 == Type::Record) {
14250     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
14251       return false;
14252 
14253     return isLayoutCompatible(C,
14254                               cast<RecordType>(T1)->getDecl(),
14255                               cast<RecordType>(T2)->getDecl());
14256   }
14257 
14258   return false;
14259 }
14260 
14261 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
14262 
14263 /// Given a type tag expression find the type tag itself.
14264 ///
14265 /// \param TypeExpr Type tag expression, as it appears in user's code.
14266 ///
14267 /// \param VD Declaration of an identifier that appears in a type tag.
14268 ///
14269 /// \param MagicValue Type tag magic value.
14270 ///
14271 /// \param isConstantEvaluated wether the evalaution should be performed in
14272 
14273 /// constant context.
14274 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
14275                             const ValueDecl **VD, uint64_t *MagicValue,
14276                             bool isConstantEvaluated) {
14277   while(true) {
14278     if (!TypeExpr)
14279       return false;
14280 
14281     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
14282 
14283     switch (TypeExpr->getStmtClass()) {
14284     case Stmt::UnaryOperatorClass: {
14285       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
14286       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
14287         TypeExpr = UO->getSubExpr();
14288         continue;
14289       }
14290       return false;
14291     }
14292 
14293     case Stmt::DeclRefExprClass: {
14294       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
14295       *VD = DRE->getDecl();
14296       return true;
14297     }
14298 
14299     case Stmt::IntegerLiteralClass: {
14300       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
14301       llvm::APInt MagicValueAPInt = IL->getValue();
14302       if (MagicValueAPInt.getActiveBits() <= 64) {
14303         *MagicValue = MagicValueAPInt.getZExtValue();
14304         return true;
14305       } else
14306         return false;
14307     }
14308 
14309     case Stmt::BinaryConditionalOperatorClass:
14310     case Stmt::ConditionalOperatorClass: {
14311       const AbstractConditionalOperator *ACO =
14312           cast<AbstractConditionalOperator>(TypeExpr);
14313       bool Result;
14314       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
14315                                                      isConstantEvaluated)) {
14316         if (Result)
14317           TypeExpr = ACO->getTrueExpr();
14318         else
14319           TypeExpr = ACO->getFalseExpr();
14320         continue;
14321       }
14322       return false;
14323     }
14324 
14325     case Stmt::BinaryOperatorClass: {
14326       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
14327       if (BO->getOpcode() == BO_Comma) {
14328         TypeExpr = BO->getRHS();
14329         continue;
14330       }
14331       return false;
14332     }
14333 
14334     default:
14335       return false;
14336     }
14337   }
14338 }
14339 
14340 /// Retrieve the C type corresponding to type tag TypeExpr.
14341 ///
14342 /// \param TypeExpr Expression that specifies a type tag.
14343 ///
14344 /// \param MagicValues Registered magic values.
14345 ///
14346 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
14347 ///        kind.
14348 ///
14349 /// \param TypeInfo Information about the corresponding C type.
14350 ///
14351 /// \param isConstantEvaluated wether the evalaution should be performed in
14352 /// constant context.
14353 ///
14354 /// \returns true if the corresponding C type was found.
14355 static bool GetMatchingCType(
14356     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
14357     const ASTContext &Ctx,
14358     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
14359         *MagicValues,
14360     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
14361     bool isConstantEvaluated) {
14362   FoundWrongKind = false;
14363 
14364   // Variable declaration that has type_tag_for_datatype attribute.
14365   const ValueDecl *VD = nullptr;
14366 
14367   uint64_t MagicValue;
14368 
14369   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
14370     return false;
14371 
14372   if (VD) {
14373     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
14374       if (I->getArgumentKind() != ArgumentKind) {
14375         FoundWrongKind = true;
14376         return false;
14377       }
14378       TypeInfo.Type = I->getMatchingCType();
14379       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
14380       TypeInfo.MustBeNull = I->getMustBeNull();
14381       return true;
14382     }
14383     return false;
14384   }
14385 
14386   if (!MagicValues)
14387     return false;
14388 
14389   llvm::DenseMap<Sema::TypeTagMagicValue,
14390                  Sema::TypeTagData>::const_iterator I =
14391       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
14392   if (I == MagicValues->end())
14393     return false;
14394 
14395   TypeInfo = I->second;
14396   return true;
14397 }
14398 
14399 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
14400                                       uint64_t MagicValue, QualType Type,
14401                                       bool LayoutCompatible,
14402                                       bool MustBeNull) {
14403   if (!TypeTagForDatatypeMagicValues)
14404     TypeTagForDatatypeMagicValues.reset(
14405         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
14406 
14407   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
14408   (*TypeTagForDatatypeMagicValues)[Magic] =
14409       TypeTagData(Type, LayoutCompatible, MustBeNull);
14410 }
14411 
14412 static bool IsSameCharType(QualType T1, QualType T2) {
14413   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
14414   if (!BT1)
14415     return false;
14416 
14417   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
14418   if (!BT2)
14419     return false;
14420 
14421   BuiltinType::Kind T1Kind = BT1->getKind();
14422   BuiltinType::Kind T2Kind = BT2->getKind();
14423 
14424   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
14425          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
14426          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
14427          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
14428 }
14429 
14430 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
14431                                     const ArrayRef<const Expr *> ExprArgs,
14432                                     SourceLocation CallSiteLoc) {
14433   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
14434   bool IsPointerAttr = Attr->getIsPointer();
14435 
14436   // Retrieve the argument representing the 'type_tag'.
14437   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
14438   if (TypeTagIdxAST >= ExprArgs.size()) {
14439     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14440         << 0 << Attr->getTypeTagIdx().getSourceIndex();
14441     return;
14442   }
14443   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
14444   bool FoundWrongKind;
14445   TypeTagData TypeInfo;
14446   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
14447                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
14448                         TypeInfo, isConstantEvaluated())) {
14449     if (FoundWrongKind)
14450       Diag(TypeTagExpr->getExprLoc(),
14451            diag::warn_type_tag_for_datatype_wrong_kind)
14452         << TypeTagExpr->getSourceRange();
14453     return;
14454   }
14455 
14456   // Retrieve the argument representing the 'arg_idx'.
14457   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
14458   if (ArgumentIdxAST >= ExprArgs.size()) {
14459     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
14460         << 1 << Attr->getArgumentIdx().getSourceIndex();
14461     return;
14462   }
14463   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
14464   if (IsPointerAttr) {
14465     // Skip implicit cast of pointer to `void *' (as a function argument).
14466     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
14467       if (ICE->getType()->isVoidPointerType() &&
14468           ICE->getCastKind() == CK_BitCast)
14469         ArgumentExpr = ICE->getSubExpr();
14470   }
14471   QualType ArgumentType = ArgumentExpr->getType();
14472 
14473   // Passing a `void*' pointer shouldn't trigger a warning.
14474   if (IsPointerAttr && ArgumentType->isVoidPointerType())
14475     return;
14476 
14477   if (TypeInfo.MustBeNull) {
14478     // Type tag with matching void type requires a null pointer.
14479     if (!ArgumentExpr->isNullPointerConstant(Context,
14480                                              Expr::NPC_ValueDependentIsNotNull)) {
14481       Diag(ArgumentExpr->getExprLoc(),
14482            diag::warn_type_safety_null_pointer_required)
14483           << ArgumentKind->getName()
14484           << ArgumentExpr->getSourceRange()
14485           << TypeTagExpr->getSourceRange();
14486     }
14487     return;
14488   }
14489 
14490   QualType RequiredType = TypeInfo.Type;
14491   if (IsPointerAttr)
14492     RequiredType = Context.getPointerType(RequiredType);
14493 
14494   bool mismatch = false;
14495   if (!TypeInfo.LayoutCompatible) {
14496     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
14497 
14498     // C++11 [basic.fundamental] p1:
14499     // Plain char, signed char, and unsigned char are three distinct types.
14500     //
14501     // But we treat plain `char' as equivalent to `signed char' or `unsigned
14502     // char' depending on the current char signedness mode.
14503     if (mismatch)
14504       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
14505                                            RequiredType->getPointeeType())) ||
14506           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
14507         mismatch = false;
14508   } else
14509     if (IsPointerAttr)
14510       mismatch = !isLayoutCompatible(Context,
14511                                      ArgumentType->getPointeeType(),
14512                                      RequiredType->getPointeeType());
14513     else
14514       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
14515 
14516   if (mismatch)
14517     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
14518         << ArgumentType << ArgumentKind
14519         << TypeInfo.LayoutCompatible << RequiredType
14520         << ArgumentExpr->getSourceRange()
14521         << TypeTagExpr->getSourceRange();
14522 }
14523 
14524 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
14525                                          CharUnits Alignment) {
14526   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
14527 }
14528 
14529 void Sema::DiagnoseMisalignedMembers() {
14530   for (MisalignedMember &m : MisalignedMembers) {
14531     const NamedDecl *ND = m.RD;
14532     if (ND->getName().empty()) {
14533       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
14534         ND = TD;
14535     }
14536     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
14537         << m.MD << ND << m.E->getSourceRange();
14538   }
14539   MisalignedMembers.clear();
14540 }
14541 
14542 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
14543   E = E->IgnoreParens();
14544   if (!T->isPointerType() && !T->isIntegerType())
14545     return;
14546   if (isa<UnaryOperator>(E) &&
14547       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
14548     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
14549     if (isa<MemberExpr>(Op)) {
14550       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
14551       if (MA != MisalignedMembers.end() &&
14552           (T->isIntegerType() ||
14553            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
14554                                    Context.getTypeAlignInChars(
14555                                        T->getPointeeType()) <= MA->Alignment))))
14556         MisalignedMembers.erase(MA);
14557     }
14558   }
14559 }
14560 
14561 void Sema::RefersToMemberWithReducedAlignment(
14562     Expr *E,
14563     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
14564         Action) {
14565   const auto *ME = dyn_cast<MemberExpr>(E);
14566   if (!ME)
14567     return;
14568 
14569   // No need to check expressions with an __unaligned-qualified type.
14570   if (E->getType().getQualifiers().hasUnaligned())
14571     return;
14572 
14573   // For a chain of MemberExpr like "a.b.c.d" this list
14574   // will keep FieldDecl's like [d, c, b].
14575   SmallVector<FieldDecl *, 4> ReverseMemberChain;
14576   const MemberExpr *TopME = nullptr;
14577   bool AnyIsPacked = false;
14578   do {
14579     QualType BaseType = ME->getBase()->getType();
14580     if (ME->isArrow())
14581       BaseType = BaseType->getPointeeType();
14582     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
14583     if (RD->isInvalidDecl())
14584       return;
14585 
14586     ValueDecl *MD = ME->getMemberDecl();
14587     auto *FD = dyn_cast<FieldDecl>(MD);
14588     // We do not care about non-data members.
14589     if (!FD || FD->isInvalidDecl())
14590       return;
14591 
14592     AnyIsPacked =
14593         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
14594     ReverseMemberChain.push_back(FD);
14595 
14596     TopME = ME;
14597     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
14598   } while (ME);
14599   assert(TopME && "We did not compute a topmost MemberExpr!");
14600 
14601   // Not the scope of this diagnostic.
14602   if (!AnyIsPacked)
14603     return;
14604 
14605   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
14606   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
14607   // TODO: The innermost base of the member expression may be too complicated.
14608   // For now, just disregard these cases. This is left for future
14609   // improvement.
14610   if (!DRE && !isa<CXXThisExpr>(TopBase))
14611       return;
14612 
14613   // Alignment expected by the whole expression.
14614   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
14615 
14616   // No need to do anything else with this case.
14617   if (ExpectedAlignment.isOne())
14618     return;
14619 
14620   // Synthesize offset of the whole access.
14621   CharUnits Offset;
14622   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
14623        I++) {
14624     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
14625   }
14626 
14627   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
14628   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
14629       ReverseMemberChain.back()->getParent()->getTypeForDecl());
14630 
14631   // The base expression of the innermost MemberExpr may give
14632   // stronger guarantees than the class containing the member.
14633   if (DRE && !TopME->isArrow()) {
14634     const ValueDecl *VD = DRE->getDecl();
14635     if (!VD->getType()->isReferenceType())
14636       CompleteObjectAlignment =
14637           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14638   }
14639 
14640   // Check if the synthesized offset fulfills the alignment.
14641   if (Offset % ExpectedAlignment != 0 ||
14642       // It may fulfill the offset it but the effective alignment may still be
14643       // lower than the expected expression alignment.
14644       CompleteObjectAlignment < ExpectedAlignment) {
14645     // If this happens, we want to determine a sensible culprit of this.
14646     // Intuitively, watching the chain of member expressions from right to
14647     // left, we start with the required alignment (as required by the field
14648     // type) but some packed attribute in that chain has reduced the alignment.
14649     // It may happen that another packed structure increases it again. But if
14650     // we are here such increase has not been enough. So pointing the first
14651     // FieldDecl that either is packed or else its RecordDecl is,
14652     // seems reasonable.
14653     FieldDecl *FD = nullptr;
14654     CharUnits Alignment;
14655     for (FieldDecl *FDI : ReverseMemberChain) {
14656       if (FDI->hasAttr<PackedAttr>() ||
14657           FDI->getParent()->hasAttr<PackedAttr>()) {
14658         FD = FDI;
14659         Alignment = std::min(
14660             Context.getTypeAlignInChars(FD->getType()),
14661             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14662         break;
14663       }
14664     }
14665     assert(FD && "We did not find a packed FieldDecl!");
14666     Action(E, FD->getParent(), FD, Alignment);
14667   }
14668 }
14669 
14670 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14671   using namespace std::placeholders;
14672 
14673   RefersToMemberWithReducedAlignment(
14674       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14675                      _2, _3, _4));
14676 }
14677